**docs/I18N.md was wrong in a way that would waste a contributor's afternoon.** It said adding a locale to `SUPPORTED_LANGUAGES` was "the only registration step". It is one of four, and the missing ones fail differently: the `SupportedLanguage` union is a compile error, `MULTILINGUAL_TAGS` is a compile error, but `detectBrowserLanguage`'s own hardcoded copy of the list fails *silently* — the language works and simply never auto-selects for a visitor whose browser is set to it. Also noted: `SUPPORTED_LANGUAGES` is not type-bound to the union and every consumer casts, so a mismatch compiles cleanly. Also documents the `--copy-english` / `--force` flags on the locale generator, which only started existing in v0.35.0 despite having been advertised in package.json since v0.1. Elsewhere: - **DEVELOPMENT.md** — the five new npm scripts, including why `format:check` excludes markdown and locale JSON, and why `typecheck:all` exists. - **TECH-SPEC.md** — the real CI job, a new Field Limits section, and how over-limit enforcement derives from the engine's long-ignored `warnings`. - **ARCHITECTURE.md** — the settings→engine mapping and its two guards, the two-source validation state, and an honest note that the first Strict Mode implementation typechecked, passed tests, and did nothing. - **FEATURES.md** — the settings table still listed `Default Genre` and `Auto-save Draft`, removed in v0.22.0 and v0.3. Replaced, plus a guardrails section. - **README.md** — guardrails in the feature list, and a link to the wiki. The wiki itself (12 pages: quick start, glossary, field reference, guardrails, batch/social, import-export, languages, privacy, troubleshooting, FAQ, release process) is published separately — it lives in its own repository. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
20 KiB
Architecture Document
YTDescGen — Technical Architecture
1. High-Level Architecture
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────────┐ │
│ │ Editor │ │ Output │ │ Profiles │ │ Batch / History│ │
│ │ Page │ │ Page │ │ Page │ │ Pages │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬────────┘ │
│ │ │ │ │ │
│ ┌────┴─────────────┴────────────┴───────────────┴────────┐ │
│ │ Shared Components (ui/, editor/, output/) │ │
│ └────────────────────────────┬────────────────────────────┘ │
├───────────────────────────────┼──────────────────────────────┤
│ Application Layer │
│ ┌────────────┐ ┌───────────┴──────────┐ ┌──────────────┐ │
│ │ Hooks │ │ State (Zustand) │ │ i18next │ │
│ │ useGenerate │ │ editor / profile / │ │ locales/ │ │
│ │ useClipboard│ │ preset / history / │ │ en/vi/ja/ │ │
│ │ useCharCount│ │ settings │ │ es/ko/zh │ │
│ └──────┬─────┘ └───────────┬───────────┘ └──────┬───────┘ │
├─────────┼────────────────────┼──────────────────────┼────────┤
│ Core Engine Layer │
│ ┌──────┴────────────────────┴──────────────────────┴──────┐ │
│ │ engine/ (Pure TypeScript) │ │
│ │ ┌──────────────┐ ┌──────────────────┐ ┌──────────────┐ │ │
│ │ │ title-builder│ │description-builder│ │ tag-generator│ │ │
│ │ └──────┬───────┘ └────────┬─────────┘ └──────┬───────┘ │ │
│ │ └──────────────────┼───────────────────┘ │ │
│ │ ┌────────┴────────┐ │ │
│ │ │template-renderer│ │ │
│ │ └─────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
├──────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ ┌────────────────┐ ┌───────────────┐ ┌─────────────────┐ │
│ │ localStorage │ │ File System │ │ Clipboard API │ │
│ │ (Web) │ │ (Tauri) │ │ │ │
│ └────────────────┘ └───────────────┘ └─────────────────┘ │
└──────────────────────────────────────────────────────────────┘
Error pages (v0.27): components/errors/ holds a reusable ErrorPage
(404/403/419/500/offline/runtime) driven by the pure config/error-pages.ts
map. The dedicated error routes (/403, /419, /500, /offline, catch-all
*) are declared as siblings of the AppShell route group in App.tsx, so
they render full-screen with no Sidebar/Header. ErrorPage is router-agnostic
(hash anchors + history.back()) so the root ErrorBoundary — mounted outside
HashRouter in main.tsx — can reuse it as its crash fallback.
2. Core Engine Design
Engine module chứa toàn bộ logic generate — zero framework dependency. Mọi function đều pure: input → string.
2.1 Type Definitions (engine/types.ts)
// ── Video Types ──
type VideoType =
| "full" // Full Gameplay
| "part" // Gameplay Part X
| "boss" // Boss Fight
| "boss_nohit" // Boss No Hit
| "ending" // Ending / All Endings
| "speedrun" // Speedrun
| "100percent" // 100% Completion
| "dlc" // DLC Content
| "newgame_plus" // New Game+
| "challenge" // Challenge Run
| "side_quest" // Side Quest / Optional Content
| "secret" // Secret / Hidden Content
| "comparison" // Graphics / Version Comparison
| "guide"; // Silent Guide / Walkthrough
// ── Genre ──
type Genre =
| "action" | "horror" | "rpg" | "fps" | "openworld"
| "indie" | "soulslike" | "racing" | "story" | "simulation"
| "fighting" | "stealth" | "survival_craft" | "mmo"
| "rhythm" | "puzzle" | "roguelike" | "metroidvania"
| "tower_defense" | "card_game" | "battle_royale"
| "crpg" | "tactical" | "space" | "farming";
// ── Supported Languages ──
type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh"
| "fr" | "de" | "pt" | "ru" | "th" | "ar";
// ── Input State ──
interface GeneratorInput {
// Core
videoType: VideoType;
language: SupportedLanguage;
genre: Genre;
// Game info
gameName: string;
gameNameLocalized?: Record<SupportedLanguage, string>; // optional localized game name
channelName: string;
platform: string;
// Video type-specific
partNumber?: string;
bossName?: string;
dlcName?: string;
challengeName?: string;
// Video settings
resolution?: string;
fps?: string;
graphicsPreset?: string;
// Content
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
// Warnings
spoilerWarning: boolean;
matureWarning: boolean;
// Links
storeLinks: Record<string, string>;
social: Record<string, string>;
rig: Record<string, string>;
}
// ── Output ──
interface GeneratorOutput {
title: string;
description: string;
tags: string[];
tagString: string;
charCounts: {
title: number;
description: number;
tags: number;
};
warnings: string[]; // e.g. "Tags exceed 500 character limit"
}
2.2 Template Architecture
Templates sử dụng data-driven approach thay vì hardcode string concatenation:
// i18n/locales/en/templates.json
{
"title": {
"separator": " — ",
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "Part {{partNumber}}",
"boss": "{{bossName}} Boss Fight",
"boss_nohit": "{{bossName}} Boss No Hit",
"ending": "Ending",
"speedrun": "Speedrun",
"100percent": "100% Completion",
"dlc": "{{dlcName}} DLC",
"newgame_plus": "New Game+",
"challenge": "{{challengeName}} Challenge"
}
},
"description": {
"intro": {
"full": "This video features the full gameplay of {{gameName}} on {{channelName}}.",
"part": "This video features Part {{partNumber}} of {{gameName}} on {{channelName}}."
},
"noCommentaryLine": "No Commentary — pure gameplay for your enjoyment.",
"sections": {
"timestamps": "⏱ TIMESTAMPS",
"storeLinks": "🎮 GET THE GAME",
"videoSettings": "🖥 VIDEO SETTINGS: {{settings}}",
"rig": "💻 MY RIG",
"spoilerWarning": "⚠️ SPOILER WARNING: This video contains spoilers.",
"matureWarning": "🔞 MATURE CONTENT (18+): Contains violence / strong language.",
"playlist": "▶️ Watch the full series: {{link}}",
"contact": "📧 Business inquiries: {{email}}",
"cta": "👍 Like | 🔔 Subscribe | ↗️ Share"
}
}
}
2.3 Tag Generator Architecture
TagGenerator Pipeline:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Core Pool│───→│Genre Pool│───→│ Platform │───→│ Quality │
│ (always) │ │(by genre)│ │ Pool │ │ Pool │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
│ │ │ │
└───────────────┴──────────────┴───────────────┘
│
┌─────────┴─────────┐
│ VideoType Pool │
│ (boss, speedrun…) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Multilingual Pool │
│ (JA, VI, ES…) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Trending Pool │
│ (year-based) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Dedup (Set) │
│ + Priority Sort │
│ + 500 char trim │
└───────────────────┘
Tag pools là registry pattern — thêm genre mới chỉ cần thêm 1 entry:
// engine/tag-generator.ts
const TAG_REGISTRY: Record<Genre, (gameName: string) => string[]> = {
action: (g) => [`${g} action`, "action game no commentary", "action adventure gameplay"],
horror: (g) => [`${g} horror`, "horror game no commentary", "survival horror gameplay"],
// ... thêm genre ở đây
};
3. State Architecture
Zustand Stores:
┌───────────────────────────────────────────────┐
│ EditorStore │
│ - videoType, language, genre │
│ - gameName, channelName, platform │
│ - timestamps, storeLinks, rig, social │
│ - spoilerWarning, matureWarning │
│ Middleware: none (ephemeral per session) │
│ + persist: auto-save draft (debounced) │
├───────────────────────────────────────────────┤
│ ProfileStore │
│ - profiles: Profile[] │
│ - activeProfileId: string | null │
│ Middleware: persist (localStorage) │
├───────────────────────────────────────────────┤
│ PresetStore │
│ - gamePresets: GamePreset[] │
│ Middleware: persist (localStorage) │
├───────────────────────────────────────────────┤
│ HistoryStore │
│ - entries: HistoryEntry[] (max 100) │
│ Middleware: persist (localStorage, pruned) │
├───────────────────────────────────────────────┤
│ SettingsStore │
│ - theme: "dark" | "light" │
│ - appLanguage / defaultOutputLanguage │
│ - strictMode, settingsAccordionState (v12) │
│ - (flags: quality badge / copyright / ...) │
│ Middleware: persist (localStorage + file) │
├───────────────────────────────────────────────┤
│ PendingInvalidStore (0.35) │
│ - entries: Record<fieldId, PendingInvalid> │
│ Middleware: NONE — in-flight typing, not data │
└───────────────────────────────────────────────┘
Settings → engine options
renderAll is called from three places (the Output hook, the multi-language
Output hook, BatchPage). Each used to hand-copy the same twelve settings fields
into an options object, and they had drifted — BatchPage's copy silently omitted
splitContactEmail and showThirdPartyAds, so Batch rendered a different
description than Output from identical data.
src/hooks/use-render-options.ts is now the single mapping, with two guards:
- Compile-time —
buildRenderOptionsbuilds aRequired<SettingsRenderOptions>, so omitting a key is a type error. - Runtime —
tests/hooks/render-options-parity.test.tsdiffs the produced keys againstSETTINGS_DERIVED_RENDER_KEYSin both directions.
RenderOptions is split accordingly: SettingsRenderOptions (from the user)
plus RenderOptionOverrides (tEn, bilingualContentBlocks — decided per call
site, since Output wants bilingual content blocks and Batch does not).
Validation state
Two sources, unioned by useStrictBlock, because neither alone is sufficient:
| Source | Catches | Why it's needed |
|---|---|---|
collectEditorIssues (pure, over EditorData) |
Saved values that fail validation | Bad data from imports — ValidatedInput refuses to commit invalid text, so imports are the main way it gets in |
PendingInvalidStore |
Typed text that is invalid and therefore not saved | Otherwise a field showing a red error is invisible to every gate, because the store behind it holds the last good value |
Both are filtered through isRelevantIssueId, so a field that isn't currently
shown (adEmail with split-email off, zaloGroupLink outside Vietnamese
output) can never block on a value with no visible input to fix it.
The first implementation registered issues from the inputs themselves and cleared on unmount. It typechecked and had passing tests, and did nothing: the fields live on the Editor page while the gates live on Batch / Social / Output, so navigating away cleared every issue. Deriving from state removes the mount coupling entirely.
4. i18n Architecture
i18n/locales/
├── en/
│ ├── ui.json # UI strings: buttons, labels, tooltips, errors
│ └── templates.json # Generated content: title patterns, description sections
├── vi/
│ ├── ui.json
│ └── templates.json
├── ja/
│ ├── ui.json
│ └── templates.json
└── _schema.json # JSON Schema — validates all locale files have same keys
Adding a new language = 2 JSON files + 1 line registration. See docs/I18N.md.
Lazy loading (v0.26+): only English is bundled into the main chunk — it is the fallbackLng and the engine's bilingual tEn translator, both of which must resolve synchronously. Every other language is fetched on first use as a Vite async chunk via i18next-resources-to-backend + dynamic import(). Generation paths gate on bundle readiness (useLanguagesReady hook / ensureLanguagesLoaded): an unloaded language would otherwise silently render English fallback output. A chunk that fails to fetch degrades to English and logs to the in-app Log page — it never hangs the UI.
UI language vs Output language: These are independent. User can browse the app in English but generate descriptions in Japanese. UI language follows SettingsStore.defaultLanguage, output language follows EditorStore.language.
5. Desktop Packaging (Tauri)
Web App (React + Vite)
│
▼
┌───────────────────┐
│ Tauri Shell │
│ ┌──────────────┐ │
│ │ WebView │ │ ← Renders the same React app
│ │ (system) │ │
│ └──────────────┘ │
│ ┌──────────────┐ │
│ │ Rust Core │ │ ← File system access, clipboard, tray
│ └──────────────┘ │
└───────────────────┘
│
▼
Binary output:
- Windows: .msi / .exe (~8MB)
- macOS: .dmg / .app (~10MB)
Tauri advantages over Electron:
- Binary size: ~8MB vs ~150MB
- Memory: ~30MB vs ~100MB+
- No bundled Chromium — uses system WebView
- Rust backend for native features
6. Extensibility Points
| What | How to Extend | Files to Touch |
|---|---|---|
| New language | Add locales/{code}/ui.json + templates.json, register in SUPPORTED_LANGUAGES (lazy-loaded automatically) |
3 files |
| New genre | Add entry to config/genres.ts, add tag pool to engine/tag-generator.ts |
2 files |
| New video type | Add to config/video-types.ts, add patterns to all templates.json |
1 + N locale files |
| New platform/store | Add entry to config/platforms.ts |
1 file |
| New social link | Add entry to config/social-fields.ts |
1 file |
| New rig field | Add entry to config/rig-fields.ts |
1 file |
| Custom template | Edit templates.json for target language |
1 file |
| Desktop feature | Add Tauri command in src-tauri/src/main.rs |
1 file |
7. Data Flow
User Input (form)
│
▼
EditorStore (Zustand)
│
├──→ useGeneratedOutput hook
│ │
│ ├──→ titleBuilder(input, locale) → title string
│ ├──→ descriptionBuilder(input, locale) → description string
│ ├──→ tagGenerator(input) → tags string[]
│ │
│ └──→ GeneratorOutput (memoized)
│ │
│ ▼
│ OutputPage (display + copy)
│
├──→ ProfileStore.save() ──→ localStorage
├──→ PresetStore.save() ──→ localStorage
└──→ HistoryStore.add() ──→ localStorage