Skip to content

Commit 11e0441

Browse files
feat(spec, runtime, lint, core): a hook writes the sentences it declares in the organization's language (ctx.text) (#34545)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Qsbvr2NRYcFNgPCJ7PDjgK)_ Part of #34374 Clause-②: yes (widening) — a hook may now declare `texts` and its code may call `ctx.text`; translation bundles accept `hooks.<hook>.texts.<key>.message`; `@objectstack/core` exports `readOrganizationTextLocale`. Nothing that was accepted before is refused Metadata-protocol: added Skills-docs: follow-up #34546 This is the **hook half** of #34374 (ruling 6913660232 option B, parameter 7; split recorded on the card by `repo:objectstack#2`). The **action half is left to PR2**: action-written text (`objects.<obj>._actions.<act>.*` / `globalActions.<act>.*`, e.g. HotCRM's `send_email` script action writing `'Email: ' + subject`) lands after #34273 merges, reuses #34273's shared declared-entry factory, starts from fresh main, and is the PR that closes the card. This PR does not touch `action.zod.ts`. ## 维护者速读 - 改了什么:钩子可以声明自己写进记录给人读的句子(`texts`),运行时用 `await ctx.text('key', { … })` 取,按**组织语言**给出(Localization 设置有人设过就用它,否则应用的 `i18n.defaultLocale`),从不按触发保存的那个人的语言。 - 为什么改:HotCRM 的线索/工单钩子把「Follow up with qualified lead: …」这类英文句子写进任务标题,中文、日文组织里大家读到的都是英文;裁定 B 第 7 项要求和已声明的钩子拒绝语同一规则。 - 风险与回滚:纯新增,未声明 `texts` 的钩子行为不变;缺译文写声明原文,不失败;只有 Localization 设置读不出来(非「未注册」)时那次 `ctx.text` 拒绝。回滚即 revert。 - 先看:`packages/runtime/src/sandbox/hook-text.ts`(取语言、选译文、填洞),然后 `packages/spec/src/data/hook.zod.ts` 的 `texts` 与保存期检查。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run src/sandbox/hook-text.integration.test.ts`,预期 11 条全过(返工后加了「译文渲染不了回落到声明句」在两条路径上各 1 条)。 - 需要你做的:无,席位落地;动作一半在 PR2(等 #34273 合并)。 ## What changes - **Spec — `HookSchema.texts`** (`packages/spec/src/data/hook.zod.ts`, `hook-refusal-codes.ts`): a hook declares `texts: { <snake_case key>: { message, params? } }`. `params` names the `{{ }}` holes, under the same closed-scope rule a declared refusal's message follows; a text with no `params` is plain and a hole in it is refused. Save-time checks: `texts` on an `expression` body or on a hook with neither body nor handler is refused at `texts`; a `ctx.text('<literal>')` key the hook does not declare is refused at `body.source` / `handler` (comments and strings are masked; a computed key is left to the run). - **Spec — translation face** (`i18n-resolver.ts`, `translation.zod.ts`): the key is `hooks.<hook>.texts.<key>.message` (`hookTextMessageKey`); the translation bundle's `hooks.<hook>` group accepts `texts`. - **Core — one reading of the organization's language** (`packages/core/src/organization-locale.ts`): `readOrganizationTextLocale(getService, organizationId)` — the Localization setting somebody set (`source !== 'default'`), else the app's `i18n.defaultLocale`, else nothing. An unregistered Localization namespace/key (`SETTINGS_UNKNOWN_NAMESPACE` / `SETTINGS_UNKNOWN_KEY`) is "not set"; any other read failure propagates. The flow record write (`service-automation`) used its own private copy of exactly this; it now calls the shared one, answers unchanged. - **Runtime — `ctx.text(key, params?)`** (`packages/runtime/src/sandbox/hook-text.ts`, `body-runner.ts`, `quickjs-runner.ts`, `script-runner.ts`, `app-artifact-handlers.ts`): translate the template first (through the `i18n` service, negotiated as refusals are), then fill the holes through the formula template engine (`renderHookTemplate`, shared with the refusal filler, which keeps its behaviour). A missing translation answers the declared `message`; a translation whose holes do not render is dropped for the declared `message`, filled, with a warning that says so; an undeclared key throws a `SandboxError` naming the hook and the key. Same answer on a sandboxed `js` body (installed on the VM's `ctx`) and an in-process `handler` (the `withInProcessHookTitle` seam). - **Lint** (`i18n-walk.ts`, `validate-translation-references.ts`, `validate-hook-refusal-templates.ts`): `os i18n extract` scaffolds `hooks.<hook>.texts.<key>.message` with the declared sentence; `objectstack validate` refuses a `hooks.<hook>.texts.<key>` translation over a key the hook does not declare (nearest key offered). The compile half of a hook sentence (#33214) now judges `texts.<key>.message` for an entry with `params` beside the refusal sentences: logic, an unknown formatter, an empty hole and `currency` with no code are errors at `objectstack validate`, `compile` and the publish gate's `hook` write. - **Docs**: `automation/hooks.mdx` (new section), `automation/hook-bodies.mdx` (`ctx.text` row), `ui/translations.mdx` (key row). - **Generated**: dropped-refinements baseline (the new `HookText` object-level check and the `texts.valueType` sites), liveness rows (`hook.texts`, `translation.hooks.texts`), and the `check:generated --fix` outputs (api-surface, export-origins, declaration-map, reference docs, strictness ledger, liveness counts, and the two generator-owned `skills/*/references/_index.md` lines that list `HookTextSchema`). Not changed: no backfill of rows already written (parameter 6); no `org.locale` root (parameter 8); a string a hook builds itself is written as it is (parameter 4). ## Tests - **`packages/runtime/src/sandbox/hook-text.integration.test.ts`** (new): the HotCRM lead follow-up shape on the real `ObjectQL` + `SqlDriver` (better-sqlite3) + `QuickJSScriptRunner` + in-memory `i18n`, on **both** the sandboxed body and the in-process handler path, every assertion on the stored task row. An en-US caller in a zh-CN app writes the zh-CN translation, holes filled; a ja-JP Localization setting somebody set wins and is asked in the write's organization (CONTROL: the `source: 'default'` placeholder does not count); no translation writes the declared sentence filled; `SETTINGS_UNKNOWN_KEY` answers the app default while `SETTINGS_STORE_UNAVAILABLE` rejects the update with no task written; an undeclared key rejects naming hook and key; a translation whose holes do not render writes the declared sentence filled and warns so (CONTROL: a translation that renders, with a known formatter, is written). - **`packages/spec/src/data/hook-texts.test.ts`** (new): schema acceptance, key pattern, hole rules, alias, expression-body / no-code refusal, handler acceptance, literal undeclared key at `body.source` and `handler`, masked-comment/string/computed-key CONTROL, run-time message, translation face, key spelling. - **`packages/core/src/organization-locale.test.ts`**: `readOrganizationTextLocale` — set wins in the organization; no settings / placeholder → app default; unregistered namespace/key → app default; other failure rejects; no lookup → nothing. - **`packages/lint/src/validate-hook-refusal-templates.test.ts`**: a hook text with `params` — CONTROLs accepted (a path, a known formatter, `currency:EUR`, plain text); an unknown formatter, logic and an empty hole refused as errors at `texts.<key>.message`; `currency` with no code refused naming `currency:EUR`; a text with no `params` not read; a text and a refusal on one hook each at its own path; part of the stack expression pass; refused at the publish gate's `hook` write (CONTROL passes). - **`packages/lint/src/validate-translation-references.test.ts`**, **`i18n-walk.test.ts`**: declared text passes; undeclared key refused with suggestion; key on a hook with no `texts` refused; the walk yields the key with the declared sentence from the `hook` bucket. - **Forced test changes**: `packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts` (`hook` serves 24 top-level properties, was 23); `packages/spec/src/system/metadata-form-zod-reconciliation.test.ts` (a root ledger row for `hook.texts`); `packages/spec/src/type-alias-convention.pin.test.ts` pins `HookTextSchema` as an isomorphic alias (ADR-0122; no default, no transform, beside `HookRefusalSchema`) and moves the pin count by one (857 after merging main, which added two). No other existing test was changed. ## Acceptance notes - **Action half → PR2** (after #34273), as above. - The Studio hook form (`hook.form.ts`) gets no `texts` row in this PR: adding one needs its labels and help text translated in the eleven metadata-forms bundles, which is outside this half's file surface. The form↔Zod reconciliation records the omission as a root ledger row, owed to a follow-up card. A hook authored in Studio can still carry `texts` through its source. Filed: #34575. - `ctx.text` is a pull API rather than a write-time marker because the HotCRM hooks truncate and compose the sentence (both cut to 255 characters) before writing it. - New public names, confirmed by the seat: `texts`, `ctx.text`, `HookTextSchema`, `hookTextMessageKey`. `readOrganizationTextLocale` is kept because its reading differs from main's `readOrganizationLocaleSetting` (it is built on it, not beside it); its JSDoc carries the side-by-side table below. | the Localization setting answers… | `readOrganizationLocaleSetting` | `readOrganizationTextLocale` | |:--|:--|:--| | set (`source: 'tenant'`, `ja-JP`) | `ja-JP` | `ja-JP` | | the `source: 'default'` placeholder | `undefined` | the app default (`zh-CN`) | | no settings service | `undefined` | the app default (`zh-CN`) | | `SETTINGS_UNKNOWN_KEY` | rejects | the app default (`zh-CN`) | | `SETTINGS_STORE_UNAVAILABLE` | rejects | rejects | Read by a probe at head over both exports (app default `zh-CN`, organization `org_1`). The flow record write's private copy of the second column (`service-automation`) is gone; the seed loader keeps the first. - Needs a contract-tier review (`Metadata-protocol: added`). ## Verification Every heavy run went under `os-verify-lock`. - Head 7b8d110 merges main d57d6ee through `scripts/pm/os-regen-merge.sh` (merge 5e33619, then the regeneration commit 7b8d110). `packages/spec/dropped-refinements.baseline.json` conflicted only in its `measured` header (main 268 / 1116, this PR +1 schema / +6 sites) and was recomputed from the merged body, 269 / 1122; `authorable-surface/data.json` and `content/docs/references/data/hook.mdx` were regenerated from the merged tree (`gen:schema`, `gen:docs`) rather than text-merged. After the merge: `check:generated` 14/14; `@objectstack/spec` tests 848 files, 27168 passed; `@objectstack/lint` 214 files, 9107 passed; runtime sandbox + app-artifact-handlers 52 files, 649 passed; spec, lint and runtime `typecheck` exit 0 (runtime's first run was red on a stale local `driver-turso` build, green after rebuilding it). `check-governed-merges.mjs --pr 34545` at 7b8d110: "0 of 48 path(s) hit the register after 2 generated-artifact lift(s) (13 surfaces govern objectstack). ✅ NOT governed". Outside the baseline and the generated docs and surface, this PR's diff against main is line-for-line the one reviewed at 8929099 (`git diff 31096af 8929099` against `git diff d57d6ee 7b8d110`, same changed lines). - Head 8929099 is L1 rework round 1 (review 6937770388), plus a merge of main 31096af: - Item 1: `validate-hook-refusal-templates.ts` judges hook texts; `hook-text.ts` falls back from a translation that does not render to the declared `message`, filled. `@objectstack/lint` `validate-hook-refusal-templates.test.ts` 24/24; runtime `hook-text.integration.test.ts` + hook-refusal suites 49/49. - Ablations (restored, `git diff` empty after each): the lint pass skipping `texts` ⇒ 7 of 24 red (every refusal case, the stack pass and the publish gate; the 4 CONTROLs and the no-`params` case stay green). The run-time fallback writing the unrendered translation ⇒ 2 of 11 red (the new case, both paths). - `HookTextSchema.params`, its JSDoc, `automation/hooks.mdx` and the changeset now say where each hole is refused (parse, or `os validate` / `compile` / the publish gate). The liveness row `hook.texts.params` is re-anchored at `renderHookTemplate`. - Merge of main 31096af: the alias pin count resolves to 857 (main 854 → 856, this PR +1), with both history lines; `gen:schema` and `gen:docs` exit 0; `check:generated` failed `check:liveness` on its first run (the `hook.texts.params` citation named the replaced filler) and passed 14/14 after the re-anchor above. - Gates: `dispatch-gates --commands` derived 129 families at 8929099; all 129 ran: 128 exit 0, and `check:skill-examples` exit 3 on a stale `@objectstack/client` dist (nothing measured), exit 0 on its rerun after `pnpm --filter @objectstack/client build`. - `node scripts/pm/check-governed-merges.mjs --pr 34545` at 8929099, in a built tree: "governed-surface predicate: 0 of 48 path(s) hit the register after 2 generated-artifact lift(s) (13 surfaces govern objectstack). ✅ NOT governed". Both `skills/*/references/_index.md` lines read as a pure `gen:skill-refs` regeneration on this tree (#11705). - `@objectstack/runtime` sandbox + app-artifact-handlers suites: 10 files, 308 passed (the hook-text pin 9/9 again at head). `@objectstack/core` `organization-locale.test.ts`: 10 passed. `@objectstack/lint` walk + translation references: 255 passed. `@objectstack/service-automation`: 286 files, 4076 passed. `@objectstack/spec` hook texts + hook refusals: 113 passed. - Typecheck (`tsc --noEmit`) of core, runtime, lint, service-automation: exit 0. `pnpm --filter @objectstack/spec check:generated`: 14/14 green after `--fix`; `check:test-typecheck` green. - **Ablation** (`scripts/ablation-replace.mjs`, restored, blob == HEAD, `git diff HEAD` empty): replace the translation pick in `hook-text.ts` with `undefined` ⇒ 6 of 9 integration tests red (every translated-language pin, both paths); the 3 that stay green are the missing-translation fallback (both paths) and the undeclared-key refusal, which read no translation. - Head df9ac15 merges main 8dd8192. `packages/spec/dropped-refinements.baseline.json` conflicted only in its `measured` header (main moved sites 1090 → 1114, this PR 1090 → 1096); the header was recomputed from the merged body, 267 schemas / 1120 sites, and `authorable-surface/data.json` was regenerated with `gen:schema`. After the merge: `check:generated` exit 0; `@objectstack/spec` local tests 848 files, 27148 passed; runtime sandbox + app-artifact-handlers 52 files, 647 passed; runtime and service-automation `typecheck` exit 0 (runtime's first run was red on a stale local `driver-turso` build, green after rebuilding it). - Head 70a4381 fixes `Test Core (2/8)` at aae87d7: `scripts/dropped-refinements.test.ts` checks that the ledger's `measured` header totals equal its body. The hand-edited rows for `HookText` and the four hook `texts.valueType` sites were added, but the header still read 266 schemas / 1090 sites; it now reads 267 / 1096. `@objectstack/spec` local project: 847 files, 1 failed before the fix (this test), 27/27 in the file after. - Head aae87d7 fixes three red CI checks at d4e652a: - `Type Check · workspace`: the new pin imported `EngineInsertOptions`, which `@objectstack/spec/data` does not export; it now names `DataEngineInsertOptions`. `pnpm --filter @objectstack/runtime typecheck` (with `check:test-typecheck`) exit 0; core, lint and service-automation `typecheck` exit 0. - `Test Core (2/8)`: `metadata-form-zod-reconciliation.test.ts` refused `texts` as accepted by the Zod but not offered by the hook form. A root ledger row (`omit`, `hook`, `texts`) now records why: the Studio row is owed to a follow-up (see Acceptance notes). 76/76. - `Test Core (6/8)`: `protocol.meta-types-degenerate-derivation.test.ts` pins the top-level property count `/meta/types` serves; `hook` 23 → 24 for `texts`, with its history line. `@objectstack/metadata-protocol`: 355 files, 1 failed before the fix (this pin), 18/18 in the file after. - Affected gates rerun: `check:query-options-erasure`, `check:slot-lookup`, `check:test-source-alias`, `check:type-check-debt` exit 0; `check:generated` exit 1 on a first run beside a concurrent build and exit 0 on a second run. - Head d4e652a: the changeset's `Clause-②` line now reads `yes (widening)`, matching `Metadata-protocol: added` (CI `Check Changeset` refused `no` beside `added`). `check-empty-changeset` and `check:changeset-fixed` exit 0. - Head a3a4bb5 merges main 107d2e8. GitHub read the PR as conflicting because both sides moved the generated schema counts in `content/docs/references/index.mdx` (this PR +1 in Data, main +1 in UI), and GitHub does not use the repo's merge driver for generated artifacts. The local merge applied that driver. Resolution: `gen:docs` on the merged tree (1667 schemas: Data 188, UI 177), then `check:generated` 14/14 and `check:docs` exit 0. `check-governed-merges --pr 34545`: NOT governed, and both `skills/*/references/_index.md` lines are a pure `gen:skill-refs` regeneration on this tree (#11705). - Head 7bebb37 (35212cf plus a JSDoc table on `readOrganizationTextLocale` and the `Skills-docs` line in the changeset): core `organization-locale.test.ts` 10 passed and `tsc --noEmit` exit 0; the same 129-family derivation, of which the 26 changeset/docs/core families reran with exit 0. At 35212cf, merged with main after branching from e8cba8f. Gates: `dispatch-gates --commands` derived 129 families; all 129 ran with exit 0 at this head, and `--ran` reports 129 run, 0 NOT-MEASURED, 0 UNRUN. On the first round `check:query-options-erasure` caught two erased options bags in the new pin (now typed) and `check:spec-parsed-alias` asked for the `HookTextSchema` pin (added); the exit-3 prerequisites (shallow clone, unbuilt `client-react` and other dists) were built and every family rerun. --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmNwjZuUekdsr5UH3GP <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRXuRn93HphKp7kXEz --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 77d7f52 commit 11e0441

