diff --git a/.changeset/34374-hook-texts-org-locale.md b/.changeset/34374-hook-texts-org-locale.md new file mode 100644 index 00000000000..86cc344084d --- /dev/null +++ b/.changeset/34374-hook-texts-org-locale.md @@ -0,0 +1,25 @@ +--- +'@objectstack/spec': minor +'@objectstack/core': minor +'@objectstack/runtime': minor +'@objectstack/lint': minor +'@objectstack/service-automation': patch +--- + +feat(hooks): a hook writes the sentences it declares in the organization's language + +Clause-②: yes (widening) — a hook may now declare `texts` and its code may call `ctx.text`; translation bundles accept `hooks..texts..message`; `@objectstack/core` exports `readOrganizationTextLocale`. Nothing that was accepted before is refused +Metadata-protocol: added +Skills-docs: follow-up #34546 + +A hook can now declare the sentences it writes into records for people to read, and ask for one by key: `texts: { follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] } }`, then `await ctx.text('follow_up_subject', { lead })`. The answer is in the organization's language, because everyone in the organization reads the record: the Localization setting (`localization.locale`) when somebody set it, else the app's declared `i18n.defaultLocale`. It is never the language of the person whose save fired the hook. The translation `hooks..texts..message` is picked first, then its `{{ }}` holes are filled from `params`. + +- A missing translation, or no language to pick, answers the declared sentence, and the hook goes on. +- A Localization setting that cannot be read rejects the call, so another language is never stored over a choice that may exist. A host that registers no `localization` setting has none set, so the app's declared default answers. +- Only declared text is translated: a string the hook builds itself is written as it is. A key `texts` does not declare is refused when the hook is saved if the hook asks for it literally (`ctx.text('key')`), otherwise when the hook runs, as a fault naming the hook and the key. `texts` on an `expression` body, or on a hook with neither a body nor a handler, is refused. A text with no `params` is plain text, and a `{{ }}` hole in it is refused. +- A text with `params` is compiled like a declared refusal's sentence: a hole over another name is refused when the hook is saved, and `objectstack validate`, `compile` and the publish gate refuse a hole holding logic, an unknown formatter, an empty hole and `{{ amount | currency }}` with no code. A translation whose holes do not render at run time is dropped for the declared sentence, filled. +- `ctx.text` is the same on a sandboxed `js` body and on an in-process `handler`. +- `os i18n extract` scaffolds the key, and the existing coverage check counts it. `objectstack validate` refuses a `hooks..texts.` translation over a key the hook does not declare. +- Text is picked when it is written. Records already written are not changed. + +`@objectstack/core` exports `readOrganizationTextLocale`: the one reading of the organization's language that every writer of such text shares, with an unregistered Localization setting answered as not set. The flow record write (`@objectstack/service-automation`) now reads through it; its answers are unchanged. diff --git a/content/docs/automation/hook-bodies.mdx b/content/docs/automation/hook-bodies.mdx index b9822f6d9e8..7111449cfda 100644 --- a/content/docs/automation/hook-bodies.mdx +++ b/content/docs/automation/hook-bodies.mdx @@ -103,6 +103,7 @@ The script sees only what the surrounding `ctx` object exposes: | `ctx.api.object(name).insert\|update\|delete` | Cross-object writes. | `api.write` | | `ctx.title()` | This record's title — the object's `nameField`, **including when it is a `formula`** (evaluated server-side against the record already in hand: no extra read over the record's own columns, one read per lookup a title such as `record.book.title + ' · ' + record.reader.name` reads through). | none | | `ctx.title('')` | The related record's title, through a lookup / master_detail / user / tree column. Costs one `findOne` (plus the lookups that record's own title reads through). | `api.read` | +| `ctx.text('', params?)` | A sentence the hook declared under `texts`, in the **organization's** language (translated, holes filled from `params`), for a value it writes into a record. Hook bodies only. See [Writing a sentence people read](/docs/automation/hooks#writing-a-sentence-people-read--texts). | none | | `ctx.crypto.randomUUID()` | UUID generation. | `crypto.uuid` | | `ctx.log.{info,warn,error}` | Structured logging. | `log` | | `ctx.email.send({ to, subject, text })` | Sends mail through the mail service, from the configured sender, as the calling user and under the caller's organization. An action or a job body only: a hook body cannot send mail, because a message cannot be taken back if the write that runs the hook rolls back. A hook whose body is granted `email.send` is refused when it is saved, validated, built or bound, and the Console does not offer the grant on a hook. Send mail on a record change from an action, a job or a flow. See [Email service](/docs/kernel/runtime-services/email-service#from-a-script-body). | `email.send` | diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index cc1afb5cac9..eea8c232784 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -453,6 +453,62 @@ export const planGate = { A hook that declares no `refusals` refuses exactly as before: the thrown error's own `code`, `status` and message reach the caller. +## Writing a sentence people read — `texts` + +A sentence a hook writes into a record — the subject of the follow-up task it +opens, the summary it logs — is read by the whole organization. **Declare it** +on the hook and ask for it by key: the runtime answers it in the +**organization's** language, never the language of the person whose save fired +the hook. + +```typescript +export const leadFollowUp = { + name: 'lead_follow_up', + object: 'crm_lead', + events: ['afterUpdate'], + texts: { + follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] }, + }, + handler: async (ctx) => { + if (ctx.input.status !== 'qualified' || ctx.previous?.status === 'qualified') return; + const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name }); + await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.input.id }); + }, +}; +``` + +- **The organization's language.** The Localization setting when somebody set + it (Setup → Localization), else the app's `i18n.defaultLocale`. A hook a + person's save fires still writes in the organization's language — the record + is data everyone reads, not a message to that person. +- **Translated first, filled after.** `ctx.text` picks + `hooks..texts..message` in that language, then fills the `{{ }}` + holes from the `params` you pass. A text that declares `params` may write + `{{ name }}` holes over those names, with an optional known formatter; one + that declares none is plain text, and a hole in it is refused when the hook + is saved. A hole over another name is refused at save; logic, an unknown + formatter, an empty hole and `{{ amount | currency }}` with no code are + refused by `os validate`, `compile` and the publish gate. +- **A missing translation never fails the hook.** With no translation, or no + language to pick, the declared `message` is written. A translation whose + holes do not render is dropped for the declared `message`, filled. +- **An unreadable Localization setting rejects.** When the settings service + cannot be read, `ctx.text` rejects rather than write another language over + the organization's choice. Catch it if the hook should write anyway. +- **Only declared text is translated.** A string the hook builds itself is + written as it is. A key `texts` does not declare is refused when the hook is + saved if the hook names it literally in `ctx.text('key')`, otherwise when the + hook runs, as a `500` that names the hook and the key. +- **It works whichever way the hook is written** — a TypeScript `handler` and a + sandboxed `js` body get the same `ctx.text`. An `expression` body cannot ask + for one, so `texts` is refused there. +- **Translated by key.** `os i18n extract` scaffolds + `hooks..texts..message` and `os i18n check` counts it. See + [Translations](/docs/ui/translations). + +Rows a hook wrote before it declared the text keep their text: nothing is +rewritten. + ## Recipe — refuse overlapping time ranges Leave and overtime requests share one rule: two live records of the same owner diff --git a/content/docs/references/api/protocol.mdx b/content/docs/references/api/protocol.mdx index e8da992fdaf..4027b6a360b 100644 --- a/content/docs/references/api/protocol.mdx +++ b/content/docs/references/api/protocol.mdx @@ -1876,7 +1876,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | -| **hooks** | `Record }>` | optional | Hook translations keyed by hook name | +| **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | | **permissions** | `Record` | optional | Permission-set translations keyed by permission-set name | | **books** | `Record }>` | optional | Doc-book translations keyed by book name | diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 4eeb32e2c0d..6dcd7ba1296 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -1,7 +1,7 @@ --- title: Hook schema — Data Protocol property reference navTitle: Hook -description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent, HookRefusal — each property with its type, default and a TypeScript example." +description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent and 2 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, ## TypeScript Usage ```typescript -import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema } from '@objectstack/spec/data'; -import type { Hook, HookContext, HookRefusal } from '@objectstack/spec/data'; +import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema, HookTextSchema } from '@objectstack/spec/data'; +import type { Hook, HookContext, HookRefusal, HookText } from '@objectstack/spec/data'; // Validate data const result = HookSchema.parse(data); @@ -43,6 +43,7 @@ const result = HookSchema.parse(data); | **timeout** | `never` | optional | [REMOVED] `hook.timeout` was removed in @objectstack/spec 17 — its unit (milliseconds) lived only in the description, beside a body-level `timeoutMs` and a `retryPolicy.backoffMs` that spell theirs, so the same number read as two conventions on one surface. Rename the key to `timeoutMs`; the value (milliseconds) is unchanged. Run `os migrate meta --from 17` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | | **onError** | `Enum<'abort' \| 'log'>` | optional (default: `"abort"`) | Error handling strategy. abort: refuse the operation; a blocking hook's abort rolls the write back inside a unit of work, which the write door opens for an after* hook on an object on the default datasource whose driver declares transactions (elsewhere the caller is refused and the row stays stored). log: log the error and continue | | **refusals** | `Record; params?: string[] }>` | optional | Refusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: `{ message, status?, reasons?, params? }`. The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through hooks.``.refusals.``.message, or ….``.reasons.``.message, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the hook throws it literally, otherwise at run time; under a code with no reasons a thrown reason is not read | +| **texts** | `Record` | optional | Texts the hook writes into records, keyed by the snake_case key its code asks for with ctx.text(KEY, params): `{ message, params? }`. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through hooks.``.texts.``.message with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the hook asks for it literally, otherwise at run time | | **runAs** | `Enum<'system' \| 'user' \| 'inherit'>` | optional (default: `"inherit"`) | Execution identity for the hook's ctx.api data operations: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting), inherit = the context of the write that fired the hook (the pre-runAs behaviour; the default). A hook with no trigger user has no identity to scope to, so under user its ctx.api data operations are REFUSED — declare system to make the elevation explicit. This covers any hook fired by a write that carried no user (an isSystem plugin/service write; a system-elevated flow node). Elevation does not reach identity assignment: a system hook's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED, and a system hook whose body names such a write is refused at save; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the hook acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system hook body's update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. Scope: ctx.api only — condition evaluation, the readonly strip on ctx.input, ctx.session and async are unchanged. | | **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). | | **_lockReason** | `string` | optional | Human-readable reason shown when a write is refused by _lock. | @@ -89,6 +90,13 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **reasons** | `Record` | optional | Further sentences under this same code, keyed by the snake_case reason the hook throws beside the code (`{ code, reason }`): `{ message }`. The wire code and status stay this entry's. A reason not declared here is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read | | **params** | `string[]` | optional | The names this entry's sentences may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the hook throws in `params` (`{ code, params: { NAME: value } }`). A hole over any other name, logic, an unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences are plain text and a `{{ }}` hole is refused | +### Nested Shape: `Hook.texts[string]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the hook writes into a record — in the source locale, translated whole through hooks.``.texts.``.message in the organization's language when the hook asks for it (ctx.text). With no params every `{{ }}` hole is refused; with params a hole is a path over one of them with an optional known formatter | +| **params** | `string[]` | optional | The names this text may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the hook passes in ctx.text(KEY, `{ NAME: value }`). A hole over any other name is refused at parse; a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a `{{ }}` hole is refused | + --- @@ -201,3 +209,15 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities --- +## HookText + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **message** | `string` | ✅ | The sentence the hook writes into a record — in the source locale, translated whole through hooks.``.texts.``.message in the organization's language when the hook asks for it (ctx.text). With no params every `{{ }}` hole is refused; with params a hole is a path over one of them with an optional known formatter | +| **params** | `string[]` | optional | The names this text may fill: a `{{ NAME }}` or `{{ NAME \| formatter }}` hole renders the value the hook passes in ctx.text(KEY, `{ NAME: value }`). A hole over any other name is refused at parse; a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a `{{ }}` hole is refused | + + +--- + diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 2cf24123d06..d6c69c93bff 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1668 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1669 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 81 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 36 | 496 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 187 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 188 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 177 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **218** | **1668** | 14 protocol modules | +| **Total** | **218** | **1669** | 14 protocol modules | --- @@ -139,7 +139,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 187 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 188 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -168,7 +168,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`field.zod.ts`](/docs/references/data/field) | `CurrencyConfig`, `Field`, `FieldMaskingKeep`, `FieldMaskingRule`, `FieldType`, `InlineGridColumn`, `LocationCoordinates`, `LookupFilterRecordReference`, `SelectOption`, `UniqueScope` | | [`field-value.zod.ts`](/docs/references/data/field-value) | `Address`, `AddressValue`, `CalendarDateValue`, `ClockTimeValue`, `FileLikeValue`, `FileReferenceIdValue`, `FileRefusedValue`, `FileValue`, `InstantValue`, `LocationValue`, `ReferenceIdValue`, `ReferenceNameOnlyValue` | | [`filter.zod.ts`](/docs/references/data/filter) | `ComparisonOperator`, `EqualityOperator`, `FieldOperators`, `FieldReference`, `FilterArray`, `FilterCondition`, `NormalizedFilter`, `NowAnchor`, `QueryFilter`, `RangeOperator`, `SetOperator`, `SpecialOperator`, `StringOperator` | -| [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal` | +| [`hook.zod.ts`](/docs/references/data/hook) | `Hook`, `HookContext`, `HookEvent`, `HookRefusal`, `HookText` | | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | diff --git a/content/docs/references/system/translation.mdx b/content/docs/references/system/translation.mdx index 0c52cf5211f..8fa67c8231d 100644 --- a/content/docs/references/system/translation.mdx +++ b/content/docs/references/system/translation.mdx @@ -189,7 +189,7 @@ Platform translation data — the per-app groups plus the platform-only `setting | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | -| **hooks** | `Record }>` | optional | Hook translations keyed by hook name | +| **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | | **permissions** | `Record` | optional | Permission-set translations keyed by permission-set name | | **books** | `Record }>` | optional | Doc-book translations keyed by book name | @@ -299,6 +299,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the hook's `texts` declares | ### Nested Shape: `PlatformTranslationData.positions[string]` @@ -369,7 +370,7 @@ Served translation data — the platform groups the browser reads, without the s | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | -| **hooks** | `Record }>` | optional | Hook translations keyed by hook name | +| **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | | **permissions** | `Record` | optional | Permission-set translations keyed by permission-set name | | **books** | `Record }>` | optional | Doc-book translations keyed by book name | @@ -478,6 +479,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the hook's `texts` declares | ### Nested Shape: `ServedTranslationData.positions[string]` @@ -611,7 +613,7 @@ Per-app translation data for objects, apps, and UI messages | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | -| **hooks** | `Record }>` | optional | Hook translations keyed by hook name | +| **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | | **permissions** | `Record` | optional | Permission-set translations keyed by permission-set name | | **books** | `Record }>` | optional | Doc-book translations keyed by book name | @@ -720,6 +722,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the hook's `texts` declares | ### Nested Shape: `TranslationData.positions[string]` @@ -811,7 +814,7 @@ One locale of translations — the `translation` metadata type | **reports** | `Record }>` | optional | Report translations keyed by report name | | **pages** | `Record` | optional | Page translations keyed by page name | | **flows** | `Record; … }>` | optional | Screen-flow translations keyed by flow name | -| **hooks** | `Record }>` | optional | Hook translations keyed by hook name | +| **hooks** | `Record; texts?: Record }>` | optional | Hook translations keyed by hook name | | **positions** | `Record` | optional | Position translations keyed by position name | | **permissions** | `Record` | optional | Permission-set translations keyed by permission-set name | | **books** | `Record }>` | optional | Doc-book translations keyed by book name | @@ -931,6 +934,7 @@ Translation data for a single object | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **refusals** | `Record }>` | optional | Refusal translations keyed by the code the hook's `refusals` declares | +| **texts** | `Record` | optional | Text translations keyed by the key the hook's `texts` declares | ### Nested Shape: `TranslationItem.positions[string]` diff --git a/content/docs/ui/translations.mdx b/content/docs/ui/translations.mdx index 1989336eb87..4d3fc2d0fd9 100644 --- a/content/docs/ui/translations.mdx +++ b/content/docs/ui/translations.mdx @@ -92,6 +92,7 @@ export default defineStack({ | Screen-flow wizards (flow label, screen headings and body text, screen field copy) | `flows..label` / `flows..screens..title` / `.description` / `.fields..label` / `.placeholder` / `.inlineHelpText` — a screen field's help text is `inlineHelpText`, the key the field itself declares, not `help`; see the boundary note below | | Text a flow writes into a record (a `create_record` / `update_record` field value marked `{ dialect: 'template', source }`) | `flows..records..fields.` — picked in the organization's language (the Localization setting when set, else the app's `i18n.defaultLocale`), never the run starter's; see [Flows](/docs/automation/flows#text-a-record-keeps--a-field-value-marked-as-text) | | Hook refusal messages | `hooks..refusals..message` — one per entry of the hook's `refusals` catalogue — and `hooks..refusals..reasons..message`, one per reason an entry declares. A hook (a `js` body or a TypeScript `handler`) refuses by code, optionally with a declared reason, and the server answers the refusal with this sentence in the caller's locale, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | +| Hook texts | `hooks..texts..message` — one per entry of the hook's `texts`. A hook asks for the sentence with `ctx.text(key, params)` when it writes it into a record, and the server answers it in the **organization's** language (the Localization setting somebody set, else the app's `i18n.defaultLocale`), never the caller's, else the declared one. A translation of an entry that declares `params` keeps its `{{ name }}` holes; the server fills them after picking the translation | | Position label / description | `positions..label` / `description` — keyed by the position's `name`; overlaid on every served position, which is the list the console's position picker draws | | Permission-set label / description | `permissions..label` / `description` — the group is spelled as the stack spells the collection (`permissions[]`), keyed by the set's `name` | | Doc book title, description and section titles | `books..label` / `description` / `groups..label` — keyed by the book's `name` and each group's `key`; overlaid on every served book and on the book tree, which is what the docs sidebar draws. A doc's own title and body localize through `doc.translations` instead | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md index 131e0eba14e..4485bdc5f92 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `data/` | 175 | 106 | 2 | 0 | 67 | +| `data/` | 176 | 107 | 2 | 0 | 67 | ## `data/` — sites @@ -51,7 +51,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `filter.zod.ts` | 13 | | `hook-body-doors.zod.ts` | 4 | | `hook-body.zod.ts` | 2 | -| `hook.zod.ts` | 9 | +| `hook.zod.ts` | 10 | | `mapping.zod.ts` | 8 | | `object.zod.ts` | 26 | | `picklist.zod.ts` | 3 | @@ -61,7 +61,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `seed-loader.zod.ts` | 12 | | `seed.zod.ts` | 2 | | `validation.zod.ts` | 6 | -| **total** | **175** | +| **total** | **176** | ## `data/` — open @@ -69,7 +69,7 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**67 strip of 175**, in 11 file(s). +**67 strip of 176**, in 11 file(s). | File | Strip | Sites | |---|---|---| @@ -80,11 +80,11 @@ over it is here. | `external-catalog.zod.ts` | 4 | 4 | | `field.zod.ts` | 1 | 16 | | `filter.zod.ts` | 11 | 13 | -| `hook.zod.ts` | 5 | 9 | +| `hook.zod.ts` | 5 | 10 | | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | -| **total** | **67** | **175** | +| **total** | **67** | **176** | | Bucket | Sites | |---|---| diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md index 3ae8141da10..74a96565703 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/system.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `system/` | 404 | +| `system/` | 405 | diff --git a/packages/core/src/organization-locale.test.ts b/packages/core/src/organization-locale.test.ts index d8bdd0705d5..cc3bb7d6aea 100644 --- a/packages/core/src/organization-locale.test.ts +++ b/packages/core/src/organization-locale.test.ts @@ -1,7 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi } from 'vitest'; -import { readOrganizationLocaleSetting, resolveOrganizationLocale } from './organization-locale.js'; +import { readOrganizationLocaleSetting, readOrganizationTextLocale, resolveOrganizationLocale } from './organization-locale.js'; /** A settings door answering `localization.locale` with `answer`, recording the scope it was asked in. */ function settingsAnswering(answer: { value?: unknown; source?: string } | undefined) { @@ -48,3 +48,41 @@ describe('resolveOrganizationLocale — the deployment-default ladder for text w expect(await readOrganizationLocaleSetting({ get: 'not a function' }, 'org_1')).toBeUndefined(); }); }); + +describe('readOrganizationTextLocale — the one reading every writer of organization text shares (#34374)', () => { + const services = (entries: Record) => (name: string): unknown => { + if (name in entries) return entries[name]; + throw new Error(`service '${name}' not registered`); + }; + const throwing = (code: string) => ({ get: vi.fn(async () => { throw Object.assign(new Error(code), { code }); }) }); + + it('answers the Localization setting somebody set, asked in the organization', async () => { + const settings = settingsAnswering({ value: 'ja-JP', source: 'tenant' }); + expect(await readOrganizationTextLocale(services({ settings, i18n: i18nDefault('zh-CN') }), 'org_1')).toBe('ja-JP'); + expect(settings.get).toHaveBeenCalledWith('localization', 'locale', { tenantId: 'org_1' }); + }); + + it('answers the app default when no settings service is registered, or none is set', async () => { + expect(await readOrganizationTextLocale(services({ i18n: i18nDefault('zh-CN') }), 'org_1')).toBe('zh-CN'); + expect(await readOrganizationTextLocale( + services({ settings: settingsAnswering({ value: 'en-US', source: 'default' }), i18n: i18nDefault('zh-CN') }), 'org_1', + )).toBe('zh-CN'); + }); + + it('answers an unregistered Localization namespace or key as not set', async () => { + for (const code of ['SETTINGS_UNKNOWN_NAMESPACE', 'SETTINGS_UNKNOWN_KEY']) { + expect(await readOrganizationTextLocale(services({ settings: throwing(code), i18n: i18nDefault('zh-CN') }), 'org_1')) + .toBe('zh-CN'); + } + }); + + it('rejects when the setting cannot be read for any other reason (never another language)', async () => { + await expect(readOrganizationTextLocale( + services({ settings: throwing('SETTINGS_STORE_UNAVAILABLE'), i18n: i18nDefault('zh-CN') }), 'org_1', + )).rejects.toThrow('SETTINGS_STORE_UNAVAILABLE'); + }); + + it('answers nothing with no service lookup at all', async () => { + expect(await readOrganizationTextLocale(undefined, 'org_1')).toBeUndefined(); + }); +}); diff --git a/packages/core/src/organization-locale.ts b/packages/core/src/organization-locale.ts index 95ed7ec1f43..cdede013921 100644 --- a/packages/core/src/organization-locale.ts +++ b/packages/core/src/organization-locale.ts @@ -114,3 +114,85 @@ export async function resolveOrganizationLocale( const declared = appDefaultLocale(input.i18n); return declared ? { locale: declared, source: 'app-default' } : undefined; } + +/** + * The settings service's refusal of a namespace or key nobody REGISTERED — + * `SETTINGS_UNKNOWN_NAMESPACE` / `SETTINGS_UNKNOWN_KEY`, as `@objectstack/objectql`'s + * home-localization bridge reads them. + */ +function isUnregisteredSetting(err: unknown): boolean { + const code = (err as { code?: unknown } | null | undefined)?.code; + return code === 'SETTINGS_UNKNOWN_NAMESPACE' || code === 'SETTINGS_UNKNOWN_KEY'; +} + +/** + * [ruling 6913660232, review 6924979595 S1] The settings door a WRITER of + * organization-language text hands {@link resolveOrganizationLocale} (through + * {@link readOrganizationTextLocale}): an + * unregistered `localization.locale` is answered as not set, so the next rung + * (the app's declared default) answers. A host that loads no `localization` + * manifest has no setting anybody could have set. Any other throw still + * propagates: the setting may exist and could not be read, and the writer + * fails rather than store another language over it. + * + * Shared by every writer of such text — the flow record write + * (`@objectstack/service-automation`) and a hook's or action's declared text + * (`ctx.text`, `@objectstack/runtime`, #34374) — and kept apart from the + * reader itself, so the seed loader's rung 1 keeps propagating every throw. + */ +function treatUnregisteredLocaleSettingAsUnset(settings: unknown): unknown { + const door = settings as { get?: unknown } | null | undefined; + if (!door || typeof door.get !== 'function') return settings; + const get = door.get as (namespace: string, key: string, ctx?: { tenantId?: string }) => Promise; + return { + async get(namespace: string, key: string, ctx?: { tenantId?: string }) { + try { + return await get.call(settings, namespace, key, ctx); + } catch (err: unknown) { + if (isUnregisteredSetting(err)) return undefined; + throw err; + } + }, + }; +} + +/** + * The organization's language for a sentence the platform WRITES into a record + * on the organization's behalf — the one reading every such writer shares: + * the flow record write's text field (`@objectstack/service-automation`) and a + * hook's or action's declared text (`ctx.text`, `@objectstack/runtime`, + * #34374). {@link resolveOrganizationLocale} over the `settings` and `i18n` + * services, both looked up at QUESTION time (a service registered after the + * caller bound is still found), with an unregistered Localization setting + * answered as not set. `undefined`: no rung answered, write the authored text. + * A settings read that throws rejects. + * + * NOT a second reading of the setting: rung 1 here IS + * {@link readOrganizationLocaleSetting}, reached through + * {@link resolveOrganizationLocale}. What this adds over that reader, for a + * writer only, and why the seed loader keeps calling that reader bare: + * + * | the setting answers… | `readOrganizationLocaleSetting` | this | + * | set (`source !== 'default'`) | the value | the value | + * | the `source: 'default'` placeholder | `undefined` | the app default | + * | no settings service | `undefined` | the app default | + * | `SETTINGS_UNKNOWN_NAMESPACE` / `…_KEY` | rejects | the app default | + * | any other throw | rejects | rejects | + * + * — rung 2 (the app's declared `i18n.defaultLocale`), an unregistered setting + * read as not set, and both services looked up at question time by name. + */ +export async function readOrganizationTextLocale( + getService: ((name: string) => unknown) | undefined, + organizationId: string | undefined, +): Promise { + let settings: unknown; + let i18n: unknown; + try { settings = getService?.('settings'); } catch { settings = undefined; } + try { i18n = getService?.('i18n'); } catch { i18n = undefined; } + return (await resolveOrganizationLocale({ + settings: treatUnregisteredLocaleSettingAsUnset(settings), + i18n, + organizationId, + }))?.locale; +} diff --git a/packages/lint/src/i18n-walk.test.ts b/packages/lint/src/i18n-walk.test.ts index c2481d0b509..4e19a0b2bef 100644 --- a/packages/lint/src/i18n-walk.test.ts +++ b/packages/lint/src/i18n-walk.test.ts @@ -64,6 +64,24 @@ describe('collectExpectedEntries', () => { }); }); +describe('collectExpectedEntries — a hook\'s declared texts (#34374)', () => { + const entries = collectExpectedEntries({ + hooks: [{ + name: 'lead_follow_up', + object: 'lead', + events: ['afterUpdate'], + body: { language: 'js', source: "await ctx.text('follow_up_subject', { lead: 'x' });" }, + texts: { follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] } }, + }], + }, { warnedGroups: new Set() }); + + it('yields hooks..texts..message with the declared sentence, from the hook', () => { + const entry = entries.find((e) => e.path.join('.') === 'hooks.lead_follow_up.texts.follow_up_subject.message'); + expect(entry?.sourceValue).toBe('Follow up with qualified lead: {{ lead }}'); + expect(entry?.source).toBe('hook'); + }); +}); + describe('authorWarnedTranslationGroups on the shipped ledger', () => { // A browser reads no ledger file, so there the default leaves no group out. // That matches the CLI only while the ledger warns on no translation group; diff --git a/packages/lint/src/i18n-walk.ts b/packages/lint/src/i18n-walk.ts index 568e6d84b71..225c5f24cf3 100644 --- a/packages/lint/src/i18n-walk.ts +++ b/packages/lint/src/i18n-walk.ts @@ -140,6 +140,7 @@ * (see `authorWarnedTranslationGroups`) * hooks..refusals..message (#26170) * hooks..refusals..reasons..message (#33214) + * hooks..texts..message (#34374) * positions..label / .description * permissions..label / .description * books..label / .description @@ -1756,6 +1757,9 @@ export function collectExpectedEntries( // ── Hook refusal catalogues (`hooks..refusals..message`) ─ walkHookRefusals(config, out); + // ── Hook texts (`hooks..texts..message`, #34374) ───── + walkHookTexts(config, out); + // ── Object sections (fieldGroups + authored form/page sections) ─── // Deliberately a pass of its own: the two authoring surfaces live in // `objects`, `views` and `pages`, and one section may be declared by more @@ -2448,6 +2452,29 @@ function walkHookRefusals(config: any, out: ExpectedEntry[]): void { } } +/** + * Emit `hooks..texts..message` for every text a hook declares + * (#34374, ruling 6913660232 parameter 7), seeded with the declared message. + * + * The hook runtime reads exactly that key (`hookTextMessageKey`) in the + * organization's language when the hook asks for the text (`ctx.text`), so + * each declared text is one demand, counted under the `hook` bucket like a + * refusal, and `os i18n extract` scaffolds it (parameter 5: the existing + * coverage check demands it, no new gate). Keyed by hook name. + */ +function walkHookTexts(config: any, out: ExpectedEntry[]): void { + const hooks: any[] = Array.isArray(config?.hooks) ? config.hooks : []; + for (const hook of hooks) { + const hookName = typeof hook?.name === 'string' && hook.name.length > 0 ? hook.name : undefined; + if (!hookName) continue; + const texts = hook.texts; + if (!texts || typeof texts !== 'object' || Array.isArray(texts)) continue; + for (const [key, entry] of Object.entries(texts)) { + pushOptional(out, ['hooks', hookName, 'texts', key, 'message'], inlineText(entry?.message), 'hook'); + } + } +} + /** * Iterate the canonical metadata form registry and emit translation entries * for every metadata type's display label/description, plus the section and diff --git a/packages/lint/src/validate-hook-refusal-templates.test.ts b/packages/lint/src/validate-hook-refusal-templates.test.ts index 87b1095a34b..1873054e4ca 100644 --- a/packages/lint/src/validate-hook-refusal-templates.test.ts +++ b/packages/lint/src/validate-hook-refusal-templates.test.ts @@ -80,3 +80,80 @@ describe('hook refusal templates over declared params (#33214)', () => { expect(finding!.severity).toBe('error'); }); }); + +describe('hook text templates over declared params (#34374)', () => { + const textHook = (texts: Record) => ({ + name: 'lead_follow_up', + object: 'crm_lead', + events: ['afterUpdate'], + handler: 'leadFollowUp', + texts, + }); + const textIssues = (message: string, params: string[] | null = ['lead']) => + hookRefusalTemplateIssues({ hooks: [textHook({ follow_up_subject: params ? { message, params } : { message } })] }); + + it.each([ + 'Follow up: {{ lead }}', + 'Follow up: {{ lead | upper }}', + 'Worth {{ lead | currency:EUR }}', + 'Plain text with no hole.', + ])('CONTROL: accepts %j', (message) => { + expect(textIssues(message)).toEqual([]); + }); + + it.each([ + ['an unknown formatter', 'Follow up: {{ lead | shout }}'], + ['logic', 'Follow up: {{ lead + 1 }}'], + ['an empty hole', 'Follow up: {{ }}'], + ])('refuses %s as an error at texts..message', (_label, message) => { + const issues = textIssues(message); + expect(issues.length).toBeGreaterThan(0); + expect(issues.every((i) => i.severity === 'error')).toBe(true); + expect(issues[0]!.where).toBe("hook 'lead_follow_up' texts.follow_up_subject.message"); + }); + + it('refuses a currency formatter with no code, naming the spelling that names one', () => { + const issues = textIssues('Worth {{ lead | currency }}'); + expect(issues).toHaveLength(1); + expect(issues[0]).toMatchObject({ severity: 'error', source: '{{ lead | currency }}' }); + expect(issues[0]!.message).toContain('{{ lead | currency:EUR }}'); + }); + + it('reads no text that declares no params — the parse refuses every hole there', () => { + expect(textIssues('Follow up: {{ lead | shout }}', null)).toEqual([]); + }); + + it('judges a text beside the same hook\'s refusals, each at its own path', () => { + const issues = hookRefusalTemplateIssues({ + hooks: [{ + ...textHook({ follow_up_subject: { message: 'Follow up: {{ lead | shout }}', params: ['lead'] } }), + refusals: { VALIDATION_FAILED: { message: 'The plan is {{ state | shout }}.', params: ['state'] } }, + }], + }); + expect(issues.map((i) => i.where).sort()).toEqual([ + "hook 'lead_follow_up' refusals.VALIDATION_FAILED.message", + "hook 'lead_follow_up' texts.follow_up_subject.message", + ]); + }); + + it('is part of the stack expression pass `objectstack validate` and `compile` run', () => { + const issues = validateStackExpressions({ + hooks: [textHook({ follow_up_subject: { message: 'Follow up: {{ lead | shout }}', params: ['lead'] } })], + } as never); + expect(issues.some((i) => i.where === "hook 'lead_follow_up' texts.follow_up_subject.message" && i.severity === 'error')).toBe(true); + }); + + it('refuses a `hook` write at the publish gate, and passes the CONTROL', () => { + const gate = (message: string) => runRuntimeAuthoringRules({ + type: 'hook', + item: textHook({ follow_up_subject: { message, params: ['lead'] } }), + context: { objects: [] }, + }); + const refused = gate('Worth {{ lead | currency }}'); + const finding = refused.errors.find((e) => String(e.message).includes('{{ lead | currency:EUR }}')); + expect(finding, JSON.stringify(refused.errors)).toBeDefined(); + expect(finding!.severity).toBe('error'); + const control = gate('Worth {{ lead | currency:EUR }}'); + expect(control.errors.filter((e) => String(e.message).includes('currency'))).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-hook-refusal-templates.ts b/packages/lint/src/validate-hook-refusal-templates.ts index 0db7d236ef3..a77a3ecd310 100644 --- a/packages/lint/src/validate-hook-refusal-templates.ts +++ b/packages/lint/src/validate-hook-refusal-templates.ts @@ -21,6 +21,12 @@ * flow run carries and a hook refusal does not, so the runtime cannot render * it either. It is refused with the spelling that names the code. * + * [#34374] A hook's declared texts (`HookSchema.texts`) are the same kind of + * sentence, filled by the same engine from the same closed scope, so an entry + * of `texts` that declares `params` is judged here too, at `texts..message` + * — a text that cannot render would otherwise reach the business record with + * its braces. + * * Every finding is an ERROR: `objectstack validate` and `compile` fail, and the * publish gate refuses a `hook` write carrying one (the `hook` write type runs * this pass with the hook-`condition` walk it sits beside). An entry that @@ -52,43 +58,50 @@ function currencyWithoutCode(holeText: string, inner: string): string | undefine if (formatter !== 'currency') return undefined; const path = inner.slice(0, bar).trim() || 'amount'; return ( - `\`${holeText}\` formats in the organization's default currency, which a hook refusal does not carry, so the ` + `\`${holeText}\` formats in the organization's default currency, which a hook sentence does not carry, so the ` + 'sentence would be served with its braces. Name the code in the hole: ' + `\`{{ ${path} | currency:EUR }}\`.` ); } /** - * The findings for every hook refusal sentence of `stack` whose entry declares - * `params` (see the module header). + * The findings for every hook sentence of `stack` whose entry declares + * `params` — each refusal entry's `message` and `reasons[*].message`, and + * (#34374) each declared text's `message` (see the module header). */ export function hookRefusalTemplateIssues(stack: AnyRec): ExprIssue[] { const issues: ExprIssue[] = []; for (const hook of recordsOf(stack.hooks)) { const hookName = typeof hook.name === 'string' ? hook.name : '?'; - if (!isRec(hook.refusals)) continue; - for (const [code, entry] of Object.entries(hook.refusals)) { - if (!isRec(entry)) continue; - const params = paramsOf(entry); - if (params.length === 0) continue; - const sentences: Array<{ path: string; text: unknown }> = [{ path: `refusals.${code}.message`, text: entry.message }]; - if (isRec(entry.reasons)) { - for (const [reason, sentence] of Object.entries(entry.reasons)) { - sentences.push({ path: `refusals.${code}.reasons.${reason}.message`, text: isRec(sentence) ? sentence.message : undefined }); + const sentences: Array<{ path: string; text: unknown }> = []; + if (isRec(hook.refusals)) { + for (const [code, entry] of Object.entries(hook.refusals)) { + if (!isRec(entry) || paramsOf(entry).length === 0) continue; + sentences.push({ path: `refusals.${code}.message`, text: entry.message }); + if (isRec(entry.reasons)) { + for (const [reason, sentence] of Object.entries(entry.reasons)) { + sentences.push({ path: `refusals.${code}.reasons.${reason}.message`, text: isRec(sentence) ? sentence.message : undefined }); + } } } - for (const { path, text } of sentences) { - if (typeof text !== 'string') continue; - const where = `hook '${hookName}' ${path}`; - const refuse = (message: string, source: string): void => { - issues.push({ where, message, source, severity: 'error' }); - }; - for (const m of text.matchAll(HOLE)) { - const refusal = currencyWithoutCode(m[0], m[1]!); - if (refusal !== undefined) refuse(refusal, m[0]); - } - for (const e of validateExpression('template', text).errors) refuse(e.message, e.source); + } + if (isRec(hook.texts)) { + for (const [key, entry] of Object.entries(hook.texts)) { + if (!isRec(entry) || paramsOf(entry).length === 0) continue; + sentences.push({ path: `texts.${key}.message`, text: entry.message }); + } + } + for (const { path, text } of sentences) { + if (typeof text !== 'string') continue; + const where = `hook '${hookName}' ${path}`; + const refuse = (message: string, source: string): void => { + issues.push({ where, message, source, severity: 'error' }); + }; + for (const m of text.matchAll(HOLE)) { + const refusal = currencyWithoutCode(m[0], m[1]!); + if (refusal !== undefined) refuse(refusal, m[0]); } + for (const e of validateExpression('template', text).errors) refuse(e.message, e.source); } } return issues; diff --git a/packages/lint/src/validate-translation-references.test.ts b/packages/lint/src/validate-translation-references.test.ts index 614a7c55769..608dfae51fe 100644 --- a/packages/lint/src/validate-translation-references.test.ts +++ b/packages/lint/src/validate-translation-references.test.ts @@ -4922,6 +4922,47 @@ describe('validateTranslationReferences — hook refusals (#26170)', () => { }); }); +describe('validateTranslationReferences — hook texts (#34374)', () => { + const textStack = { + hooks: [ + { + name: 'lead_follow_up', + object: 'lead', + events: ['afterUpdate'], + body: { language: 'js', source: "await ctx.text('follow_up_subject', { lead: ctx.input.name });" }, + texts: { follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] } }, + }, + { name: 'stamp', object: 'lead', events: ['beforeInsert'], handler: 'stamp' }, + ], + }; + const bundle = (hooks: unknown) => ({ ...textStack, translations: [{ 'zh-CN': { hooks } }] }); + + it('reports nothing for a translation of a declared text', () => { + expect(validateTranslationReferences( + bundle({ lead_follow_up: { texts: { follow_up_subject: { message: '跟进已认定线索:{{ lead }}' } } } }), + )).toEqual([]); + }); + + it('refuses a text key the hook does not declare, with the nearest declared key offered', () => { + const findings = validateTranslationReferences( + bundle({ lead_follow_up: { texts: { follow_up_subjct: { message: 'x' } } } }), + ); + expect(findings).toHaveLength(1); + expect(findings[0].rule).toBe(TRANSLATION_TARGET_UNKNOWN); + expect(findings[0].severity).toBe('error'); + expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.lead_follow_up.texts.follow_up_subjct'); + expect(findings[0].message).toContain('a key hook "lead_follow_up" does not declare under `texts`'); + expect(findings[0].message).toContain('Did you mean "follow_up_subject"?'); + }); + + it('refuses a text key on a hook that declares no texts', () => { + const findings = validateTranslationReferences(bundle({ stamp: { texts: { anything: { message: 'x' } } } })); + expect(findings).toHaveLength(1); + expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.stamp.texts.anything'); + expect(findings[0].message).toContain('hook "stamp" declares no `texts`'); + }); +}); + describe('validateTranslationReferences — hook refusal reasons (#33214)', () => { const planStack = { hooks: [ diff --git a/packages/lint/src/validate-translation-references.ts b/packages/lint/src/validate-translation-references.ts index 0304d69749f..b52150aa1d2 100644 --- a/packages/lint/src/validate-translation-references.ts +++ b/packages/lint/src/validate-translation-references.ts @@ -132,7 +132,9 @@ * refusal catalogue: the hook must be one the stack defines (or a sibling * package's, through the artifact carrier), and the code one its `refusals` * declares — the body runner reads the key for a declared code and nothing - * else. An unknown hook and an undeclared code are each an orphan. + * else. An unknown hook and an undeclared code are each an orphan. So is + * (#34374) a `hooks..texts.` key over a text the hook's `texts` + * does not declare: `ctx.text` reads the key for a declared text only. * * `flows..successMessage` / `.errorMessage` (#22507), the terminal * toasts, are judged against the flow itself: `translateFlow` overlays a toast @@ -564,6 +566,8 @@ interface Universe { */ /** [#26170] Each hook's declared refusal codes, and (#33214) each code's declared reasons. */ hooks: Map>>; + /** [#34374] Each hook's declared text keys (`HookSchema.texts`) — what a `hooks..texts.` key may name. */ + hookTexts: Map>; /** Object-less actions — the ones `globalActions.*` may name. */ globalActions: Map; /** Action name → owning object, so a misfiled `globalActions` key can say where it belongs. */ @@ -1689,6 +1693,7 @@ function buildUniverse(stack: AnyRec): Universe { // the artifact carrier; the declaration this leg is JUDGING keeps the slot, // the flows' decision. const hooks = new Map>>(); + const hookTexts = new Map>(); const collectHookRecord = (hook: AnyRec, { ownDeclaration }: { ownDeclaration: boolean }) => { const hookName = strName(hook.name); if (!hookName) return; @@ -1698,6 +1703,8 @@ function buildUniverse(stack: AnyRec): Universe { codes.set(code, new Set(Object.keys(asRecord(isRec(entry) ? entry.reasons : undefined)))); } hooks.set(hookName, codes); + // [#34374] The text keys `hooks..texts.` may name. + hookTexts.set(hookName, new Set(Object.keys(asRecord(hook.texts)))); }; for (const hook of recordsOf(stack.hooks)) collectHookRecord(hook, { ownDeclaration: true }); for (const hook of artifactProvidedRecords(stack, 'hooks')) { @@ -1806,6 +1813,7 @@ function buildUniverse(stack: AnyRec): Universe { dashboards, flows, hooks, + hookTexts, globalActions, actionOwners, picklists, @@ -2552,7 +2560,7 @@ export function validateTranslationReferences(stack: AnyRec): TranslationRefFind `${inLocale} · hook "${hookName}"`, hookPath, `Translations are keyed to hook "${hookName}", which this stack does not define, so its ` + - `refusals keep their declared messages.` + + `refusals and texts keep their declared messages.` + suggest(hookName, universe.hooks.keys()), `Match the key to a hook's \`name\`, or drop it.`, ); @@ -2593,6 +2601,23 @@ export function validateTranslationReferences(stack: AnyRec): TranslationRefFind `or drop the key.`, ); } + // ── hooks..texts. (#34374) ───────────────────────────── + const texts = universe.hookTexts.get(hookName) ?? new Set(); + for (const key of Object.keys(asRecord(rawHook.texts))) { + if (texts.has(key)) continue; + orphan( + `${inLocale} · hook "${hookName}" · text "${key}"`, + `${hookPath}.texts.${key}`, + texts.size === 0 + ? `Translations are keyed to text "${key}", but hook "${hookName}" declares no \`texts\`, so ` + + `nothing resolves this key.` + : `Translations are keyed to text "${key}", a key hook "${hookName}" does not declare under ` + + `\`texts\`, so nothing resolves this key.` + + suggest(key, texts), + `Text translations are keyed by a key the hook's \`texts\` declares; declare it there, or drop ` + + `the key.`, + ); + } } } } diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 94583374385..c8f606b6802 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -386,9 +386,11 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // holders the security plugin moves to the renamed position at boot. // [#34167] `skill` 16 → 17: `mcpPrompt`, the owner's opt-out of MCP // prompt projection for a skill written for the in-product agents only. + // [#34374] `hook` 23 → 24: the declared texts, `texts`, a hook's + // sentences written into records in the organization's language. const CARD_PROPERTY_COUNTS: Record = { agent: 24, app: 24, dashboard: 21, dataset: 17, field: 83, flow: 23, - hook: 23, object: 50, page: 28, position: 14, report: 24, skill: 17, tool: 14, + hook: 24, object: 50, page: 28, position: 14, report: 24, skill: 17, tool: 14, }; it.each(Object.entries(CARD_PROPERTY_COUNTS))( diff --git a/packages/runtime/src/app-artifact-handlers.ts b/packages/runtime/src/app-artifact-handlers.ts index 0479cc8071f..39343709257 100644 --- a/packages/runtime/src/app-artifact-handlers.ts +++ b/packages/runtime/src/app-artifact-handlers.ts @@ -436,8 +436,11 @@ export function bindAppArtifactHandlers( // applies it after resolving the name, so both take this one wrap. // [#33214] …and its throws are answered against the hook's refusal // catalogue, in the caller's language, with the body path's wire. + // [#34374] …and handed `ctx.text`, the hook's declared texts in + // the organization's language, read through the same services. wrapHandler: (handler, hook) => withInProcessHookTitle(handler, ql, hook, { i18n: options.i18n, + getService: options.getService, logger, }), }); diff --git a/packages/runtime/src/sandbox/body-runner.ts b/packages/runtime/src/sandbox/body-runner.ts index 0f39e9855c9..d184049422d 100644 --- a/packages/runtime/src/sandbox/body-runner.ts +++ b/packages/runtime/src/sandbox/body-runner.ts @@ -82,6 +82,7 @@ import { type HookRefusalI18nSource, } from './hook-refusal-catalogue.js'; import { isRelayedSandboxRefusal } from './quickjs-runner.js'; +import { buildHookTextSurface } from './hook-text.js'; import { buildBodyDoors, callerScopeOf, type BodyDoorCaller } from './body-doors.js'; import { deriveHookApi, openTransactionKind, seedHookUnreadMembership, seedHookUserGrants } from '@objectstack/objectql'; @@ -369,7 +370,7 @@ function buildTitleSurface( export function withInProcessHookTitle( handler: (ctx: any) => unknown, ql: unknown, - hook: string | Pick, + hook: string | Pick, opts: InProcessHookOptions = {}, ): (ctx: any) => Promise { const hookName = typeof hook === 'string' ? hook : String(hook.name); @@ -382,15 +383,24 @@ export function withInProcessHookTitle( const readTitle = async (field?: unknown): Promise => (await surface(field === undefined || field === null ? undefined : String(field), undefined)) ?? null; const title = catalogued ? inProcessHostSurface(readTitle) : readTitle; + // [#34374] The hook's declared texts, in the organization's language — the + // body's `ctx.text`, built by the same function. + const readText = buildHookTextSurface( + typeof hook === 'string' ? { name: hook } : (hook as Pick), + engineCtx, + { i18n: opts.i18n, getService: opts.getService, logger: opts.logger }, + ); + const text = catalogued ? inProcessHostSurface(readText) : readText; const view = new Proxy(engineCtx, { get: (target, prop) => { if (prop === 'title') return title; + if (prop === 'text') return text; const value = Reflect.get(target, prop); // [#33214] The host surfaces a handler calls: what they raise is the // platform's, never the handler's refusal. return catalogued && (prop === 'api' || prop === 'ql') ? inProcessHostSurface(value) : value; }, - has: (target, prop) => prop === 'title' || Reflect.has(target, prop), + has: (target, prop) => prop === 'title' || prop === 'text' || Reflect.has(target, prop), }); if (!catalogued) return handler(view); try { @@ -405,6 +415,12 @@ export function withInProcessHookTitle( export interface InProcessHookOptions { /** The `i18n` service a declared refusal is translated through, read at refusal time. */ i18n?: HookRefusalI18nSource; + /** + * [#34374] Kernel service lookup, read at call time — the `settings` and + * `i18n` services a declared text's organization language is read from. + * Absent: `ctx.text` answers the declared message. + */ + getService?: (name: string) => unknown; logger?: { warn?: (...args: any[]) => void }; } @@ -536,6 +552,7 @@ export function hookBodyRunnerFactory( opts.ql, buildBodyLogSurface(opts, { kind: 'hook', name: hook.name }), buildTitleSurface(engineCtx, opts.ql, { kind: 'hook', name: hook.name }), + buildHookTextSurface(hook, engineCtx, { i18n: opts.i18n, getService: opts.getService, logger: opts.logger }), ); installBodyDoors( sandboxCtx, @@ -1430,6 +1447,7 @@ function buildSandboxContext( ql: any, log: ScriptContext['log'], title?: ScriptContext['title'], + text?: ScriptContext['text'], ): ScriptContext { // `input` and `previous` are the engine's own spellings, and the only ones: // `HookContextSchema` (`packages/spec/src/data/hook.zod.ts`) declares neither a @@ -1540,6 +1558,9 @@ function buildSandboxContext( // sites; widening the accessor to it is a separate capability call and is // deliberately not taken here — the ruling names hook bodies. title, + // [#34374] Hook face only: the hook's declared texts, answered in the + // organization's language (`hook-text.ts`). + ...(text ? { text } : {}), // [#11552] Hook face only, both of them: an action is never one of N // dispatches for one write, and its params bag has no caller options. dispatch, diff --git a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts index 145db461235..81dcd370f59 100644 --- a/packages/runtime/src/sandbox/hook-refusal-catalogue.ts +++ b/packages/runtime/src/sandbox/hook-refusal-catalogue.ts @@ -136,8 +136,11 @@ function catalogueOf(hook: Pick): Record) : undefined; } -/** The locale the service can answer in for `requested` — `resolveBundleLocale` against what it holds. */ -function negotiatedLocale(service: HookRefusalI18nService, requested: string): string { +/** + * The locale the service can answer in for `requested` — `resolveBundleLocale` + * against what it holds. Shared with a hook's declared text (`hook-text.ts`). + */ +export function negotiatedLocale(service: HookRefusalI18nService, requested: string): string { if (typeof service.getLocales !== 'function') return requested; let available: unknown; try { @@ -169,6 +172,31 @@ export function fillHookRefusalParams( params: Record | undefined, logger?: { warn?: (...args: any[]) => void }, ): string { + const result = renderHookTemplate(template, declared, params); + if (result.ok) return result.value; + logger?.warn?.( + `[BodyRunner] hook '${hookName}': its refusal sentence did not render (${result.error}), ` + + 'so it is served as written.', + ); + return template; +} + +/** What {@link renderHookTemplate} answers: the filled sentence, or why it did not render. */ +export type HookTemplateRender = { ok: true; value: string } | { ok: false; error: string }; + +/** + * One declared hook sentence with its `{{ NAME }}` holes filled from `params`: + * the engine and the scope rule {@link fillHookRefusalParams} uses (only the + * entry's declared names are in scope), answering a failure instead of choosing + * a fallback, so each caller states its own. Shared with a hook's declared text + * (#34374, `hook-text.ts`), which falls back from a translation that does not + * render to the declared sentence. + */ +export function renderHookTemplate( + template: string, + declared: readonly string[], + params: Record | undefined, +): HookTemplateRender { const scope: Record = {}; for (const name of declared) { scope[name] = params && Object.prototype.hasOwnProperty.call(params, name) ? params[name] : undefined; @@ -179,12 +207,9 @@ export function fillHookRefusalParams( } catch (err: unknown) { result = { ok: false, error: { message: err instanceof Error ? err.message : String(err) } }; } - if (result.ok) return String(result.value ?? ''); - logger?.warn?.( - `[BodyRunner] hook '${hookName}': its refusal sentence did not render (${result.error?.message ?? 'unknown'}), ` - + 'so it is served as written.', - ); - return template; + return result.ok + ? { ok: true, value: String(result.value ?? '') } + : { ok: false, error: result.error?.message ?? 'unknown' }; } /** diff --git a/packages/runtime/src/sandbox/hook-text.integration.test.ts b/packages/runtime/src/sandbox/hook-text.integration.test.ts new file mode 100644 index 00000000000..78781a04ddf --- /dev/null +++ b/packages/runtime/src/sandbox/hook-text.integration.test.ts @@ -0,0 +1,240 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34374, ruling 6913660232 option B, parameter 7] A sentence a hook writes + * into a record for people to read is written in the ORGANIZATION's language. + * + * The hook declares it (`HookSchema.texts`) and asks for it by key — + * `await ctx.text('follow_up_subject', { lead })` — and the runtime answers + * the translation `hooks..texts..message` in the organization's + * language (the Localization setting somebody set, else the app's + * `i18n.defaultLocale`; never the caller's), the declared sentence on a miss, + * its holes filled after. + * + * The HotCRM shape this card carries (hotcrm#2494): an `afterUpdate` hook that + * opens a follow-up task when a lead qualifies, titled with the lead's name. + * Same wiring as the sibling signal pins: the REAL `ObjectQL` + REAL + * `SqlDriver` (better-sqlite3) + REAL `QuickJSScriptRunner` behind + * `hookBodyRunnerFactory`, with the REAL in-memory `i18n` service; the + * in-process half runs through the binder's own `wrapHandler` seam, + * `withInProcessHookTitle`, as `bindAppArtifactHandlers` composes it. Every + * assertion lands on the task row the hook stored. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { createMemoryI18n } from '@objectstack/core'; +import type { DataEngineInsertOptions, EngineQueryOptions, EngineUpdateOptions } from '@objectstack/spec/data'; +import { hookBodyRunnerFactory, withInProcessHookTitle } from './body-runner.js'; +import { hookRefusalI18nReader } from './hook-refusal-catalogue.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; +import { + captureExpectedReadRefusals, + type ExpectedReadRefusalCapture, +} from '../expected-read-refusal-noise.js'; + +const LEAD = { name: 'probe_text_lead', fields: { name: { type: 'text' }, status: { type: 'text' } } }; +const TASK = { name: 'probe_text_task', fields: { subject: { type: 'text' }, lead_id: { type: 'text' } } }; + +const HOOK_NAME = 'probe_lead_follow_up'; +const EN = 'Follow up with qualified lead: {{ lead }}'; +const ZH = '跟进已认定线索:{{ lead }}'; +const JA = '有望リードのフォローアップ:{{ lead }}'; + +/** The body the build lowers the HotCRM handler to: one declared text, asked for by key. */ +const BODY_SOURCE = ` + if (ctx.input.status !== 'qualified') return; + var subject = await ctx.text(ctx.input.name === 'Undeclared' ? 'no_such_text' : 'follow_up_subject', { lead: ctx.input.name }); + await ctx.api.object('${TASK.name}').insert({ subject: subject, lead_id: ctx.input.id }); +`; + +/** The same hook as an in-process handler (a source boot runs it unlowered). */ +async function inProcessHandler(ctx: any): Promise { + if (ctx.input.status !== 'qualified') return; + const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name }); + await ctx.api.object(TASK.name).insert({ subject, lead_id: ctx.input.id }); +} + +const TEXTS = { follow_up_subject: { message: EN, params: ['lead'] } }; + +const SYSTEM_READ: EngineQueryOptions = { context: { isSystem: true } }; + +/** What the `settings` service answers for `localization.locale`. */ +type SettingsAnswer = { value?: unknown; source?: string } | (() => never); + +interface StackOptions { + /** The app's declared `i18n.defaultLocale`. */ + defaultLocale?: string; + /** Translation bundles by locale. */ + bundles?: Record>; + /** What the settings service answers; absent ⇒ the host has no settings service. */ + settings?: SettingsAnswer; + /** Run the hook in-process (a `handler`) instead of as a sandboxed body. */ + inProcess?: boolean; + /** Collects every `logger.warn` line the runtime writes. */ + warnings?: string[]; +} + +const ABSENT_TENANCY_TABLE = 'sys_organization'; + +function bundle(sentence: string) { + return { hooks: { [HOOK_NAME]: { texts: { follow_up_subject: { message: sentence } } } } }; +} + +describe('#34374 — a hook writes its declared text in the organization\'s language (ctx.text)', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + let noise: ExpectedReadRefusalCapture | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function makeStack(options: StackOptions = {}) { + dir = mkdtempSync(join(tmpdir(), 'os-34374-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + noise = captureExpectedReadRefusals([ABSENT_TENANCY_TABLE]); + noise.captureDriver(driver); + await driver.initObjects([LEAD, TASK]); + engine = new ObjectQL(); + noise.captureEngine(engine); + engine.registerDriver(driver, true); + await engine.init(); + engine.registry.registerObject(LEAD as any, 'probe'); + engine.registry.registerObject(TASK as any, 'probe'); + + const i18n = createMemoryI18n(); + if (options.defaultLocale) i18n.setDefaultLocale(options.defaultLocale); + for (const [locale, data] of Object.entries(options.bundles ?? {})) i18n.loadTranslations(locale, data); + const asked: Array<{ tenantId?: string } | undefined> = []; + const settings = options.settings === undefined ? undefined : { + async get(_ns: string, _key: string, ctx?: { tenantId?: string }) { + asked.push(ctx); + const answer = options.settings!; + if (typeof answer === 'function') answer(); + return answer as { value?: unknown; source?: string }; + }, + }; + const services: Record = { i18n, ...(settings ? { settings } : {}) }; + const getService = (name: string): unknown => { + if (name in services) return services[name]; + throw new Error(`service '${name}' not registered`); + }; + const i18nSource = hookRefusalI18nReader({ getService: getService as never }); + const logger = { + debug: () => {}, info: () => {}, error: () => {}, + warn: (...args: unknown[]) => { options.warnings?.push(args.map(String).join(' ')); }, + }; + + if (options.inProcess) { + const hook = { name: HOOK_NAME, object: LEAD.name, events: ['afterUpdate'], handler: inProcessHandler, texts: TEXTS }; + bindHooksToEngine(engine, [hook as any], { + packageId: 'probe', + wrapHandler: (handler, bound) => withInProcessHookTitle(handler as any, engine, bound as any, { + i18n: i18nSource, getService, logger, + }), + }); + } else { + engine.setDefaultBodyRunner( + hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'probe', logger, i18n: i18nSource, getService }), + ); + bindHooksToEngine(engine, [{ + name: HOOK_NAME, + object: LEAD.name, + events: ['afterUpdate'], + body: { language: 'js', source: BODY_SOURCE, capabilities: ['api.read', 'api.write'] }, + texts: TEXTS, + } as any], { packageId: 'probe' }); + } + return { engine, asked }; + } + + /** Qualify a lead as a caller whose own language is en-US, in organization `org_a`; answer the stored task subjects. */ + async function qualify(ql: ObjectQL, name: string): Promise { + const context = { userId: 'u_probe', isSystem: true, tenantId: 'org_a', locale: 'en-US' }; + const asCaller: DataEngineInsertOptions = { context }; + const lead: any = await ql.insert(LEAD.name, { name, status: 'new' }, asCaller); + // The update carries the name, so the hook reads it from its own input. + const qualifyIt: EngineUpdateOptions = { context, where: { id: lead.id } }; + await ql.update(LEAD.name, { name, status: 'qualified' }, qualifyIt); + const tasks: any[] = await ql.find(TASK.name, SYSTEM_READ); + return tasks.map((t) => t.subject); + } + + for (const inProcess of [false, true]) { + const path = inProcess ? 'in-process handler' : 'sandboxed body'; + + describe(path, () => { + it('writes the app default language\'s translation for an en-US caller (no Localization setting), holes filled', async () => { + const { engine: ql } = await makeStack({ + inProcess, defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH), 'en-US': bundle('EN-US VARIANT {{ lead }}') }, + }); + expect(await qualify(ql, 'Acme')).toEqual(['跟进已认定线索:Acme']); + }, 30000); + + it('writes the language somebody SET in Localization, asked for the write\'s organization; CONTROL: the default placeholder does not count', async () => { + const bundles = { 'zh-CN': bundle(ZH), 'ja-JP': bundle(JA) }; + const set = await makeStack({ inProcess, defaultLocale: 'zh-CN', bundles, settings: { value: 'ja-JP', source: 'organization' } }); + expect(await qualify(set.engine, 'Acme')).toEqual(['有望リードのフォローアップ:Acme']); + expect(set.asked).toContainEqual({ tenantId: 'org_a' }); + await engine?.destroy(); engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + + const placeholder = await makeStack({ inProcess, defaultLocale: 'zh-CN', bundles, settings: { value: 'en-US', source: 'default' } }); + expect(await qualify(placeholder.engine, 'Acme')).toEqual(['跟进已认定线索:Acme']); + }, 30000); + + it('writes the declared sentence, holes filled, when the organization\'s language has no translation — and the hook goes on', async () => { + const { engine: ql } = await makeStack({ inProcess, defaultLocale: 'fr-FR', bundles: { 'zh-CN': bundle(ZH) } }); + expect(await qualify(ql, 'Acme')).toEqual(['Follow up with qualified lead: Acme']); + }, 30000); + + it('writes the declared sentence, filled, when the translation\'s holes do not render — never the braces; CONTROL: a translation that renders is written', async () => { + const warnings: string[] = []; + const { engine: ql } = await makeStack({ + inProcess, defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle('跟进已认定线索:{{ lead | shout }}') }, warnings, + }); + expect(await qualify(ql, 'Acme')).toEqual(['Follow up with qualified lead: Acme']); + expect(warnings.some((w) => w.includes("the zh-CN translation of its text 'follow_up_subject' did not render") + && w.includes('so the declared text is written'))).toBe(true); + await engine?.destroy(); engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + + const control = await makeStack({ inProcess, defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle('跟进:{{ lead | upper }}') } }); + expect(await qualify(control.engine, 'Acme')).toEqual(['跟进:ACME']); + }, 30000); + + it('answers an unregistered Localization setting as not set (the app default writes); any other settings failure refuses the write', async () => { + const unregistered = await makeStack({ + inProcess, defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH) }, + settings: () => { throw Object.assign(new Error('unknown key'), { code: 'SETTINGS_UNKNOWN_KEY' }); }, + }); + expect(await qualify(unregistered.engine, 'Acme')).toEqual(['跟进已认定线索:Acme']); + await engine?.destroy(); engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + + const broken = await makeStack({ + inProcess, defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH) }, + settings: () => { throw Object.assign(new Error('settings store unavailable'), { code: 'SETTINGS_STORE_UNAVAILABLE' }); }, + }); + await expect(qualify(broken.engine, 'Acme')).rejects.toThrow(/settings store unavailable/); + const tasks: any[] = await broken.engine.find(TASK.name, SYSTEM_READ); + expect(tasks).toEqual([]); + }, 30000); + }); + } + + it('refuses a key the hook does not declare, naming the hook and the key (sandboxed body)', async () => { + const { engine: ql } = await makeStack({ defaultLocale: 'zh-CN', bundles: { 'zh-CN': bundle(ZH) } }); + await expect(qualify(ql, 'Undeclared')).rejects.toThrow( + /hook 'probe_lead_follow_up' asked for text 'no_such_text'.*declared: 'follow_up_subject'/, + ); + expect(noise?.tablesSeen() ?? ['no capture was installed']).toEqual([]); + }, 30000); +}); diff --git a/packages/runtime/src/sandbox/hook-text.ts b/packages/runtime/src/sandbox/hook-text.ts new file mode 100644 index 00000000000..89cdddac024 --- /dev/null +++ b/packages/runtime/src/sandbox/hook-text.ts @@ -0,0 +1,148 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A hook's declared texts, answered at run time (#34374, maintainer ruling + * 6913660232 option B, parameter 7). + * + * A hook that declares `texts: { : { message, params? } }` + * (`HookSchema.texts`) asks for a sentence it writes into a record by key — + * `await ctx.text('follow_up_subject', { lead })` — and {@link buildHookTextSurface} + * answers it: + * + * - in the ORGANIZATION's language, never the caller's (parameter 2): the one + * shared reading `readOrganizationTextLocale` (`@objectstack/core`) of the + * Localization setting somebody set, else the app's `i18n.defaultLocale` + * (parameter 3) — the reading the flow record write's text field uses; + * - the translated sentence first, `hooks..texts..message` through + * the `i18n` service, negotiated by `resolveBundleLocale`; then its `{{ }}` + * holes are filled from `params` through the formula template engine, the + * one a declared refusal is filled with (parameter 1). A translation whose + * holes do not render is dropped for the declared `message`, filled; + * - with no translation, or no language, the declared `message` (parameter 5) + * — the hook goes on; + * - a Localization setting that cannot be READ (the settings service throws) + * rejects the call: the organization's language may exist and could not be + * known, and answering another would look like success — the flow record + * write's rule (ruling 6929082704 letter A). The hook decides what a + * rejection means for its own write. + * + * A key the hook does not declare is refused loudly, as a fault naming the hook + * and the key (`undeclaredHookTextAtRun`); a save already refused the keys the + * hook's source asks for literally (`HookSchema`). + * + * One answer on every path a hook runs on: the sandboxed body (installed on the + * VM's `ctx.text` by `installCtx`) and the in-process seam a `handler` runs + * through (`withInProcessHookTitle`). + */ + +import type { Hook } from '@objectstack/spec/data'; +import { undeclaredHookTextAtRun } from '@objectstack/spec/data'; +import { hookTextMessageKey } from '@objectstack/spec/system'; +import { readOrganizationTextLocale } from '@objectstack/core'; +import { + negotiatedLocale, + renderHookTemplate, + type HookRefusalI18nService, + type HookRefusalI18nSource, +} from './hook-refusal-catalogue.js'; +import { SandboxError } from './quickjs-runner.js'; + +/** One declared text, as the hook holds it. */ +interface DeclaredText { + message: string; + params?: string[]; +} + +/** What `ctx.text(key, params?)` is answered with. */ +export type HookTextSurface = (key: string, params?: Record) => Promise; + +/** What {@link buildHookTextSurface} reads its services through. */ +export interface HookTextOptions { + /** The `i18n` service a declared text is translated through, read at call time. */ + i18n?: HookRefusalI18nSource; + /** Kernel service lookup — the `settings` and `i18n` services the organization's language is read from, at call time. */ + getService?: (name: string) => unknown; + logger?: { warn?: (...args: any[]) => void }; +} + +/** The hook's declared texts, or `undefined` when it declares none. */ +function textsOf(hook: Pick): Record | undefined { + const texts = (hook as { texts?: unknown }).texts; + return texts && typeof texts === 'object' ? (texts as Record) : undefined; +} + +/** The translation of a declared text in `locale`, or `undefined` when none is picked. */ +function pickTranslatedText( + hookName: string, + key: string, + locale: string, + i18n: HookRefusalI18nSource | undefined, + logger: HookTextOptions['logger'], +): string | undefined { + let service: HookRefusalI18nService | undefined; + try { + service = i18n?.(); + } catch { + return undefined; + } + if (!service || typeof service.t !== 'function') return undefined; + const translationKey = hookTextMessageKey(hookName, key); + try { + const translated = service.t(translationKey, negotiatedLocale(service, locale)); + // II18nService echoes the key back on a miss. + if (typeof translated === 'string' && translated.trim().length > 0 && translated !== translationKey) return translated; + } catch (err: unknown) { + logger?.warn?.( + `[BodyRunner] hook '${hookName}': the i18n service threw reading '${translationKey}' ` + + `(${err instanceof Error ? err.message : String(err)}), so the text is written as declared.`, + ); + } + return undefined; +} + +/** + * Build `ctx.text(key, params?)` for one hook invocation. The organization is + * the hook context's `session.organizationId`; a write with none asks the + * settings service with no scope (its own reach), as the flow record write does. + */ +export function buildHookTextSurface( + hook: Pick, + engineCtx: { session?: { organizationId?: unknown } } | undefined, + opts: HookTextOptions = {}, +): HookTextSurface { + const hookName = String(hook.name); + return async (key: string, params?: Record): Promise => { + const texts = textsOf(hook); + const entry = texts && Object.prototype.hasOwnProperty.call(texts, key) ? texts[key] : undefined; + if (!entry || typeof entry.message !== 'string') { + throw new SandboxError(undeclaredHookTextAtRun(hookName, String(key), Object.keys(texts ?? {}))); + } + const organizationId = engineCtx?.session?.organizationId; + const locale = await readOrganizationTextLocale( + opts.getService, + typeof organizationId === 'string' && organizationId.length > 0 ? organizationId : undefined, + ); + const translated = locale ? pickTranslatedText(hookName, key, locale, opts.i18n, opts.logger) : undefined; + const declared = Array.isArray(entry.params) ? entry.params : []; + if (declared.length === 0) return translated ?? entry.message; + // A translation whose holes do not render falls back to the declared + // sentence, filled; never a sentence with its braces in the record. + if (translated !== undefined) { + const filled = renderHookTemplate(translated, declared, params); + if (filled.ok) return filled.value; + opts.logger?.warn?.( + `[BodyRunner] hook '${hookName}': the ${locale} translation of its text '${key}' did not render ` + + `(${filled.error}), so the declared text is written.`, + ); + } + const filled = renderHookTemplate(entry.message, declared, params); + if (filled.ok) return filled.value; + // Only reachable for a hook that skipped the compile check (`objectstack + // validate`, `compile`, the publish gate refuse such a sentence). + opts.logger?.warn?.( + `[BodyRunner] hook '${hookName}': its declared text '${key}' did not render (${filled.error}), ` + + 'so it is written unfilled, holes and all.', + ); + return entry.message; + }; +} diff --git a/packages/runtime/src/sandbox/quickjs-runner.ts b/packages/runtime/src/sandbox/quickjs-runner.ts index eb1f2154029..26887c7af60 100644 --- a/packages/runtime/src/sandbox/quickjs-runner.ts +++ b/packages/runtime/src/sandbox/quickjs-runner.ts @@ -1033,6 +1033,44 @@ export class QuickJSScriptRunner implements ScriptRunner { titleFn.dispose(); } + // ── [#34374] `ctx.text(key, params?)` — a declared text, in the + // organization's language ──────────────────────────────────────────────── + // + // Installed when the host built the seam (hook bodies, `hook-text.ts`). The + // same deferred-promise pump as `title`, never `newAsyncifiedFunction`, for + // the same reason: a body awaits it beside `ctx.api` calls. No capability: + // it reads no record, and the language it reads is the platform's. + // `vm.dump` for both arguments, like every other bridge here; a `params` + // that is not a plain object is handed over as no params. + if (typeof ctx.text === 'function') { + const textFn = vm.newFunction('text', (keyH, paramsH) => { + const key = keyH === undefined ? undefined : vm.dump(keyH); + const rawParams = paramsH === undefined ? undefined : vm.dump(paramsH); + const params = rawParams !== null && typeof rawParams === 'object' && !Array.isArray(rawParams) + ? (rawParams as Record) + : undefined; + const deferred = vm.newPromise(); + deferreds.add(deferred); + void (async () => { + try { + const value = await ctx.text!(String(key), params); + if (!vm.alive) return; + const h = jsonToHandle(vm, value); + deferred.resolve(h); + h.dispose(); + } catch (err) { + if (!vm.alive) return; + const errH = hostErrorToVm(vm, err); + deferred.reject(errH); + errH.dispose(); + } + })(); + return deferred.handle; + }); + vm.setProp(ctxObj, 'text', textFn); + textFn.dispose(); + } + // ── [#28251] `ctx.notice(message)` — tell the saver what the save did ─── // // Installed only when the host handed the engine's member over (the hook diff --git a/packages/runtime/src/sandbox/script-runner.ts b/packages/runtime/src/sandbox/script-runner.ts index 9473c02daee..452958aff6c 100644 --- a/packages/runtime/src/sandbox/script-runner.ts +++ b/packages/runtime/src/sandbox/script-runner.ts @@ -420,6 +420,18 @@ export interface ScriptContext { * `=== undefined` does not, so the VM-facing contract is stated as `null`. */ title?: (field: string | undefined, api: unknown) => Promise; + /** + * [#34374, ruling 6913660232 parameter 7] `ctx.text(key, params?)` for the + * HOOK face — a sentence the hook declared under `HookSchema.texts`, answered + * in the ORGANIZATION's language (translated `hooks..texts..message` + * first, the declared message on a miss, its `{{ }}` holes filled from + * `params` after). Built per invocation by `buildHookTextSurface` + * (`hook-text.ts`); `installCtx` wires it onto the VM's `ctx.text` through the + * same deferred-promise pump as `title`. A key the hook does not declare + * rejects as a fault naming the hook and the key; an unreadable Localization + * setting rejects too. No capability token: it reads no record. + */ + text?: (key: string, params?: Record) => Promise; /** * The engine's save-notice member, marshalled for the HOOK face (#28251) — * `HookContextSchema.notice` (`@objectstack/spec/data`), which objectql's diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index f215ffccc37..3e3d93da996 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -2,7 +2,7 @@ import type { Plugin, PluginContext } from '@objectstack/core'; import { installEgressGuard, type EgressPolicy } from '@objectstack/core/egress'; -import { RUNTIME_COMPATIBILITY_PACKAGE_ID, effectiveTenancyPosture, isServiceNotRegisteredError, resolveLocalizationContext, resolveOrganizationLocale, resolveUserAuthzGrants } from '@objectstack/core'; +import { RUNTIME_COMPATIBILITY_PACKAGE_ID, effectiveTenancyPosture, isServiceNotRegisteredError, resolveLocalizationContext, readOrganizationTextLocale, resolveUserAuthzGrants } from '@objectstack/core'; import type { IClusterService, IJobService, IPubSub } from '@objectstack/spec/contracts'; import { installedManifestsOf, type InstalledPackageSource } from '@objectstack/metadata-core'; import type { @@ -1582,56 +1582,15 @@ export function i18nServiceReader(ctx: Pick): () => * else the app's declared `i18n.defaultLocale`). * * Both services are resolved at QUESTION time, for {@link i18nServiceReader}'s - * reason. A composition with neither answers `undefined`, and the text is - * written as authored; a settings read that throws rejects. + * reason, by core's `readOrganizationTextLocale` — the reading a hook's or + * action's declared text shares (#34374). A composition with neither answers + * `undefined`, and the text is written as authored; an unregistered + * Localization setting is not set; any other settings read that throws rejects. */ export function organizationLocaleReader( ctx: Pick, ): (tenantId: string | undefined) => Promise { - return async (tenantId) => { - let settings: unknown; - let i18n: unknown; - try { settings = ctx.getService('settings'); } catch { settings = undefined; } - try { i18n = ctx.getService('i18n'); } catch { i18n = undefined; } - return (await resolveOrganizationLocale({ settings: unregisteredSettingIsUnset(settings), i18n, organizationId: tenantId }))?.locale; - }; -} - -/** - * The settings service's refusal of a namespace or key nobody REGISTERED — - * `SETTINGS_UNKNOWN_NAMESPACE` / `SETTINGS_UNKNOWN_KEY`, as `@objectstack/objectql`'s - * home-localization bridge reads them. A host that loads no `localization` - * manifest has no setting anybody could have set, so for the organization's - * language it is "not set", the same as a host with no settings service. - */ -function isUnregisteredSetting(err: unknown): boolean { - const code = (err as { code?: unknown } | null | undefined)?.code; - return code === 'SETTINGS_UNKNOWN_NAMESPACE' || code === 'SETTINGS_UNKNOWN_KEY'; -} - -/** - * [ruling 6913660232, review 6924979595 S1] The settings door the reader is - * handed, with an unregistered `localization.locale` answered as not set, so - * the next rung (the app's declared default) answers. Any other throw still - * propagates: the setting may exist and could not be read, and the record - * node fails rather than store another language over it. Kept here, in the - * automation bridge, so the shared reader and the seed loader's rung 1 stay - * as they are. - */ -function unregisteredSettingIsUnset(settings: unknown): unknown { - const door = settings as { get?: unknown } | null | undefined; - if (!door || typeof door.get !== 'function') return settings; - const get = door.get as (namespace: string, key: string, ctx?: { tenantId?: string }) => Promise; - return { - async get(namespace: string, key: string, ctx?: { tenantId?: string }) { - try { - return await get.call(settings, namespace, key, ctx); - } catch (err: unknown) { - if (isUnregisteredSetting(err)) return undefined; - throw err; - } - }, - }; + return (tenantId) => readOrganizationTextLocale((name) => ctx.getService(name), tenantId); } /** diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 27548dce14f..3b54be1ad3f 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -387,6 +387,8 @@ "HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE (const)", "HOOK_REFUSAL_PARAM_PATTERN (const)", "HOOK_REFUSAL_REASON_PATTERN (const)", + "HOOK_TEXT_KEY_PATTERN (const)", + "HOOK_TEXT_MESSAGE_HOLE_REFUSED (const)", "Hook (type)", "HookApi (interface)", "HookBody (type)", @@ -410,6 +412,8 @@ "HookRefusal (type)", "HookRefusalSchema (const)", "HookSchema (const)", + "HookText (type)", + "HookTextSchema (const)", "HookUpdateDoc (type)", "HookUpdateOptions (type)", "IMPORT_BOOLEAN_FALSE_TOKENS (const)", @@ -983,6 +987,8 @@ "hookRefusalCodesThrownIn (function)", "hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody (function)", + "hookTextKeysAskedIn (function)", + "hookTextsWithoutRunnableCode (function)", "importMappingEntryTargets (function)", "indexImportMappingTargets (function)", "injectedSystemColumnDefs (function)", @@ -1118,6 +1124,8 @@ "undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun (function)", "undeclaredHookRefusalReasonAtSave (function)", + "undeclaredHookTextAtRun (function)", + "undeclaredHookTextKeyAtSave (function)", "uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets (function)", "unprovisionedInjectedColumns (function)", diff --git a/packages/spec/api-surface/system.json b/packages/spec/api-surface/system.json index 424f7f86c9b..1ad698476d2 100644 --- a/packages/spec/api-surface/system.json +++ b/packages/spec/api-surface/system.json @@ -873,6 +873,7 @@ "hasObservedDeviation (function)", "hasPlatformObjectPrefix (function)", "hookRefusalMessageKey (function)", + "hookTextMessageKey (function)", "inProcessServiceMessage (function)", "interpolateValidationMessage (function)", "isAudiencePosture (function)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 5e1972e0556..a6ddf50c160 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -472,6 +472,7 @@ "data/Hook:refusals", "data/Hook:retryPolicy", "data/Hook:runAs", + "data/Hook:texts", "data/Hook:timeout [RETIRED]", "data/Hook:timeoutMs", "data/HookContext:api", @@ -495,6 +496,8 @@ "data/HookRefusal:params", "data/HookRefusal:reasons", "data/HookRefusal:status", + "data/HookText:message", + "data/HookText:params", "data/ImportFieldMapping:params", "data/ImportFieldMapping:source", "data/ImportFieldMapping:target", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index 542f4cf738f..79e5607b91c 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -166,6 +166,8 @@ "HookRefusal": "data/HookRefusal", "HookRefusalSchema": "data/HookRefusal", "HookSchema": "data/Hook", + "HookText": "data/HookText", + "HookTextSchema": "data/HookText", "ImportFieldMapping": "data/ImportFieldMapping", "ImportFieldMappingSchema": "data/ImportFieldMapping", "IndexSchema": "data/Index", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 75ee5495641..c80b26cc463 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -2,8 +2,8 @@ "description": "Shrink-only ledger of every PUBLISHED JSON Schema that is STILL WIDER than the Zod type it was generated from, because a rule written as `.refine()` reaches the runtime and not the file (#18670). `z.toJSONSchema()` has no arm for a `custom` check: a plain record, the same record with a `.refine()`, and the same record with an ABORTING `.refine()` all project byte-identically (measured on zod 4.4.3, the version packages/spec resolves). So a document one of these files ACCEPTS can still be refused at parse time, and an author -- or an AI -- validating against packages/spec/json-schema/** finds out a release later. Each `sites` path is a position under that schema at which a refinement is dropped; the same paths are written onto the artifact itself as `x-dropped-refinements`. Item 2 closed the first patterns: a refinement DECLARED through the closed list in src/shared/refinement-projection.ts is emitted into the published file, reads `projected` rather than `dropped`, and its row LEAVES this ledger in the same PR -- which is why the ledger shrinks and never grows on a repair. Every refinement outside that closed list stays here, and adding an arm to the list is a public-contract decision, not a refactor. Hand-edited on purpose and with no `gen:` script: a generator would let a new gap be admitted by running a command instead of by a decision, which is the silence this ledger exists to end. Adding, removing or moving a site fails packages/spec/scripts/build-schemas.ts until the line moves with it, and the failure prints the corrected entry in full. ⛔ Do not delete or weaken a refinement to shorten this file -- the runtime rule is correct; it is the projection that is silent, and the remedy is to teach the closed list a NAMED pattern, never to drop the rule.", "measured": { "zod": "4.4.3", - "publishedSchemasWithDroppedRefinements": 268, - "droppedRefinementSites": 1116, + "publishedSchemasWithDroppedRefinements": 269, + "droppedRefinementSites": 1122, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -136,6 +136,7 @@ "manifest.hooks.element", "manifest.hooks.element.object", "manifest.hooks.element.refusals.valueType", + "manifest.hooks.element.texts.valueType", "manifest.jobs.element", "manifest.jobs.element.schedule.options[0].timezone", "manifest.mappings.element", @@ -319,6 +320,7 @@ "data.options[1].manifest.hooks.element", "data.options[1].manifest.hooks.element.object", "data.options[1].manifest.hooks.element.refusals.valueType", + "data.options[1].manifest.hooks.element.texts.valueType", "data.options[1].manifest.jobs.element", "data.options[1].manifest.jobs.element.schedule.options[0].timezone", "data.options[1].manifest.mappings.element", @@ -471,6 +473,7 @@ "options[1].manifest.hooks.element", "options[1].manifest.hooks.element.object", "options[1].manifest.hooks.element.refusals.valueType", + "options[1].manifest.hooks.element.texts.valueType", "options[1].manifest.jobs.element", "options[1].manifest.jobs.element.schedule.options[0].timezone", "options[1].manifest.mappings.element", @@ -562,6 +565,7 @@ "data.packages.element.options[1].manifest.hooks.element", "data.packages.element.options[1].manifest.hooks.element.object", "data.packages.element.options[1].manifest.hooks.element.refusals.valueType", + "data.packages.element.options[1].manifest.hooks.element.texts.valueType", "data.packages.element.options[1].manifest.jobs.element", "data.packages.element.options[1].manifest.jobs.element.schedule.options[0].timezone", "data.packages.element.options[1].manifest.mappings.element", @@ -1053,7 +1057,8 @@ "sites": [ "", "object", - "refusals.valueType" + "refusals.valueType", + "texts.valueType" ] }, "data/HookRefusal": { @@ -1061,6 +1066,11 @@ "" ] }, + "data/HookText": { + "sites": [ + "" + ] + }, "data/InlineGridColumn": { "sites": [ "" diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 55638e65884..62b3c71f639 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -378,6 +378,8 @@ "HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE (const)", "HOOK_REFUSAL_PARAM_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_PARAM_PATTERN (const)", "HOOK_REFUSAL_REASON_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_REFUSAL_REASON_PATTERN (const)", + "HOOK_TEXT_KEY_PATTERN": "src/data/hook-refusal-codes.ts#HOOK_TEXT_KEY_PATTERN (const)", + "HOOK_TEXT_MESSAGE_HOLE_REFUSED": "src/data/hook-refusal-codes.ts#HOOK_TEXT_MESSAGE_HOLE_REFUSED (const)", "Hook": "src/data/hook.zod.ts#Hook (type)", "HookApi": "src/data/hook-api.ts#HookApi (interface)", "HookBody": "src/data/hook-body.zod.ts#HookBody (type)", @@ -400,6 +402,8 @@ "HookRefusal": "src/data/hook.zod.ts#HookRefusal (type)", "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", + "HookText": "src/data/hook.zod.ts#HookText (type)", + "HookTextSchema": "src/data/hook.zod.ts#HookTextSchema (const)", "HookUpdateDoc": "src/data/hook-api.ts#HookUpdateDoc (type)", "HookUpdateOptions": "src/data/hook-api.ts#HookUpdateOptions (type)", "IMPORT_BOOLEAN_FALSE_TOKENS": "src/data/import-coercion.ts#IMPORT_BOOLEAN_FALSE_TOKENS (const)", @@ -969,6 +973,8 @@ "hookRefusalCodesThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalCodesThrownIn (function)", "hookRefusalReasonsThrownIn": "src/data/hook-refusal-codes.ts#hookRefusalReasonsThrownIn (function)", "hookRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#hookRefusalsWithoutSandboxedBody (function)", + "hookTextKeysAskedIn": "src/data/hook-refusal-codes.ts#hookTextKeysAskedIn (function)", + "hookTextsWithoutRunnableCode": "src/data/hook-refusal-codes.ts#hookTextsWithoutRunnableCode (function)", "importMappingEntryTargets": "src/data/import-mapping-target.ts#importMappingEntryTargets (function)", "indexImportMappingTargets": "src/data/import-mapping-target.ts#indexImportMappingTargets (function)", "injectedSystemColumnDefs": "src/data/injected-system-column-provenance.ts#injectedSystemColumnDefs (function)", @@ -1104,6 +1110,8 @@ "undeclaredHookRefusalCodeAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalCodeAtSave (function)", "undeclaredHookRefusalReasonAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtRun (function)", "undeclaredHookRefusalReasonAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookRefusalReasonAtSave (function)", + "undeclaredHookTextAtRun": "src/data/hook-refusal-codes.ts#undeclaredHookTextAtRun (function)", + "undeclaredHookTextKeyAtSave": "src/data/hook-refusal-codes.ts#undeclaredHookTextKeyAtSave (function)", "uniqueNullDistinctDivergence": "src/data/unique-null-distinct-conformance.ts#uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets": "src/data/import-mapping-target.ts#unknownImportMappingTargets (function)", "unprovisionedInjectedColumns": "src/data/injected-system-column-provenance.ts#unprovisionedInjectedColumns (function)", diff --git a/packages/spec/export-origins/system.json b/packages/spec/export-origins/system.json index 97efa9679d1..3e6d27b4a2d 100644 --- a/packages/spec/export-origins/system.json +++ b/packages/spec/export-origins/system.json @@ -833,6 +833,7 @@ "hasObservedDeviation": "src/system/migration.zod.ts#hasObservedDeviation (function)", "hasPlatformObjectPrefix": "src/system/constants/platform-object-names.ts#hasPlatformObjectPrefix (function)", "hookRefusalMessageKey": "src/system/i18n-resolver.ts#hookRefusalMessageKey (function)", + "hookTextMessageKey": "src/system/i18n-resolver.ts#hookTextMessageKey (function)", "inProcessServiceMessage": "src/system/core-services.zod.ts#inProcessServiceMessage (function)", "interpolateValidationMessage": "src/system/validation-message.ts#interpolateValidationMessage (function)", "isAudiencePosture": "src/system/auth-config.zod.ts#isAudiencePosture (function)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index f626184e297..e4feb05b920 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -90,6 +90,7 @@ "data/HookContext", "data/HookEvent", "data/HookRefusal", + "data/HookText", "data/ImportFieldMapping", "data/Index", "data/InlineGridColumn", diff --git a/packages/spec/liveness/hook.json b/packages/spec/liveness/hook.json index 72b799dd1df..30dc46e1c70 100644 --- a/packages/spec/liveness/hook.json +++ b/packages/spec/liveness/hook.json @@ -130,6 +130,29 @@ }, "note": "[#26170, maintainer ruling 6431311681 letter A] Seeded `live` together with its reader: the key, the body runner that answers it, the translation group and the coverage count land in one change (Prime Directive 10). [#33214, ruling 6879477573 letter A] Read on every path a hook runs on: the sandboxed `body` and the in-process `handler` seam, so the schema refuses `refusals` only on a hook whose code cannot throw a code (an expression body, or neither a body nor a handler). An error a host call raised and the body let through unchanged, a nested hook's refusal, a crash and a sandbox fault pass through untouched. DRILLED to the entry's four keys: the entry face is closed (`.strict()`)." }, + "texts": { + "status": "live", + "verifiedAt": "2026-11-16", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-text.ts#buildHookTextSurface (the one reader: `ctx.text(key, params)` answers a declared text in the organization's language, and a key the hook does not declare as a fault naming the hook and the key); packages/runtime/src/sandbox/body-runner.ts#hookBodyRunnerFactory (builds it for every sandboxed body invocation); packages/runtime/src/sandbox/quickjs-runner.ts#installCtx (wires it onto the VM's `ctx.text`); packages/runtime/src/sandbox/body-runner.ts#withInProcessHookTitle (the one in-process seam that hands every in-process handler the same `ctx.text`)", + "producer": "packages/objectql/src/hook-binder.ts#bindHooksToEngine (hands the AUTHORED hook to the body runner factory and to the in-process wrap, `texts` included); packages/spec/src/data/hook.zod.ts#HookSchema (refuses at save a key the hook's source asks for literally that `texts` does not declare)", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-16", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-text.ts#buildHookTextSurface (the sentence `ctx.text` answers: `hooks..texts..message` picked through the `i18n` service in the organization's language — `readOrganizationTextLocale`, the Localization setting somebody set, else the app's `i18n.defaultLocale` — negotiated by `resolveBundleLocale`, else the declared `message`)" + }, + "params": { + "status": "live", + "verifiedAt": "2026-11-17", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-refusal-catalogue.ts#renderHookTemplate (fills the picked sentence's `{{ NAME }}` holes from the call's `params` through the formula template engine, the declared names alone in scope); packages/runtime/src/sandbox/hook-text.ts#buildHookTextSurface (fills an entry that declares `params`; one that declares none stays plain text)", + "producer": "packages/spec/src/data/hook.zod.ts#HookTextSchema (judges the message's holes against the declared names at save)" + } + }, + "note": "[#34374, ruling 6913660232 parameter 7] Seeded `live` with its reader in one change. Never the caller's language (parameter 2); a missing translation writes the declared sentence (parameter 5); an unreadable Localization setting rejects the call, the flow record write's rule (ruling 6929082704 letter A)." + }, "label": { "status": "live", "verifiedAt": "2026-09-29", diff --git a/packages/spec/liveness/state-counts/hook.md b/packages/spec/liveness/state-counts/hook.md index 884217259e9..78dc1eb1d56 100644 --- a/packages/spec/liveness/state-counts/hook.md +++ b/packages/spec/liveness/state-counts/hook.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `hook` | 25 | 0 | 0 | 1 | 0 | 26 | +| `hook` | 27 | 0 | 0 | 1 | 0 | 28 | diff --git a/packages/spec/liveness/state-counts/translation.md b/packages/spec/liveness/state-counts/translation.md index c02ba4059bd..ed523cd674d 100644 --- a/packages/spec/liveness/state-counts/translation.md +++ b/packages/spec/liveness/state-counts/translation.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `translation` | 45 | 0 | 0 | 0 | 2 | 47 | +| `translation` | 46 | 0 | 0 | 0 | 2 | 48 | diff --git a/packages/spec/liveness/translation.json b/packages/spec/liveness/translation.json index 99edfe5be48..2da338a1e24 100644 --- a/packages/spec/liveness/translation.json +++ b/packages/spec/liveness/translation.json @@ -294,6 +294,22 @@ } } } + }, + "texts": { + "status": "live", + "verifiedAt": "2026-11-16", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-text.ts#buildHookTextSurface (each `texts.` entry is read for its `message`, the drilled child below)", + "children": { + "message": { + "status": "live", + "verifiedAt": "2026-11-16", + "evidenceScope": "in-repo", + "evidence": "packages/runtime/src/sandbox/hook-text.ts#buildHookTextSurface (reads `hooks..texts..message` through the `i18n` service, spelled by `hookTextMessageKey`, in the organization's language negotiated by `resolveBundleLocale`; a miss echoes the key and the declared message is written, its holes filled after)", + "producer": "packages/runtime/src/app-plugin.ts#loadTranslations (hands each bundle's locale data to the i18n service whole, `hooks` included)" + } + }, + "note": "[#34374, ruling 6913660232 parameter 7] Seeded `live` with its reader. `objectstack validate` refuses a key over a text the hook does not declare; the i18n walk counts each declared text." } }, "note": "[#26170, maintainer ruling 6431311681 letter A] Seeded `live` together with its reader, the flow `refusals` precedent: the key and the body-runner read that makes it true land in one change (Prime Directive 10). A hook's refusal leaves the server already rendered (the error envelope's message and `userMessage`), so the body runner picks the translation before it serves the refusal, the validation-message posture (`objectValidationMessageKey`). Keyed by hook name, never by object, so a hook bound to several objects or to `'*'` owns one translation per code. `objectstack validate` (`validate-translation-references.ts`) refuses a key over an unknown hook or an undeclared code, and the i18n extract/check walk counts each declared entry. No objectui reader: the console draws the served refusal verbatim. DRILLED two levels, to `refusals.message`; each entry face is closed (`.strict()`)." diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 609f199fdec..04f57a14941 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -354,3 +354,92 @@ export function undeclaredHookRefusalReasonAtRun( + 'throw one of the declared reasons, or declare this one with the message the user reads.' ); } + +/* + * ── A hook's declared texts (#34374, ruling 6913660232 parameter 7) ───────── + * + * A sentence a hook writes into a record for people to read — the subject of + * the follow-up task it opens, the summary of the activity it logs — is + * written in the ORGANIZATION's language, never the starter's (parameter 2). + * The hook declares each such sentence under `texts: { : { message, + * params? } }`, the way it declares a refusal, and its code asks for one by + * key: `await ctx.text('follow_up_subject', { lead })`. The runtime picks + * `hooks..texts..message` in the organization's language (the one + * shared reader `resolveOrganizationLocale`, parameter 3), else the declared + * sentence (parameter 5), and fills its `{{ }}` holes from `params` after + * (parameter 1). A string the hook builds itself stays a literal value + * (parameter 4). + * + * The same two halves as a refusal code: a key the hook's source asks for + * LITERALLY and `texts` does not declare is refused at save + * ({@link hookTextKeysAskedIn}); any other key is refused when the hook runs. + */ + +/** + * The spelling of a declared text key: snake_case, a machine name like every + * other key an author declares. It never reaches the wire. + */ +export const HOOK_TEXT_KEY_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/; + +/** `ctx.text('key'` — the call a hook's code asks for a declared text with. */ +const TEXT_CALL = new RegExp( + String.raw`(?['"\x60])(?[a-z][a-z0-9]*(?:_[a-z0-9]+)*)\k`, + 'g', +); + +/** + * The text keys a hook's source asks for LITERALLY — `ctx.text('key', …)` — + * in first-seen order: the cases a save can decide. A key that arrives any + * other way (a variable, a computed value) is left to the run-time refusal. + * Comments and longer strings are blanked first, as for a refusal code. + */ +export function hookTextKeysAskedIn(source: string): string[] { + const keys = new Set(); + for (const m of maskedSource(source).matchAll(TEXT_CALL)) keys.add(m.groups!.key); + return [...keys]; +} + +/** The save-time refusal for a key a hook's source asks for literally that `texts` does not declare. */ +export function undeclaredHookTextKeyAtSave( + key: string, + declared: readonly string[], + at: 'body.source' | 'handler' = 'body.source', +): string { + return ( + `\`${at}\` asks for text '${key}' (\`ctx.text('${key}')\`), and this hook's \`texts\` declares no such key ` + + `(declared: ${declaredList(declared)}). Declare it under \`texts.${key}\` with the sentence the record keeps, ` + + 'or ask for one of the declared keys.' + ); +} + +/** The save-time refusal for a `{{ … }}` hole in a text `message` whose entry declares no `params`. */ +export const HOOK_TEXT_MESSAGE_HOLE_REFUSED = + 'A hook text `message` whose entry declares no `params` is plain text, and nothing fills a `{{ }}` hole: the ' + + 'record would keep the braces as written. Declare the name under the entry\'s `params` (`params: [\'lead\']`) ' + + 'and pass it to `ctx.text` (`ctx.text(\'KEY\', { lead })`), or write the sentence without the hole.'; + +/** + * The save-time refusal for `texts` on a hook whose code cannot ask for one: + * an `expression` body, or no body and no handler at all. + */ +export function hookTextsWithoutRunnableCode(language: string | undefined): string { + return ( + '`texts` is served to a sandboxed `body` (`language: \'js\'`) and to an in-process `handler` (which ' + + `\`os build\` lowers to a \`js\` body) through \`ctx.text\`, and this hook has ${refusalCarrier(language)}: ` + + 'nothing it runs can ask for a declared text, while `os i18n` still demanded its translations. Give the hook a ' + + '`js` body or a `handler` that writes the texts, or drop `texts`.' + ); +} + +/** + * The run-time refusal for `ctx.text(key)` with a key the hook's `texts` does + * not declare (or a hook that declares none). Fault text: it names the hook + * and the key and says how to fix it. + */ +export function undeclaredHookTextAtRun(hookName: string, key: string, declared: readonly string[]): string { + return ( + `hook '${hookName}' asked for text '${key}' (ctx.text), and its \`texts\` declares no such key ` + + `(declared: ${declaredList(declared)}). Only a declared text is written in the organization's language: ` + + 'declare it under `texts` with the sentence the record keeps, or ask for one of the declared keys.' + ); +} diff --git a/packages/spec/src/data/hook-texts.test.ts b/packages/spec/src/data/hook-texts.test.ts new file mode 100644 index 00000000000..893fe0b3e19 --- /dev/null +++ b/packages/spec/src/data/hook-texts.test.ts @@ -0,0 +1,127 @@ +import { describe, it, expect } from 'vitest'; +import { HookSchema, HookTextSchema } from './hook.zod'; +import { + HOOK_TEXT_KEY_PATTERN, + HOOK_TEXT_MESSAGE_HOLE_REFUSED, + hookTextKeysAskedIn, + hookTextsWithoutRunnableCode, + undeclaredHookTextAtRun, + undeclaredHookTextKeyAtSave, +} from './hook-refusal-codes'; +import { hookTextMessageKey } from '../system/i18n-resolver'; +import { TranslationDataSchema } from '../system/translation.zod'; + +// #34374 (ruling 6913660232 option B, parameter 7): a hook declares the +// sentences it writes into records, `texts: { : { message, params? } }`, +// and asks for one by key with `ctx.text(key, params)`; the runtime answers it +// in the organization's language. + +const base = { name: 'lead_follow_up', object: 'crm_lead', events: ['afterUpdate' as const] }; +const body = (source: string) => ({ language: 'js' as const, source }); +const ASKS = "const s = await ctx.text('follow_up_subject', { lead: ctx.input.name });"; + +describe('Hook.texts — the declared texts', () => { + it('accepts snake_case keys with a message and the params its holes name', () => { + const parsed = HookSchema.parse({ + ...base, + body: body(ASKS), + texts: { follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] } }, + }); + expect(parsed.texts?.follow_up_subject).toEqual({ message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] }); + }); + + it('is optional — a hook that declares no texts is unchanged', () => { + expect(HookSchema.parse({ ...base, body: body('return;') }).texts).toBeUndefined(); + }); + + it('refuses a key that is not snake_case, at the key', () => { + expect(HOOK_TEXT_KEY_PATTERN.test('follow_up_subject')).toBe(true); + const r = HookSchema.safeParse({ ...base, body: body('return;'), texts: { FollowUp: { message: 'x' } } }); + expect(r.success).toBe(false); + expect(r.error!.issues.some((i) => i.path[0] === 'texts')).toBe(true); + }); + + it('refuses a {{ }} hole in a message whose entry declares no params; CONTROL: declared params allow it', () => { + const r = HookTextSchema.safeParse({ message: 'Follow up with {{ lead }}' }); + expect(r.success).toBe(false); + expect(r.error!.issues.find((i) => i.path.join('.') === 'message')!.message).toBe(HOOK_TEXT_MESSAGE_HOLE_REFUSED); + expect(HookTextSchema.safeParse({ message: 'Follow up with {{ lead }}', params: ['lead'] }).success).toBe(true); + }); + + it('refuses a hole over a name the entry does not declare, and a param declared twice', () => { + const hole = HookTextSchema.safeParse({ message: 'Follow up with {{ account }}', params: ['lead'] }); + expect(hole.success).toBe(false); + expect(hole.error!.issues.some((i) => i.path.join('.') === 'message')).toBe(true); + const twice = HookTextSchema.safeParse({ message: 'Follow up with {{ lead }}', params: ['lead', 'lead'] }); + expect(twice.success).toBe(false); + expect(twice.error!.issues.some((i) => i.path.join('.') === 'params.1')).toBe(true); + }); + + it('renames a near-miss spelling of message onto the declared key, loudly', () => { + const r = HookTextSchema.safeParse({ text: 'Follow up' }); + expect(r.success).toBe(false); + expect(JSON.stringify(r.error!.issues)).toMatch(/message/); + }); + + it('refuses texts on a hook whose code cannot ask for one (an expression body, or neither body nor handler)', () => { + for (const rest of [{ body: { language: 'expression' as const, source: 'true' } }, {}]) { + const r = HookSchema.safeParse({ ...base, ...rest, texts: { follow_up_subject: { message: 'x' } } }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'texts')!; + expect(issue.message).toBe(hookTextsWithoutRunnableCode('body' in rest ? 'expression' : undefined)); + } + }); + + it('accepts texts on a hook with an in-process handler (the build lowers it to a js body)', () => { + expect(HookSchema.safeParse({ ...base, handler: 'leadFollowUp', texts: { follow_up_subject: { message: 'x' } } }).success).toBe(true); + }); +}); + +describe('Hook.texts — a key the source asks for literally is refused at save when undeclared', () => { + const texts = { follow_up_subject: { message: 'Follow up', params: ['lead'] } }; + + it('refuses a literal ctx.text key that texts does not declare, at body.source', () => { + const r = HookSchema.safeParse({ ...base, body: body("await ctx.text('follow_up_title');"), texts }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'body.source')!; + expect(issue.message).toBe(undeclaredHookTextKeyAtSave('follow_up_title', ['follow_up_subject'], 'body.source')); + }); + + it('reads an inline handler\'s own source, at handler', () => { + const handler = async (ctx: any) => { await ctx.text('follow_up_title'); }; + const r = HookSchema.safeParse({ ...base, handler, texts }); + expect(r.success).toBe(false); + expect(r.error!.issues.some((i) => i.path.join('.') === 'handler')).toBe(true); + }); + + it('CONTROL: a declared key, a key in a comment or a longer string, and a computed key all pass the save', () => { + const source = [ + ASKS, + "// await ctx.text('not_declared')", + "const note = \"ctx.text('not_declared') is how\";", + 'const k = pick(); await ctx.text(k);', + ].join('\n'); + expect(HookSchema.safeParse({ ...base, body: body(source), texts }).success).toBe(true); + expect(hookTextKeysAskedIn(source)).toEqual(['follow_up_subject']); + }); + + it('a hook that declares no texts is not read for ctx.text calls (the run-time fault names it)', () => { + expect(HookSchema.safeParse({ ...base, body: body("await ctx.text('anything');") }).success).toBe(true); + expect(undeclaredHookTextAtRun('lead_follow_up', 'anything', [])).toMatch(/hook 'lead_follow_up' asked for text 'anything'.*declared: none/); + }); +}); + +describe('hooks..texts..message — the translation face', () => { + it('spells the key the runtime reads', () => { + expect(hookTextMessageKey('lead_follow_up', 'follow_up_subject')).toBe('hooks.lead_follow_up.texts.follow_up_subject.message'); + }); + + it('accepts a translated text under the hook, and refuses an undeclared key in the entry', () => { + expect(TranslationDataSchema.safeParse({ + hooks: { lead_follow_up: { texts: { follow_up_subject: { message: '跟进已认定线索:{{ lead }}' } } } }, + }).success).toBe(true); + expect(TranslationDataSchema.safeParse({ + hooks: { lead_follow_up: { texts: { follow_up_subject: { message: 'x', status: 400 } } } }, + }).success).toBe(false); + }); +}); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 82fc0ad8e6f..f10091440e9 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -35,11 +35,16 @@ import { HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE, HOOK_REFUSAL_PARAM_PATTERN, HOOK_REFUSAL_REASON_PATTERN, + HOOK_TEXT_KEY_PATTERN, + HOOK_TEXT_MESSAGE_HOLE_REFUSED, hookRefusalCodesThrownIn, hookRefusalReasonsThrownIn, hookRefusalsWithoutSandboxedBody, + hookTextKeysAskedIn, + hookTextsWithoutRunnableCode, undeclaredHookRefusalCodeAtSave, undeclaredHookRefusalReasonAtSave, + undeclaredHookTextKeyAtSave, } from './hook-refusal-codes'; // [#33214] The closed-scope `{{ }}` judge a refusal message with declared // `params` is read by — the one the action copy slots and a bulk action's @@ -336,6 +341,37 @@ function refuseUndeclaredLiteralRefusalCode( } } +/** + * [#34374, ruling 6913660232 parameter 7] The object-level check that refuses + * `texts` nothing could ask for, and a key a hook's source asks for literally + * (`ctx.text('key')`) that `texts` does not declare — the refusal catalogue's + * two halves above, for the sentences a hook writes into a record. + */ +function refuseUndeclaredLiteralTextKey( + hook: { + texts?: Record; + body?: { language?: string; source?: unknown }; + handler?: unknown; + }, + ctx: z.RefinementCtx, +): void { + if (!hook.texts) return; + const hasHandler = typeof hook.handler === 'function' || (typeof hook.handler === 'string' && hook.handler.length > 0); + const answered = hook.body === undefined ? hasHandler : hook.body.language === 'js'; + if (!answered) { + ctx.addIssue({ code: 'custom', path: ['texts'], message: hookTextsWithoutRunnableCode(hook.body?.language) }); + return; + } + const read = refusalSourceOf(hook); + if (!read) return; + const path = read.at === 'body.source' ? ['body', 'source'] : ['handler']; + const declared = Object.keys(hook.texts); + for (const key of hookTextKeysAskedIn(read.source)) { + if (Object.prototype.hasOwnProperty.call(hook.texts, key)) continue; + ctx.addIssue({ code: 'custom', path, message: undeclaredHookTextKeyAtSave(key, declared, read.at) }); + } +} + /** * One sentence under a declared refusal code (#33214, ruling 6879477573, * S1): the sentence the user reads when the hook throws the code with this @@ -478,6 +514,78 @@ export const HookRefusalSchema = lazySchema(() => strictObject( export type HookRefusal = z.input; +/** The slot a hook text's `{{ }}` holes are judged in, as a sentence names it. */ +const HOOK_TEXT_MESSAGE_SLOT = 'A hook text `message`'; + +/** + * One declared text of a hook (#34374, ruling 6913660232 parameter 7): a + * sentence the hook writes into a record for people to read, picked in the + * ORGANIZATION's language when the hook asks for it (`ctx.text(key, params)`). + * + * The message is the source-locale sentence and the fallback; its translation + * is `hooks..texts..message`, picked first, its `{{ NAME }}` holes + * filled from the call's `params` after — a declared refusal's posture + * ({@link HookRefusalSchema}), with the organization's language in place of + * the caller's. An entry that declares no `params` is plain text and a hole in + * it is refused. With `params`, a hole over an undeclared name is refused at + * parse; a hole holding logic, an unknown formatter, an empty hole and a + * `currency` formatter with no code are refused where the text is compiled — + * `os validate`, `compile` and the publish gate (`@objectstack/lint` + * `validate-hook-refusal-templates.ts`, which judges `texts` beside + * `refusals`). A translation whose holes do not render at run time is dropped + * for this `message`, filled. + */ +export const HookTextSchema = lazySchema(() => strictObject( + { + surface: 'this hook text', + history: 'Closed from the day it was declared — a key this entry does not declare would be served nowhere.', + aliases: { + text: 'message', template: 'message', value: 'message', description: 'message', + placeholders: 'params', parameters: 'params', variables: 'params', + }, + guidance: { + locale: + 'A hook text has no language of its own — the runtime picks the organization\'s language. Write the sentence ' + + 'in the source locale in `message` and translate it through `hooks.HOOK.texts.KEY.message`.', + }, + }, + { + message: z.string().trim().min(1).describe( + 'The sentence the hook writes into a record — in the source locale, translated whole through ' + + 'hooks..texts..message in the organization\'s language when the hook asks for it (ctx.text). ' + + 'With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional ' + + 'known formatter', + ), + params: z.array( + z.string().regex(HOOK_REFUSAL_PARAM_PATTERN, { + message: 'A text param is an identifier (e.g. lead) — the root a {{ }} hole names', + }), + ).optional().describe( + 'The names this text may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook passes ' + + 'in ctx.text(KEY, { NAME: value }). A hole over any other name is refused at parse; a hole holding logic, an ' + + 'unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled ' + + '(os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is refused', + ), + }, +).superRefine((entry, ctx) => { + const params = entry.params; + if (params) { + const seen = new Set(); + params.forEach((name, i) => { + if (seen.has(name)) { + ctx.addIssue({ code: 'custom', path: ['params', i], message: `\`params\` names '${name}' twice — declare each once.` }); + } + seen.add(name); + }); + } + const refusal = !params || params.length === 0 + ? (HOOK_REFUSAL_MESSAGE_WITHOUT_HOLE.test(entry.message) ? undefined : HOOK_TEXT_MESSAGE_HOLE_REFUSED) + : closedScopeTemplateRefusal(entry.message, { slot: HOOK_TEXT_MESSAGE_SLOT, roots: params }); + if (refusal !== undefined) ctx.addIssue({ code: 'custom', path: ['message'], message: refusal }); +})); + +export type HookText = z.input; + /** * Hook Lifecycle Events * Defines the interception points in the ObjectQL execution pipeline. @@ -869,6 +977,48 @@ export const HookSchema = lazySchema(() => strictObject( + 'it literally, otherwise at run time; under a code with no reasons a thrown reason is not read', ), + /** + * The hook's declared texts (#34374, ruling 6913660232 parameter 7): every + * sentence it writes into a record for people to read, keyed by a snake_case + * key its code asks for. + * + * texts: { + * follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] }, + * } + * + * await ctx.api.object('crm_task').insert({ subject: await ctx.text('follow_up_subject', { lead }) }); + * + * `ctx.text(key, params?)` answers the sentence in the ORGANIZATION's + * language, never the caller's (parameter 2): the Localization setting when + * somebody set it, else the app's `i18n.defaultLocale` (parameter 3, the one + * shared reader `resolveOrganizationLocale` the flow record write reads). It + * picks `hooks..texts..message` first and fills the `{{ }}` holes + * from `params` after (parameter 1). With no translation, or no language, + * the declared sentence is answered and the hook goes on (parameter 5). A + * Localization setting that cannot be READ rejects the call: the + * organization's language may exist and could not be known. A string the + * hook builds itself is written as it is (parameter 4). + * + * A key the hook's source asks for literally that `texts` does not declare + * is refused at save; any other undeclared key is refused when the hook + * runs. Served on every path a hook runs on — a sandboxed `js` body and an + * in-process `handler` — and refused on a hook whose code cannot ask for one + * (an `expression` body, or neither a body nor a handler). Keyed by hook + * name, not by object. Absent: `ctx.text` has nothing to answer. + */ + texts: z.record( + z.string().regex(HOOK_TEXT_KEY_PATTERN, { + message: 'A text key is snake_case (e.g. follow_up_subject) — the key the hook asks for with ctx.text', + }), + HookTextSchema, + ).optional().describe( + 'Texts the hook writes into records, keyed by the snake_case key its code asks for with ctx.text(KEY, params): ' + + '{ message, params? }. ctx.text answers the sentence in the organization\'s language (the Localization setting ' + + 'when somebody set it, else the app\'s i18n.defaultLocale), translated through hooks..texts..message ' + + 'with the declared message as the fallback, its holes filled from params. A key not declared here is refused — ' + + 'at save when the hook asks for it literally, otherwise at run time', + ), + /** * Execution identity for the hook's `ctx.api` data operations (#14010; * ruling 2026-09-01). The value semantics of `'system'` / `'user'` are @@ -944,11 +1094,13 @@ export const HookSchema = lazySchema(() => strictObject( // [#25653] the second `runAs` with `body`, [#26170] the third `refusals` // with `body`, pairs no field-level refine can see together; [#32004] the // fourth refuses a body's `email.send` grant, which only the hook can judge, - // since an action's body takes it. A schema DERIVED from this one by overriding a key must use `.safeExtend()` (zod + // since an action's body takes it; [#34374] the fifth pairs `texts` with + // `body` / `handler`, as the third pairs `refusals`. A schema DERIVED from this one by overriding a key must use `.safeExtend()` (zod // refuses `.extend()` over a refined object), which is what keeps every // check on the derived schema too. }).superRefine(refuseBodyOnStoredMetadataTarget).superRefine(refuseElevatedIdentityAssignmentBodyWrite) - .superRefine(refuseUndeclaredLiteralRefusalCode).superRefine(refuseHookBodyMailGrant)); + .superRefine(refuseUndeclaredLiteralRefusalCode).superRefine(refuseHookBodyMailGrant) + .superRefine(refuseUndeclaredLiteralTextKey)); /** * Hook Runtime Context diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index e3a7d44cc7c..1b76faae1a6 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -4446,6 +4446,20 @@ export function hookRefusalMessageKey(hookName: string, code: string, reason?: s : `hooks.${hookName}.refusals.${code}.reasons.${reason}.message`; } +/** + * Dot-notation i18n key for a hook's declared text — + * `hooks..texts..message` (#34374, ruling 6913660232 parameter 7). + * + * The sibling of {@link hookRefusalMessageKey} for a sentence the hook WRITES + * into a record rather than refuses with: the hook runtime answers + * `ctx.text(key, params)` with this translation in the ORGANIZATION's language + * (never the caller's), the declared sentence on a miss, and fills its holes + * after. By hook, never by object. + */ +export function hookTextMessageKey(hookName: string, key: string): string { + return `hooks.${hookName}.texts.${key}.message`; +} + /** * Dot-notation i18n key for a screen's heading or body text — * `flows..screens..title` / `.description` (#22507). diff --git a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts index 11933fba8bb..a8c74bb6597 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -464,6 +464,17 @@ const LEDGER: ReadonlyArray = [ key: 'homeAmount', why: "planned, not yet written — the `{ field, rateDate, rateField }` pointers are validated at parse (all three required, each judged against the object's field map), but no engine converts the amount or stores the home amount and the rate until the write-time home-currency projection lands, which ADR-0144 D9 releases with this key. A form control offered today would let an author declare a home amount nothing writes", }, + // #34374 — a hook's declared texts land in the hook's source first. The + // Studio row (a key-only record beside `refusals`, with its help text in + // the eleven metadata-forms bundles) is a follow-up, so this row records + // why the key is not offered yet. + { + kind: 'omit', + type: 'hook', + path: ROOT_PATH, + key: 'texts', + why: "live, not yet offered in the Studio — the sentences a hook writes into records (`ctx.text`, answered in the organization's language) are validated at parse (snake_case keys, closed-scope holes over declared `params`, a literal `ctx.text` key the hook does not declare refused at save) and read at run time, and they are declared in the hook's package source beside the code that asks for them. The Studio row, a key-only record beside `refusals`, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then a hook authored in the Studio declares `texts` through the metadata API or its package source", + }, // #27946 — an action's pressed-state predicate lands spec-first the same // way: `planned` in the liveness ledger, drawn by no action surface until // the console card that draws `aria-pressed` on the header buttons. diff --git a/packages/spec/src/system/translation.zod.ts b/packages/spec/src/system/translation.zod.ts index c502db0aab4..bf3c2385df4 100644 --- a/packages/spec/src/system/translation.zod.ts +++ b/packages/spec/src/system/translation.zod.ts @@ -2099,6 +2099,7 @@ const appTranslationDataShape = () => ({ * * hooks..refusals..message (a declared refusal, `HookSchema.refusals`) * hooks..refusals..reasons..message (a declared reason under it, #33214) + * hooks..texts..message (a declared text, `HookSchema.texts`, #34374) * * A hook's business refusal ("A current clean version is required before * signing.") is the sentence a user reads most often when an app says "not @@ -2127,17 +2128,26 @@ const appTranslationDataShape = () => ({ * posture (translated before it is rendered). A sentence whose entry declares * no `params` is plain text and nothing in it is filled. * + * **A declared text is picked in the organization's language (#34374, + * ruling 6913660232 parameter 7).** A sentence a hook writes into a record + * (`HookSchema.texts`) is answered by `ctx.text(key, params)` through + * `hookTextMessageKey(hook, key)` in the ORGANIZATION's language — the + * Localization setting when somebody set it, else the app's + * `i18n.defaultLocale` — never the caller's; the declared sentence on a miss, + * its holes filled after, as for a refusal. + * * `objectstack validate` refuses a key over an unknown hook, a code the hook's - * `refusals` does not declare, or a reason that code does not declare. + * `refusals` does not declare, a reason that code does not declare, or a text + * key the hook's `texts` does not declare. */ hooks: z.record(z.string(), strictObject({ surface: 'this hook translation', history: TRANSLATION_HISTORY, - aliases: { refusal: 'refusals', errors: 'refusals', messages: 'refusals' }, + aliases: { refusal: 'refusals', errors: 'refusals', messages: 'refusals', text: 'texts', sentences: 'texts' }, guidance: { label: - 'A hook has no translated label — the one string of a hook a user reads is a refusal. Translate ' - + '`refusals..message`.', + 'A hook has no translated label — the strings of a hook a user reads are its refusals and the texts it ' + + 'writes into records. Translate `refusals..message` or `texts..message`.', }, }, { refusals: z.record(z.string(), strictObject({ @@ -2165,6 +2175,21 @@ const appTranslationDataShape = () => ({ ), })).optional().describe("Reason translations keyed by the reason the code's `reasons` declares"), })).optional().describe("Refusal translations keyed by the code the hook's `refusals` declares"), + // [#34374] A declared text's sentence, picked in the organization's language. + texts: z.record(z.string(), strictObject({ + surface: 'this hook text translation', + history: TRANSLATION_HISTORY, + // The spellings `HookTextSchema` renames onto its own `message`. + aliases: { text: 'message', template: 'message', value: 'message', description: 'message' }, + }, { + // The declared message's own form — plain text, or a template over the + // entry's declared `params`; an empty string is the untranslated + // skeleton slot `os i18n extract` writes (the declared message is served). + message: z.string().optional().describe( + "Translated sentence of a hook's declared text — written into the record in the organization's language in " + + 'place of the declared message, its {{ }} holes (over the entry\'s declared params) filled after', + ), + })).optional().describe("Text translations keyed by the key the hook's `texts` declares"), })).optional().describe('Hook translations keyed by hook name'), /** diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 458944eea33..98d5e5a39d8 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -304,7 +304,7 @@ import type * as M204 from './ai/dataset-tools.zod.js'; import type * as M205 from './ai/object-query-source.zod.js'; // --------------------------------------------------------------------------- -// 856 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 857 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -959,6 +959,7 @@ export type Iso_data_hookBodyDoors__BodyDoorRecordRefSchema = Assert, z.infer< typeof M69.HookContextSchema > >>; export type Iso_data_hook__HookEvent = Assert, z.infer< typeof M69.HookEvent > >>; export type Iso_data_hook__HookRefusalSchema = Assert, z.infer< typeof M69.HookRefusalSchema > >>; +export type Iso_data_hook__HookTextSchema = Assert, z.infer< typeof M69.HookTextSchema > >>; // data/mapping.zod.ts export type Iso_data_mapping__TransformType = Assert, z.infer< typeof M179.TransformType > >>; @@ -1831,7 +1832,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 856 isomorphic pins', () => { + it('still declares all 857 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2904,7 +2905,11 @@ describe('ADR-0122 type-alias convention', () => { // that schema's own pin still holds: parse fabricates nothing // (Iso_api_protocol__BuildProbeReportSchema, // Iso_api_protocol__RuntimeBuildIssueSchema). +2 added. - expect(pins).toHaveLength(856); + // 856 -> 857 is #34374: a hook's declared text entry, `HookTextSchema` + // (`data/hook.zod.ts`), closed at `message` / `params` with no default or + // transform, pinned here (Iso_data_hook__HookTextSchema) beside its + // refusal sibling rather than given a `…Parsed` synonym. +1 added. + expect(pins).toHaveLength(857); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either diff --git a/skills/objectstack-data/references/_index.md b/skills/objectstack-data/references/_index.md index 45d7f71489f..55f2b91ea75 100644 --- a/skills/objectstack-data/references/_index.md +++ b/skills/objectstack-data/references/_index.md @@ -11,7 +11,7 @@ from `node_modules` — there is no local copy in the skill bundle. - `node_modules/@objectstack/spec/src/data/datasource.zod.ts` — Exports: DriverType, DriverDefinitionSchema, SchemaModeSchema, ExternalDatasourceSettingsSchema, DatasourceSchema - `node_modules/@objectstack/spec/src/data/field.zod.ts` — Exports: FieldType, SelectOptionSchema, LocationCoordinatesSchema, CurrencyConfigSchema, UniqueScopeSchema -- `node_modules/@objectstack/spec/src/data/hook.zod.ts` — Exports: HookRefusalSchema, HookEvent, HookSchema, HookContextSchema +- `node_modules/@objectstack/spec/src/data/hook.zod.ts` — Exports: HookRefusalSchema, HookTextSchema, HookEvent, HookSchema, HookContextSchema - `node_modules/@objectstack/spec/src/data/object.zod.ts` — Exports: ApiMethod, ApiOperationSchema, ObjectCapabilities, IndexSchema, TenancyConfigSchema - `node_modules/@objectstack/spec/src/data/seed.zod.ts` — Exports: SeedMode, SeedColumnSchema, SeedSchema, leadSeed - `node_modules/@objectstack/spec/src/data/validation.zod.ts` — ObjectStack Validation Protocol diff --git a/skills/objectstack-platform/references/_index.md b/skills/objectstack-platform/references/_index.md index 8c6c61b56d9..7099833c320 100644 --- a/skills/objectstack-platform/references/_index.md +++ b/skills/objectstack-platform/references/_index.md @@ -23,7 +23,7 @@ from `node_modules` — there is no local copy in the skill bundle. ## Transitive dependencies - `node_modules/@objectstack/spec/src/data/field.zod.ts` — Exports: FieldType, SelectOptionSchema, LocationCoordinatesSchema, CurrencyConfigSchema, UniqueScopeSchema -- `node_modules/@objectstack/spec/src/data/hook.zod.ts` — Exports: HookRefusalSchema, HookEvent, HookSchema, HookContextSchema +- `node_modules/@objectstack/spec/src/data/hook.zod.ts` — Exports: HookRefusalSchema, HookTextSchema, HookEvent, HookSchema, HookContextSchema - `node_modules/@objectstack/spec/src/data/object.zod.ts` — Exports: ApiMethod, ApiOperationSchema, ObjectCapabilities, IndexSchema, TenancyConfigSchema - `node_modules/@objectstack/spec/src/security/rls.zod.ts` — Row-Level Security (RLS) Protocol - `node_modules/@objectstack/spec/src/ui/app.zod.ts` — Exports: ObjectNavItemSchema, DashboardNavItemSchema, PageNavItemSchema, UrlNavItemSchema, ReportNavItemSchema