diff --git a/.changeset/34770-i18n-skill-router.md b/.changeset/34770-i18n-skill-router.md new file mode 100644 index 00000000000..0252857a143 --- /dev/null +++ b/.changeset/34770-i18n-skill-router.md @@ -0,0 +1,22 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): the objectstack-i18n entry file becomes a router + +Clause-②: no +Metadata-protocol: none + +`skills/objectstack-i18n/SKILL.md` goes from 25.3 KB to 9.0 KB (504 lines to 160). It now holds five things: three first checks (read the stack's `i18n` block and the contract before writing a key; which of `defaultLocale`, `sourceLocale`, `supportedLocales` and `fallbackLocale` is which; verify with `os i18n check` and `os validate`), one type-checked bundle with the `translation` metadata item beside it, the key map as one path listing, seven traps, and a table that says where to go for the rest. No rule's teaching changes. This skill has no hand-written reference file, so no text moved: what left the entry was cut, and this entry says what now answers it. + +**What the entry keeps.** The key map lists, as paths, the groups under `objects.{object}` (`fields`, `_views`, `_actions`, `_sections`, `_tabs`, `_relatedLists`, `_milestones`, `_validations`) and the top-level groups the old entry listed, with their keys. It is not the whole contract: it stops above the leaf keys of `bulkActions.{def}`, of `params.{param}`, of a dataset member and of a report block's `description`, and it does not list the top-level `forms` group (the old entry did not either). The routing table sends a key or shape the map does not show to the contract. Six notes under it carry the placements a path cannot show: `inlineTitle` and `relatedListTitle` are keys of the child object; `_views.{view}.title` is a form's own heading and a section's override says `helpText` where the field says `help`; `columns` is a sibling of `fields` (with the one worked example the map keeps) and `preflight` has no `title`; `_relatedLists.{list}` is on the parent; a report block is keyed by its `name` and a `books` group by its `key`; a flow step is keyed under `approvals`, `screens` or `nodes`. The seven traps, each one a bundle that parses and ships and then translates nothing or the wrong text: an option key is the stored `value`, never the label; `t()` fills double braces only and there is no ICU MessageFormat; `os i18n extract` writes `objects` and `globalActions` only unless you pass `--no-objects-only`; coverage is not freshness, so `os i18n extract … --check` is the second gate; a generated module is an `objects` subtree that needs wrapping, and `withSourceFallback` needs the `--source-hashes` companion as its fourth argument; text the server writes is in the organization's language; an app-authored refusal has no `en` floor. + +**What left, and what answers it now.** + +- The condition on each key (which declaration a key needs before it is accepted) and the retired and misspelled keys (`o`, `app`, `nav`, `dashboard`, `_globalOptions`, `_meta`, `validationMessages`, `settings`, `confirmMessage`, `sourceLanguage`, `authoringLocale`, `authoringLanguage`): the contract, `node_modules/@objectstack/spec/src/system/translation.zod.ts`. Its shapes are strict, a key with a condition says it in its `.describe()` text, and a refused key is answered with the key to write. `os validate` reports a key that names nothing the metadata declares as `translation-target-unknown`, an error. +- The `i18n` property table, the naming-convention table and the file-layout table: the contract and the bundle example. +- The flags of `os i18n check` and `os i18n extract` beyond the ones a run needs (`--include-platform`, `--show-keys`, `--fill`, `--default-locale`, `--no-metadata-forms`) and `os lint --i18n-strict`: each command's `--help`. +- The `II18nService` method list: `@objectstack/spec/contracts`. The locale resolution order: https://objectstack.ai/docs/protocol/kernel/i18n-standard. The coverage and diff shapes: the contract (`TranslationCoverageResultSchema`, `TranslationDiffItemSchema`). The three `/api/v1/i18n` routes: https://objectstack.ai/docs/api/plugin-endpoints, which the entry does not link. +- The paragraph on platform-composed `userMessage` sentences, the list of shipped example bundles, and the sentence that validation, delete-restriction and permission-denial messages name fields in the request's language: cut. They describe what the platform does and ask nothing of a bundle author. + +**Anchors that no longer exist in `SKILL.md`.** Every section heading of the old file: `#translation-configuration`, `#stack-level-i18n-config`, `#authoring-translation-bundles-objects`, `#object-level-translation-structure`, `#naming-conventions`, `#file-organization-strategies`, `#authoring-at-runtime-the-translation-item`, `#message-interpolation`, `#simple-format-default`, `#no-icu-messageformat`, `#translation-coverage`, `#os-i18n-check`, `#os-i18n-extract---check--freshness-not-coverage`, `#diff--coverage-schemas`, `#integration-with-ii18nservice`, `#service-contract`, `#registration`, `#server-composed-user-text-usermessage`, `#translation-workflow-best-practices`, `#1-extract-skeletons-from-metadata`, `#2-register`, `#shipped-examples`, `#common-pitfalls`, `#-the-retired-o-shape`, `#verify-your-work`, `#references`, `#see-also`. The new ones are `#first-checks`, `#a-bundle`, `#key-map`, `#traps` and `#where-to-go`. No file in this repository linked an anchor of the old entry. diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 754909c5977..95419ecaa85 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -987,7 +987,19 @@ export const CEILINGS = new Map([ // introducing that example. No raise, no ruling spent: // 25359 bytes (25332 priced) -> 25285 (25258 priced); the row follows the measurement down. // ceil(($(wc -c < skills/objectstack-i18n/SKILL.md) - 27) / 4) == ceil(25258 / 4) - ['skills/objectstack-i18n/SKILL.md', 6315], // -11 (was 6349), then -5 A2′ (was 6338), then -18 (was 6333) + // 6315 -> 2243 (#34770): the entry becomes a router. It keeps three first checks, one + // type-checked bundle, the key map as one path listing with the six placements a path cannot + // show, seven traps (each parses and ships, then translates nothing or the wrong text) and a + // routing table. This skill has no hand-authored reference file, so nothing MOVED: the rest + // is CUT behind a pointer, to the contract (`translation.zod.ts`, whose strict shapes refuse + // a wrong key with the key to write), to `os validate` (`translation-target-unknown` is an + // error) or to the published i18n standard page. No row rises and no row is added. The file + // is 25285 bytes (25258 priced) -> 8996 (8969 priced) -> 2243 tokens, pinned AT the + // measurement; the sum of all ceilings falls by the same 4072. + // Authority: the ruling of record that orders the entry file down to router size, decision + // record #34691 S3 = A. + // ceil(($(wc -c < skills/objectstack-i18n/SKILL.md) - 27) / 4) == ceil(8969 / 4) + ['skills/objectstack-i18n/SKILL.md', 2243], // 12705 -> 12984 (2026-08-31 app-repo-principles raise, see the block above). // The largest of the five and the frame the other four are read under: what an // app IS (metadata under the platform's spec, authored from these skills, diff --git a/skills/objectstack-i18n/SKILL.md b/skills/objectstack-i18n/SKILL.md index 32d90d7bcdc..bb3979c6cf5 100644 --- a/skills/objectstack-i18n/SKILL.md +++ b/skills/objectstack-i18n/SKILL.md @@ -18,487 +18,143 @@ metadata: # Internationalization — ObjectStack I18n Protocol -## Translation Configuration - -### Stack-Level I18n Config - - -```typescript -import { defineStack } from '@objectstack/spec'; - -export default defineStack({ - i18n: { - defaultLocale: 'en', - supportedLocales: ['en', 'zh-CN', 'ja-JP', 'es-ES'], - fallbackLocale: 'en', - }, - // translations: [MyTranslations], ← register your bundles here (see below) -}); -``` - -| Property | Type | Required / Default | Description | -|:-|:-|:-|:-| -| `defaultLocale` | `string` | **required** | The locale a user who has not chosen one gets | -| `sourceLocale` | `string` | optional, defaults to `defaultLocale` | The language inline `label:` text is written in: a request in it is served that text; read by `os lint`, `os i18n check`, `os i18n extract` | -| `supportedLocales` | `string[]` | **required** | All supported locales | -| `fallbackLocale` | `string` | optional | Fallback when translation missing | - -An app authored in English for Chinese users declares `defaultLocale: 'zh-CN', sourceLocale: 'en'`, -not an English `defaultLocale`. Validation, delete-restriction and permission-denial messages name fields -and objects in the request's language, as label serving does: an `en` request reads the inline label. -`sourceLanguage`, `authoringLocale` and `authoringLanguage` are refused, each naming `sourceLocale`. - ---- - -## Authoring Translation Bundles (`objects.*`) - -The canonical authoring path: one `TranslationData` per locale, assembled with -`defineTranslationBundle` and registered on the stack: +## First checks + +1. **Read first**: the stack's `i18n` block and `translations`, the declared names a key + must match, and the contract for any shape, + `node_modules/@objectstack/spec/src/system/translation.zod.ts` + ([references/_index.md](./references/_index.md)). Never recall a key. +2. **Which language is which.** `defaultLocale` is what a user who has not chosen gets; + `sourceLocale` (defaults to it) is the language inline labels are written in, + read by `os lint`, `os i18n check`, `os i18n extract` and label serving; + `supportedLocales` are BCP-47 codes (`ja-JP`); `fallbackLocale` serves a missing + translation. An app authored in English for Chinese users declares + `defaultLocale: 'zh-CN', sourceLocale: 'en'`, not an English `defaultLocale`. +3. **Verify**: `os i18n check` lists missing keys per locale (`--locales=zh-CN`; CI: + `--strict --threshold=95`); `os validate` refuses a key naming nothing the metadata + declares (`translation-target-unknown`). + +## A bundle + +One `TranslationData` per locale, assembled by `defineTranslationBundle` and registered on +the stack; nothing loads a directory. ```typescript -// src/translations/en.ts import { defineStack, defineTranslationBundle } from '@objectstack/spec'; import type { TranslationData } from '@objectstack/spec/system'; -const en: TranslationData = { - objects: { - task: { - label: 'Task', - pluralLabel: 'Tasks', - fields: { - subject: { label: 'Subject', help: 'Brief title of the task' }, - status: { - label: 'Status', - options: { - not_started: 'Not Started', - in_progress: 'In Progress', - completed: 'Completed', - }, - }, - }, - _views: { - all_tasks: { - label: 'All Tasks', - emptyState: { title: 'No tasks yet', message: 'Create your first task' }, - }, - }, - _sections: { - details: { label: 'Details' }, - }, - _actions: { - todo_complete: { - label: 'Complete', - confirmText: 'Mark this task as completed?', - successMessage: 'Task completed', - }, - }, - }, - }, - apps: { - todo_app: { label: 'Todo Manager', description: 'Personal task management' }, - }, - messages: { - 'common.save': 'Save', - 'welcome.user': 'Welcome, {{userName}}!', - }, -}; - -// src/translations/zh-CN.ts — same shape, translated values const zhCN: TranslationData = { objects: { task: { label: '任务', - pluralLabel: '任务', - fields: { - subject: { label: '主题', help: '任务的简要标题' }, - status: { - label: '状态', - options: { not_started: '未开始', in_progress: '进行中', completed: '已完成' }, - }, - }, + fields: { status: { label: '状态', options: { in_progress: '进行中' } } }, + _actions: { todo_complete: { label: '完成' } }, }, }, - messages: { - 'common.save': '保存', - 'welcome.user': '欢迎,{{userName}}!', - }, + messages: { 'welcome.user': '欢迎,{{userName}}!' }, }; +const en: TranslationData = { messages: { 'welcome.user': 'Welcome, {{userName}}!' } }; +export const TodoTranslations = defineTranslationBundle({ en, 'zh-CN': zhCN }); -// src/translations/index.ts -export const TodoTranslations = defineTranslationBundle({ - en, - 'zh-CN': zhCN, -}); - -// objectstack.config.ts export default defineStack({ - i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] }, + i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'], fallbackLocale: 'en' }, translations: [TodoTranslations], }); ``` -`defineTranslationBundle` validates the bundle at authoring time via `.parse()` — -prefer it over a bare `: TranslationBundle` literal. - ---- - -## Object-Level Translation Structure - -All translatable content for a single object is aggregated under -`objects.{object_name}` with these sub-keys: - -| Sub-key | Holds | -|:-|:-| -| `label` / `pluralLabel` / `description` | Object-level text (every key optional) | -| `fields.{field_name}` | `label`, `help`, `placeholder`, `options` (option value → label), `inlineTitle` (the heading of the inline child grid a `master_detail` field draws on its parent's form — the field lives on the child object, so the key is the child's; untranslated it keeps its authored text, never the child's plural label), `relatedListTitle` (likewise, the title of the related list a `lookup` or `master_detail` field draws on its parent's record page) per field | -| `_views.{view_name}` | `label`, `description`, `title` (a form view's own heading — only a form that authors one is translated; a list view has none), `submitBehavior.title` / `submitBehavior.message` (the thank-you panel of a form whose `submitBehavior` is `kind: 'thank-you'`; only the copy the form authors is translated, and the other kinds carry none), `emptyState.title` / `emptyState.message`, `bulkActions.{def_name}` (`label`, `confirmText`, `confirmLabel`, `params`) | -| `_actions.{action_name}` | `label`, `description`, `confirmText`, `submitText` (the param dialog's button verb — only under an action that declares a non-empty `params`), `cancelText` (the dismiss button of the confirm or param dialog — only under an action that declares `confirmText` or a non-empty `params`), `successMessage`, `disabledReason` (the sentence a greyed action shows; absent keeps the console's default), `params.{param_name}` (and `.options.{value}` beneath it — an option's stored `value` in that param's inline `options`), `outcomeMessages.{outcome}` (an outcome the action's own `outcomeMessages` declares), `resultDialog.title` / `.description` / `.acknowledge` (only under an action that declares a `resultDialog`), `resultDialog.fields.{path}` (the literal `path` of a field in `resultDialog.fields[]`, dots included — `client.secret` is one key), `preflight.fields.{path}` (only under an action that declares `preflight`: a field's literal `path` in its `preflight.fields[]`, its value a plain string as under `resultDialog.fields`), `resultDialog.columns.{path}.{column_path}` / `preflight.columns.{path}.{column_path}` (a table's column headers, beside `fields`: the literal `path` of a `format: 'table'` field, then of one of its `columns[]`, each a plain string; `defineTranslationBundle` refuses any other key under `preflight`, a `title` included); the same keys hold under `globalActions.{action_name}` | -| `_sections.{section_name}` | Form section `label`, `description`; `fields.{field_name}` — the `label`, `placeholder`, `helpText` an entry overrides for that form alone (`helpText` here, `help` under `fields.{field_name}` above: each spells what its source does) | -| `_tabs.{tab_name}` | Filter-preset tab `label` (`ViewTabSchema.name`) | -| `_relatedLists.{list}` | `label` of an object-form `relatedLists` entry on this (parent) object, by its literal `list` (`event.related_to` is one key); an entry with no `label` has no key and keeps the child field's `relatedListTitle`, else the child's plural label. Where the paired `.custom` package's `relatedLists` (**objectstack-data**) re-states the entry without a `label`, or hides it, `os validate` refuses the key: drop it, or re-state the entry, shown, with a `label`: the owner's own keeps its translation, any other reads this key from the `.custom` package's own bundle (`os i18n check` expects it). Spelled `relatedLists`, the group is refused, naming this one | -| `_milestones.{field}.{value}` | `summary`, the timeline sentence of the `activityMilestones` entry firing on that field and value, same `{field}` tokens: composed at read time in the reader's language (a select token as its option label), stored row unchanged, redacted as the stored sentence is | -| `_validations.{rule_name}` | `message` only — the sentence a rejected write returns (replaces the retired `validationMessages`) | -| `_actions.{action_name}.refusals.{CODE}` | `message`, and `reasons.{reason}.message` per declared reason — the sentences of the action's `refusals` catalogue (**objectstack-ui** → Actions), for a code and reason it declares (any other is `translation-target-unknown`); the same under `globalActions.{action_name}` | - -Top-level groups alongside `objects`: `apps` (label, description, navigation), -`messages`, `globalActions` (actions with no `objectName` — a key naming a bound action is -an **error** whose message names the `objects.{owner}._actions.{action_name}` key to write -instead), `picklists` (`label`, `options` by stored value — every field referencing the -picklist inherits them), `dashboards`, `datasets`, `reports`, `pages`, `flows`, `positions`, -`permissions` (permission sets, spelled as the stack's `permissions[]`), `books` (a doc book's -spine, by `Book.name`: `books.{book}.label` / `.description`, and `groups.{group_key}.label` by -each group's stable `key`, never its position — `books.crm_manual.groups.getting_started.label`; -the pages themselves localize through `doc.translations`, and the inline `translations` map a -book once carried stays retired), `mappings` (an import mapping's `label` by its `name`: -`mappings.{mapping}.label`), `packages` (`name` / `description` by `manifest.id`, the dotted id one -key: `packages: { 'com.acme.crm': { name: '客户关系' } }`; a locale with no row shows -`manifest.name`, and `os lint` warns `i18n/missing-package` (`os i18n check` lists the key) -until that package's own bundle carries it), `metadataForms`, `settingsCommon`; `reports`, `positions` and -`permissions` hold `label` + `description` by name, so do `datasets` and each dataset member at -`datasets.{dataset}.{dimensions,measures}.{member}` (a member's `synonyms` have no key: one -authored list carries every language), and a joined report's block headings sit at -`reports.{report}.blocks.{block_name}.{label,description}`, keyed by the block's required `name`. -Four keys sit deeper than their group's `label`: a `page:tabs` item at -`pages.{page}.components.{tabs_id}.items.{value}.label` (by the item's `value`; an item without -one has no key), an approval step at `flows.{flow}.approvals.{node_id}.label`, any other step's -name at `flows.{flow}.nodes.{node_id}.label` (a screen is named by its heading, -`flows.{flow}.screens.{node_id}.title`, and takes a `nodes` key only beside a `title` of its own; -`os i18n check` asks for a flow's top-level steps, and for one of `FLOW_TECHNICAL_NODE_TYPES` — -`script`, `http`, `connector_action`, `assignment`, `boundary_event`, the four `*_record` types — -only where a decision's branch leads to it), and the text a -`create_record` / `update_record` writes into a field marked `{ dialect: 'template', source }` at -`flows.{flow}.records.{node_id}.fields.{field}`. That text, and each sentence a hook or a `script` -action declares in `texts` and writes through `ctx.text` — `hooks.{hook}.texts.{key}.message`, -`_actions.{action_name}.texts.{key}.message` (also under `globalActions`) — is picked in the -organization's language (the Localization setting if set, else `i18n.defaultLocale`; never the caller's). -`os i18n extract --no-objects-only` scaffolds every group above but `messages` and -`settingsCommon`, all four keys included. The `inlineTitle`, report-block, table-column and -mapping keys, as the shipped `app-crm`, `app-showcase` and platform bundles spell them for `zh-CN` -(`rows` is the table field's `path`, `error.message` one column's): - -```typescript -objects: { crm_opportunity_line_item: { fields: { opportunity: { inlineTitle: '产品明细' } } } }, -reports: { showcase_task_overview: { blocks: { open_block: { label: '未完成任务' } } } }, -objects: { sys_user: { _actions: { import_sso_users: { resultDialog: { columns: { rows: { email: '邮箱', 'error.message': '未添加的原因' } } } } } } }, -mappings: { showcase_inquiry_feed: { label: '询盘导入(营销 CSV)' } }, -``` - -`settings` is **platform-only** — it is keyed by a settings manifest's namespace and only -the platform declares one, so an app bundle carrying it is refused by name. - ---- - -## Naming Conventions - -| Context | Convention | Example | -|:-|:-|:-| -| Locale codes | BCP-47 | `en`, `en-US`, `zh-CN`, `pt-BR` | -| Object keys in `objects.*` | `snake_case` | `objects.project_task`, `objects.support_case` | -| Field keys | `snake_case` | `fields.first_name`, `fields.due_date` | -| Option values | lowercase | `options.status.in_progress` | -| Message keys | dot-separated | `common.save`, `validation.required` | - -Option sub-keys are the option's stored **`value`**, never its display label: -for `options: [{ value: 'direct_mail', label: 'Direct Mail' }]` write -`options: { direct_mail: '直邮' }` — both `'Direct Mail'` and `'direct-mail'` -parse, ship, and resolve to nothing. - -`os validate` / `os lint` / `os compile` check this direction: `translation-target-unknown` -is an **error** and fails the run; `translation-option-key-unknown` is a warning. -A key naming an object, field, view, tab, action, param, section, validation rule, app, -nav item, dashboard, widget or flow screen that does not exist is listed alongside the names -that do. The same error: a key the `_actions` row above ties to something the action does not declare -(an outcome, a dialog field or column path, `resultDialog` copy, `submitText`, `cancelText`) — -a bundle translates a dialog the action declares and cannot add one. A -param's inline option keys share the option warning with a field's `options`; a param that -references a `field` and declares no inline `options` is not judged. - ---- - -## File Organization Strategies - -Layout is an **authoring convention**: whichever one you pick, your own import graph -assembles it into the `TranslationBundle` you register on the stack — nothing loads a -directory tree for you. - -| Layout | Files | Use when | -|:--|:--|:--| -| Bundled | one `crm.translation.ts` holding every locale | under 5 objects, 2-3 locales | -| Per-locale (recommended) | `src/translations/{en,zh-CN,ja-JP}.ts` + `index.ts` | 5-20 objects, 3-5 locales | -| Per-namespace | `i18n/{locale}/{object}.json` | 20+ objects, 5+ locales | - ---- - -## Authoring at Runtime: the `translation` Item - -A **`translation` metadata item** — created in -the Studio, through the metadata API, or by an agent — carries one locale's worth of the -**same** `objects.*` groups documented above plus the `locale` it translates. `locale` is -required, and published items load at boot and on every publish, layering **over** -the file bundles (delete the item and the shipped value returns). Author with `defineTranslation`; -exact Zod shape is `TranslationItemSchema` in -`node_modules/@objectstack/spec/src/system/translation.zod.ts`. - ---- - -## Message Interpolation - -### Simple Format (Default) - -Both shipped adapters substitute -**double-brace** `{{variable}}` placeholders only — single braces pass through -unchanged. A milestone summary (`_milestones...summary`) keeps its -single-brace `{field}` tokens. - -```json -{ - "messages": { - "welcome": "Welcome, {{userName}}!" - } -} -``` - -### No ICU MessageFormat - -There is no ICU MessageFormat engine. To pluralize, select the form in application code before calling `t()`. - ---- - -## Translation Coverage - -### `os i18n check` - -```bash -os i18n check # every locale found in the config -os i18n check --locales=zh-CN # scope to specific locales -os i18n check --strict --threshold=95 # CI gate: locale parity + minimum coverage -``` - -It compares registered bundles against source metadata and reports missing keys -per locale for every surface the extractor walks. The platform's metadata -forms count only for a stack that ships their translations (`--include-platform` -audits them anyway). Gaps in the source locale are errors, `--strict` promotes -the rest, `--show-keys` lists them all; `os lint --i18n-strict` folds it in. - -### `os i18n extract --check` — freshness, not coverage - -If you commit **generated** bundles (`*.generated.ts` produced by -`os i18n extract`), coverage is only half the gate: - -```bash -os i18n extract --locales=zh-CN,ja-JP --fill=default \ - --out=src/translations --check -``` - -`--check` writes nothing. It re-renders what a real extract would produce and -fails if that differs from what is committed in `--out`, naming each stale or -missing file and printing the regenerate command. - -**Use both gates:** renaming a label or removing a spec key leaves coverage at -100% while the bundles go stale. - -It runs in the same **merge mode** as a normal extract, so it never asks for -re-translation: an up-to-date bundle re-extracts byte-identically. Requires `--out`. - -### Diff & Coverage Schemas - -The spec models coverage results for tooling — the return shapes of the optional `getCoverage()` / `suggestTranslations()` (see *Service Contract* below): `TranslationCoverageResult` -(totals, `coveragePercent`, per-group `breakdown`) and `TranslationDiffItem` — -`key` (dot path), `status` (`missing | redundant | stale`), `locale`, optional -`objectName`, optional `sourceHash` for stale detection, and AI-enrichment -fields (`aiSuggested`, `aiConfidence`). Full Zod shape: `TranslationCoverageResultSchema`, -`TranslationDiffItemSchema` (`translation.zod.ts`). - ---- - -## Integration with II18nService - -### Service Contract - -`II18nService` is the kernel service (name `'i18n'`) that loads bundles and -resolves keys with fallback: - -```typescript -import type { II18nService } from '@objectstack/spec/contracts'; -``` - -(Only `src/**/*.zod.ts` ships, so the contract's `.ts` source is not in `node_modules`.) - -Methods both shipped adapters implement (`FileI18nAdapter` from -`@objectstack/service-i18n`, and the in-memory fallback `@objectstack/core` -registers when no i18n plugin is present): - -- **`t(key, locale, params?)`** — dot-path resolution (e.g. `objects.account.label`) - with `{{param}}` interpolation and fallback-locale lookup -- **`getTranslations(locale)`** — a locale's full snapshot -- **`loadTranslations(locale, data)`** — programmatic load (deep-merge) -- **`getLocales()`** / **`setSupportedLocales()`** / **`getDefaultLocale()`** / **`setDefaultLocale()`** / **`getSourceLocale()`** (the declared one only, else `undefined`) / **`setSourceLocale()`** - -The in-memory fallback additionally resolves locale codes through `resolveLocaleAmong` -(`@objectstack/spec/system`), the one ladder `resolveBundleLocale` also runs: exact → -case-insensitive → same platform-table language (`zh-TW` → `zh-Hant`) → base language -`zh-CN` → `zh` → first registered variant `zh` → `zh-CN`. - -The contract declares optional methods — `getFieldLabels`, `getCoverage`, -`suggestTranslations` — that **no shipped implementation provides**: extension -points for a custom workbench or TMS adapter. - -### Registration - -You do not need to wire this plugin: `os serve` registers `I18nServicePlugin` itself whenever the -stack config carries `translations` or `i18n` (kernel bootstrap is -**objectstack-platform → Runtime Boot Sequence**). The runtime's HTTP dispatcher, -which `os serve` composes, mounts for signed-in callers `GET /api/v1/i18n/locales`, `/translations/:locale` and -`/labels/:object/:locale`, served from the i18n service; the locales -answer marks the default locale (`isDefault`) and names `sourceLocale` (the declared one, else the default) and the declared `fallbackChain`, if any. - ---- - -## Server-Composed User Text (`userMessage`) - -Text the server addresses to the end user — `userMessage` on an error envelope, a save / -publish advisory, a 422 or `probes` issue — comes back in the REQUEST's locale, composed where it is -produced; a client renders it as received. - -- **Platform-composed** text follows one ladder over the platform locale table - (`PLATFORM_LOCALES`, `@objectstack/spec/system`): the locale the request names (its - `Accept-Language`, or `?locale` on the REST door), else the workspace default (the - `localization` settings' locale), else `en`. Each code is read whole and then one subtag - shorter at a time (`fr-FR` → `fr`, `zh-Hant-US` → `zh-Hant`), so a Traditional Chinese - code is never handed Simplified text. -- **App-authored** refusal text is not on this ladder: a hook's catalogued refusal is served - through `hooks..refusals..message` (a declared reason's through - `…..reasons..message`), an action's through its `_actions.{action_name}.refusals` - keys (table above), each in the caller's locale, negotiated over - whatever locales the app's translations hold, and otherwise as declared, in the app's own - source language. No `en` floor is supplied for it. Under an entry declaring `params`, a - translation keeps its `{{ name }}` holes; the runtime fills them after picking it. - ---- - -## Translation Workflow Best Practices - -### 1. Extract Skeletons from Metadata - -```bash -os i18n extract --locales=zh-CN --out=./src/translations -``` - -This writes `.objects.generated.ts` TypeScript modules (not JSON), plus a -`.metadata-forms.generated.ts` companion unless `--no-metadata-forms` — -the source locale is filled from schema labels, other locales follow `--fill` -(`empty | default | todo`). `--default-locale` overrides the source locale for one run -(`i18n.sourceLocale`, else `i18n.defaultLocale`, else `en`). `os i18n extract --help` lists -the rest: `--filter`, `--no-merge`, `--dry-run`, `--json`, … - -⚠️ **`--objects-only` is on by DEFAULT**, so extract writes only the `objects` / -`globalActions` subtree while `os i18n check` still asks for the other groups: pass -`--no-objects-only`, or author them by hand. - -### 2. Register - -A **package or plugin shipping its own generated bundle** has one more step than -`defineStack({ translations: [...] })`: a generated module exports an objects *subtree* -(`NonNullable`), not a `TranslationData`, so it must be -wrapped before it is a bundle at all. - -```typescript -// src/translations/index.ts -import { defineTranslationBundle } from '@objectstack/spec'; -import type { TranslationData } from '@objectstack/spec/system'; -import { withSourceFallback } from '@objectstack/platform-objects/apps'; -import { enObjects } from './en.objects.generated.js'; -import { zhCNObjects } from './zh-CN.objects.generated.js'; -import { zhCNGeneratedSourceHashes } from './zh-CN.source-hashes.generated.js'; - -const enSource: TranslationData = { objects: enObjects }; - -export const StorageTranslations = defineTranslationBundle({ - en: enSource, - // 4th argument = the `--source-hashes` companion. Without it a leaf whose SOURCE has - // moved goes on serving the superseded fill under a green `os i18n check` forever. - // The 3rd stays undefined: it judges hand-authored `apps` / `dashboards` / `pages`, - // which a fully generated set does not have. - 'zh-CN': withSourceFallback({ objects: zhCNObjects }, enSource, undefined, zhCNGeneratedSourceHashes), -}); -``` - -A plugin that owns its objects loads that bundle from its own `kernel:ready` hook rather -than registering it on the stack: `i18n.loadTranslations(locale, data)` deep-merges, so -every plugin contributes its own `objects.*` slice. - ---- - -## Shipped examples - -`examples/app-crm` — the bundled layout (`en` + `zh-CN`). -`examples/app-todo` — the per-locale layout. - ---- - -## Common Pitfalls - -### ❌ The Retired `o.*` Shape - -Everything reads `objects.*`. The `o.*` dialect was removed. Both doors reject it, files included. - -```typescript -// WRONG -{ o: { account: { label: '客户' } } } - -// CORRECT (TranslationData) -{ objects: { account: { label: '客户' } } } +With no redeploy, the same groups plus a required `locale` are a **`translation` metadata +item**, in Studio or the metadata API: author with `defineTranslation` +(`TranslationItemSchema`). It loads at boot and on every publish, layered over the file +bundles; delete it and the shipped value returns. + +## Key map + +`{path}`, `{column_path}` and `{list}` are the declared string as one key, dots included +(`'event.related_to'`); `fields.{path}` and `{column_path}` hold plain strings. + +```text +objects.{object}: label, pluralLabel, description + fields.{field}: label, help, placeholder, options.{value}, inlineTitle, relatedListTitle + _views.{view}: label, description, title, emptyState.{title,message}, + submitBehavior.{title,message}, bulkActions.{def} + _actions.{action}: label, description, confirmText, submitText, cancelText, + successMessage, disabledReason, params.{param}(.options.{value}), + outcomeMessages.{outcome}, resultDialog.{title,description,acknowledge}, + resultDialog.fields.{path}, resultDialog.columns.{path}.{column_path}, + preflight.fields.{path}, preflight.columns.{path}.{column_path}, + refusals.{CODE}.message, refusals.{CODE}.reasons.{reason}.message, texts.{key}.message + _sections.{section}: label, description, fields.{field}.{label,placeholder,helpText} + _tabs.{tab}.label, _relatedLists.{list}.label + _milestones.{field}.{value}.summary, _validations.{rule}.message +globalActions.{action}: the _actions keys (an action with no objectName) +apps.{app}: label, description, navigation.{id}.label +picklists.{picklist}: label, options.{value} +reports, positions, datasets, permissions (as the stack's permissions[]): + {name}.label, {name}.description +reports.{report}.blocks.{block_name}.label +datasets.{dataset}.{dimensions,measures}.{member} +books.{book}: label, description, groups.{group_key}.label +mappings.{mapping}.label, packages.{manifest.id}: name, description +pages.{page}.components.{tabs_id}.items.{value}.label +flows.{flow}: approvals.{node_id}.label, screens.{node_id}.title, nodes.{node_id}.label, + records.{node_id}.fields.{field} +hooks.{hook}: texts.{key}.message, and refusals as under _actions +messages: flat dotted ids ('common.save'); dashboards, metadataForms, settingsCommon ``` -Same rule for its sibling keys: `app` → `apps`, `nav` → -`apps..navigation..label`, `dashboard` → `dashboards`, -`_globalOptions` → `objects..fields..options`, `_meta.locale` → -top-level `locale`, and `_actions.confirmMessage` → `_actions.confirmText`. - ---- - -## Verify your work - -```bash -os i18n check # coverage: which keys are missing, per locale -os validate # the bundle conforms to the protocol schema -``` - -For the build and scaffold -gates see objectstack-platform → **Verify your work**. - ---- - -## References - -See [references/_index.md](./references/_index.md) for the full list of Zod -schemas (with one-line descriptions) — pointers into -`node_modules/@objectstack/spec/src/`. Always `Read` the source for exact field -shapes; do not rely on memory of property names. - -## See Also - -- **objectstack-data** — For understanding object and field metadata structure -- **objectstack-ui** — For view, app, and action translations -- **objectstack-automation** — For workflow and flow message translations +- `inlineTitle` (the grid a `master_detail` or `lookup` field draws on its parent's form) and + `relatedListTitle` (its related list on the parent's record page) are keys of the CHILD + object, where the field lives: `objects.crm_opportunity_line_item.fields.opportunity.inlineTitle`. + Untranslated, the authored text shows, never the child's plural label. +- `_views.{view}.title` is a form's own heading. `_sections` `fields` is that form's + override: `helpText` there, `help` under `fields.{field}`. +- `columns` is a sibling of `fields`: a `format: 'table'` field's `path`, then a column's + (`resultDialog: { columns: { rows: { email: '邮箱', 'error.message': '原因' } } }`). + `preflight` holds `fields` and `columns` only, no `title`. +- `_relatedLists.{list}` is on the parent, for a `relatedLists` entry that authors a `label`; + one without has no key and shows the child field's `relatedListTitle`, else its plural label. +- A report block is keyed by its `name` + (`reports.showcase_task_overview.blocks.open_block.label`); a `books` group by its stable + `key`, never its position (`books.crm_manual.groups.getting_started.label`); its pages + localize through `doc.translations`. +- A flow step is keyed under `approvals` (approval), `screens` (screen) or `nodes` (any + other). `os i18n check` asks for a technical step (`script`, `http`, `connector_action`, + `assignment`, `boundary_event`, `*_record`) only where a decision's branch leads to it. + +## Traps + +1. **An option key is the stored `value`, never the label.** For + `{ value: 'direct_mail', label: 'Direct Mail' }` write `options: { direct_mail: '直邮' }`; + `'Direct Mail'` and `'direct-mail'` resolve to nothing and only warn. +2. **Double braces only.** `t()` fills `{{variable}}`; a single-brace `{variable}` is left + as written (a milestone `summary` keeps its `{field}` tokens). No ICU + MessageFormat: pick the plural form in code before `t()`. +3. **`os i18n extract --locales=ja-JP --out=./src/translations` writes `objects` / + `globalActions` only** (`--objects-only` defaults on) while `os i18n check` asks for + every group: pass `--no-objects-only` and author `messages` by hand. +4. **Coverage is not freshness.** A renamed label leaves `os i18n check` at 100% while a + committed `*.generated.ts` goes stale; `os i18n extract … --out=… --check` writes nothing + and names each stale file. +5. **A generated module exports an `objects` subtree, not a `TranslationData`**: wrap it, + and pass `withSourceFallback` (`@objectstack/platform-objects/apps`) the `--source-hashes` + companion 4th, or a leaf whose source moved serves the superseded fill under a green check. + With `enSource = { objects: enObjects }`: + `defineTranslationBundle({ en: enSource, 'zh-CN': withSourceFallback({ objects: zhCNObjects }, enSource, undefined, zhCNGeneratedSourceHashes) })`. + A plugin that owns its objects loads its bundle from its own `kernel:ready` hook, + `i18n.loadTranslations(locale, data)`, not on the stack. +6. **Text the server writes is in the organization's language, never the caller's**: a + `ctx.text` sentence (`texts`) and a flow field marked `{ dialect: 'template', source }` + (`records`) use the Localization setting, else `i18n.defaultLocale`. +7. **An app-authored refusal has no `en` floor.** A `refusals` sentence answers in the + caller's locale, negotiated over the locales the app's bundles hold, else as declared. Its + translation keeps the `{{ name }}` holes; the runtime fills them after picking it. + +## Where to go + +| Need | Open | +|:-|:-| +| A key or shape not above | `translation.zod.ts`: `.describe()` text, refusals | +| `II18nService`; no adapter ships its optional `getFieldLabels`, `getCoverage`, `suggestTranslations` | `@objectstack/spec/contracts` | +| Locale resolution and fallback | https://objectstack.ai/docs/protocol/kernel/i18n-standard | +| What a key names; boot | **objectstack-data** (and hooks), **objectstack-ui** (and actions), **objectstack-automation**; **objectstack-platform** |