48 files changed

Lines changed: 1492 additions & 120 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/core': minor
4+
'@objectstack/runtime': minor
5+
'@objectstack/lint': minor
6+
'@objectstack/service-automation': patch
7+
---
8+
9+
feat(hooks): a hook writes the sentences it declares in the organization's language
10+
11+
Clause-②: yes (widening) — a hook may now declare `texts` and its code may call `ctx.text`; translation bundles accept `hooks.<hook>.texts.<key>.message`; `@objectstack/core` exports `readOrganizationTextLocale`. Nothing that was accepted before is refused
12+
Metadata-protocol: added
13+
Skills-docs: follow-up #34546
14+
15+
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.<hook>.texts.<key>.message` is picked first, then its `{{ }}` holes are filled from `params`.
16+
17+
- A missing translation, or no language to pick, answers the declared sentence, and the hook goes on.
18+
- 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.
19+
- 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.
20+
- 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.
21+
- `ctx.text` is the same on a sandboxed `js` body and on an in-process `handler`.
22+
- `os i18n extract` scaffolds the key, and the existing coverage check counts it. `objectstack validate` refuses a `hooks.<hook>.texts.<key>` translation over a key the hook does not declare.
23+
- Text is picked when it is written. Records already written are not changed.
24+
25+
`@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.

‎content/docs/automation/hook-bodies.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ The script sees only what the surrounding `ctx` object exposes:
103103
| `ctx.api.object(name).insert\|update\|delete` | Cross-object writes. | `api.write` |
104104
| `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 |
105105
| `ctx.title('<lookup field>')` | 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` |
106+
| `ctx.text('<key>', 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 |
106107
| `ctx.crypto.randomUUID()` | UUID generation. | `crypto.uuid` |
107108
| `ctx.log.{info,warn,error}` | Structured logging. | `log` |
108109
| `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` |

‎content/docs/automation/hooks.mdx‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,62 @@ export const planGate = {
453453
A hook that declares no `refusals` refuses exactly as before: the thrown
454454
error's own `code`, `status` and message reach the caller.
455455

456+
## Writing a sentence people read — `texts`
457+
458+
A sentence a hook writes into a record — the subject of the follow-up task it
459+
opens, the summary it logs — is read by the whole organization. **Declare it**
460+
on the hook and ask for it by key: the runtime answers it in the
461+
**organization's** language, never the language of the person whose save fired
462+
the hook.
463+
464+
```typescript
465+
export const leadFollowUp = {
466+
name: 'lead_follow_up',
467+
object: 'crm_lead',
468+
events: ['afterUpdate'],
469+
texts: {
470+
follow_up_subject: { message: 'Follow up with qualified lead: {{ lead }}', params: ['lead'] },
471+
},
472+
handler: async (ctx) => {
473+
if (ctx.input.status !== 'qualified' || ctx.previous?.status === 'qualified') return;
474+
const subject = await ctx.text('follow_up_subject', { lead: ctx.input.name });
475+
await ctx.api.object('crm_task').insert({ subject, related_to_lead: ctx.input.id });
476+
},
477+
};
478+
```
479+
480+
- **The organization's language.** The Localization setting when somebody set
481+
it (Setup → Localization), else the app's `i18n.defaultLocale`. A hook a
482+
person's save fires still writes in the organization's language — the record
483+
is data everyone reads, not a message to that person.
484+
- **Translated first, filled after.** `ctx.text` picks
485+
`hooks.<hook>.texts.<key>.message` in that language, then fills the `{{ }}`
486+
holes from the `params` you pass. A text that declares `params` may write
487+
`{{ name }}` holes over those names, with an optional known formatter; one
488+
that declares none is plain text, and a hole in it is refused when the hook
489+
is saved. A hole over another name is refused at save; logic, an unknown
490+
formatter, an empty hole and `{{ amount | currency }}` with no code are
491+
refused by `os validate`, `compile` and the publish gate.
492+
- **A missing translation never fails the hook.** With no translation, or no
493+
language to pick, the declared `message` is written. A translation whose
494+
holes do not render is dropped for the declared `message`, filled.
495+
- **An unreadable Localization setting rejects.** When the settings service
496+
cannot be read, `ctx.text` rejects rather than write another language over
497+
the organization's choice. Catch it if the hook should write anyway.
498+
- **Only declared text is translated.** A string the hook builds itself is
499+
written as it is. A key `texts` does not declare is refused when the hook is
500+
saved if the hook names it literally in `ctx.text('key')`, otherwise when the
501+
hook runs, as a `500` that names the hook and the key.
502+
- **It works whichever way the hook is written** — a TypeScript `handler` and a
503+
sandboxed `js` body get the same `ctx.text`. An `expression` body cannot ask
504+
for one, so `texts` is refused there.
505+
- **Translated by key.** `os i18n extract` scaffolds
506+
`hooks.<hook>.texts.<key>.message` and `os i18n check` counts it. See
507+
[Translations](/docs/ui/translations).
508+
509+
Rows a hook wrote before it declared the text keep their text: nothing is
510+
rewritten.
511+
456512
## Recipe — refuse overlapping time ranges
457513

458514
Leave and overtime requests share one rule: two live records of the same owner

‎content/docs/references/api/protocol.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1876,7 +1876,7 @@ The published metadata item body, opaque by ruling (1C). Shape is the item's own
18761876
| **reports** | `Record<string, { label?: string; description?: string; blocks?: Record<string, object> }>` | optional | Report translations keyed by report name |
18771877
| **pages** | `Record<string, { label?: string; description?: string; title?: string; subtitle?: string; … }>` | optional | Page translations keyed by page name |
18781878
| **flows** | `Record<string, { label?: string; successMessage?: string; errorMessage?: string; screens?: Record<string, object>; … }>` | optional | Screen-flow translations keyed by flow name |
1879-
| **hooks** | `Record<string, { refusals?: Record<string, object> }>` | optional | Hook translations keyed by hook name |
1879+
| **hooks** | `Record<string, { refusals?: Record<string, object>; texts?: Record<string, object> }>` | optional | Hook translations keyed by hook name |
18801880
| **positions** | `Record<string, { label?: string; description?: string }>` | optional | Position translations keyed by position name |
18811881
| **permissions** | `Record<string, { label?: string; description?: string }>` | optional | Permission-set translations keyed by permission-set name |
18821882
| **books** | `Record<string, { label?: string; description?: string; groups?: Record<string, object> }>` | optional | Doc-book translations keyed by book name |

‎content/docs/references/data/hook.mdx‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Hook schema — Data Protocol property reference
33
navTitle: Hook
4-
description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent, HookRefusal — each property with its type, default and a TypeScript example."
4+
description: "Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent and 2 more — each property with its type, default and a TypeScript example."
55
---
66

77
{/* ⚠️ 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,
1313
## TypeScript Usage
1414

1515
```typescript
16-
import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema } from '@objectstack/spec/data';
17-
import type { Hook, HookContext, HookRefusal } from '@objectstack/spec/data';
16+
import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema, HookTextSchema } from '@objectstack/spec/data';
17+
import type { Hook, HookContext, HookRefusal, HookText } from '@objectstack/spec/data';
1818

1919
// Validate data
2020
const result = HookSchema.parse(data);
@@ -43,6 +43,7 @@ const result = HookSchema.parse(data);
4343
| **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. |
4444
| **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 |
4545
| **refusals** | `Record<string, { message: string; status?: integer; reasons?: Record<string, object>; 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.`<hook>`.refusals.`<CODE>`.message, or ….`<CODE>`.reasons.`<REASON>`.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 |
46+
| **texts** | `Record<string, { message: string; params?: string[] }>` | 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.`<hook>`.texts.`<key>`.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 |
4647
| **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. |
4748
| **_lock** | `Enum<'none' \| 'no-overlay' \| 'no-delete' \| 'full'>` | optional | Item-level lock — controls overlay & delete (ADR-0010). |
4849
| **_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
8990
| **reasons** | `Record<string, { message: string }>` | 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 |
9091
| **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 |
9192

93+
### Nested Shape: `Hook.texts[string]`
94+
95+
| Property | Type | Required | Description |
96+
| :--- | :--- | :--- | :--- |
97+
| **message** | `string` | ✅ | The sentence the hook writes into a record — in the source locale, translated whole through hooks.`<hook>`.texts.`<key>`.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 |
98+
| **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 |
99+
92100

93101
---
94102

@@ -201,3 +209,15 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities
201209

202210
---
203211

212+
## HookText
213+
214+
### Properties
215+
216+
| Property | Type | Required | Description |
217+
| :--- | :--- | :--- | :--- |
218+
| **message** | `string` | ✅ | The sentence the hook writes into a record — in the source locale, translated whole through hooks.`<hook>`.texts.`<key>`.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 |
219+
| **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 |
220+
221+
222+
---
223+

0 commit comments

Comments
 (0)