From f8a88d3462ab88094a6223cf5f02a889cc26c3b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:43:42 +0000 Subject: [PATCH 01/17] feat(spec): offer the hook texts row in the Studio hook form The hook form gains a key-only record row for HookSchema.texts beside refusals, with message and params, and the reconciliation ledger drops its hook/texts omit row. Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook.form.ts | 19 +++++++++++++++++-- .../metadata-form-zod-reconciliation.test.ts | 11 ----------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/packages/spec/src/data/hook.form.ts b/packages/spec/src/data/hook.form.ts index 6d2932ce0cf..3b839a76f5c 100644 --- a/packages/spec/src/data/hook.form.ts +++ b/packages/spec/src/data/hook.form.ts @@ -8,8 +8,9 @@ import { defineForm } from '../ui/view.zod'; * Hooks intercept the data lifecycle. The body field is a composite * (`{ language, source, capabilities?, timeoutMs?, memoryMb? }`) whose * `source` renders in a Monaco code editor with language-appropriate - * syntax highlighting. The hook's refusal catalogue (`refusals`) sits beside it: - * a js body or a handler may declare one, an expression body may not. + * syntax highlighting. The hook's refusal catalogue (`refusals`) and its + * declared texts (`texts`) sit beside it: a js body or a handler may declare + * them, an expression body may not. */ export const hookForm = defineForm({ schemaId: 'hook', @@ -73,6 +74,20 @@ export const hookForm = defineForm({ { field: 'params', type: 'tags', helpText: 'Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text' }, ], }, + // The declared texts are the same record shape as the refusal + // catalogue — keyed by the snake_case key the code asks for, an entry + // `{ message, params? }` with no member that echoes its key — so the + // row takes the same key-only record control. + { + field: 'texts', + type: 'record', + widget: 'key-only-record', + helpText: "Sentences the hook writes into records, keyed by the snake_case key its code asks for with ctx.text (e.g. follow_up_subject). The hook gets the declared message in the organization's language, translated, with the declared message as the fallback. For a JavaScript (L2) body or a handler; refused on an expression body", + fields: [ + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the hook writes when its code asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param' }, + { field: 'params', type: 'tags', helpText: 'Names the sentence may fill (e.g. lead): the code asks for ctx.text(key, { lead }), and a {{ lead }} hole renders it. Absent: the sentence is plain text' }, + ], + }, ], }, { 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 02bd67dffc3..88456f34fd4 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -464,17 +464,6 @@ 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", - }, // #34273 — an action's refusal catalogue lands in the action's source // first, as a hook's declared texts did (#34374). The Studio row (a // key-only record, with its help text in the eleven metadata-forms From 0cfc18e8d216fd244f769c1175f82f325c28b593 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:47:47 +0000 Subject: [PATCH 02/17] feat(spec): HookContext declares ctx.text A typed hook handler can call ctx.text(key, params) against HookContext: the member is declared the way api and notice are (z.unknown at parse, a static cast for the type), with the signature the runtime binds, and the named HookTextReader type beside HookNoticeSetter. Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .../spec/src/data/hook-context-text.test.ts | 78 +++++++++++++++++++ packages/spec/src/data/hook.zod.ts | 34 ++++++++ 2 files changed, 112 insertions(+) create mode 100644 packages/spec/src/data/hook-context-text.test.ts diff --git a/packages/spec/src/data/hook-context-text.test.ts b/packages/spec/src/data/hook-context-text.test.ts new file mode 100644 index 00000000000..2fe4f41bc96 --- /dev/null +++ b/packages/spec/src/data/hook-context-text.test.ts @@ -0,0 +1,78 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35197] `HookContext.text` — the published type of the `ctx.text(key, + * params?)` call a hook asks for one of its declared `texts` with. + * + * The runtime binds it on every path a hook runs on + * (`packages/runtime/src/sandbox/hook-text.ts`, `HookTextSurface`), so a typed + * handler must be able to call it against `HookContext` without a local type. + * Pinned from both sides: + * + * 1. the type: `HookContext['text']` is exactly an optional + * `(key: string, params?: Record) => Promise`, + * the signature the runtime injects, and a wrong call shape is a type + * error. The `@ts-expect-error` lines are real checks: `tsconfig.test.json` + * compiles this layer (`pnpm --filter @objectstack/spec check:test-typecheck`). + * 2. the parse: `HookContextSchema` (deliberately non-strict, which strips a + * key it does not declare) keeps the bound function. + */ + +import { describe, expect, it } from 'vitest'; + +import { HookContextSchema, type HookContext, type HookTextReader } from './hook.zod'; + +/** `true` only when every `A` is a usable `B`. */ +type Assignable = [A] extends [B] ? true : false; + +type RuntimeTextSurface = (key: string, params?: Record) => Promise; + +describe('HookContext.text — the declared-text call a typed handler makes', () => { + it('declares the signature the runtime injects, optional like api and notice', () => { + const declaredIsRuntime: Assignable, RuntimeTextSurface> = true; + const runtimeIsDeclared: Assignable> = true; + const namedIsMember: Assignable> = true; + const optional: Assignable = true; + expect([declaredIsRuntime, runtimeIsDeclared, namedIsMember, optional]).toEqual([true, true, true, true]); + }); + + it('a typed handler calls it with a key and params and gets a string', async () => { + const asked: Array<[string, Record | undefined]> = []; + const handler = async (ctx: HookContext): Promise => { + const lead = 'Ada'; + return (await ctx.text?.('follow_up_subject', { lead })) ?? ''; + }; + const ctx: HookContext = { + object: 'crm_lead', + event: 'afterInsert', + input: {}, + text: async (key, params) => { + asked.push([key, params]); + return `Follow up with qualified lead: ${String(params?.lead)}`; + }, + }; + await expect(handler(ctx)).resolves.toBe('Follow up with qualified lead: Ada'); + expect(asked).toEqual([['follow_up_subject', { lead: 'Ada' }]]); + }); + + it('a wrong call shape is a type error', () => { + const text: HookTextReader = async (key) => key; + // @ts-expect-error the key is the snake_case string a hook declares, never a number + void text(42); + // @ts-expect-error params is a name → value record, never a positional list + void text('follow_up_subject', ['Ada']); + const answer = async (): Promise => { + // @ts-expect-error the call resolves to the sentence, a string + const n: number = await text('follow_up_subject'); + void n; + }; + expect(typeof answer).toBe('function'); + }); + + it('the parse keeps the bound function instead of stripping it', () => { + const text: HookTextReader = async () => 'sentence'; + const parsed = HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {}, text }); + expect(parsed.text).toBe(text); + expect('text' in HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {} })).toBe(false); + }); +}); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index f8275109575..49b2f0174c7 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -1927,6 +1927,34 @@ export const HookContextSchema = lazySchema(() => z.object({ + 'by the engine on every insert/update dispatch (a no-op when nothing listens); absent on find/delete', ), + /** + * Declared Text (#34374, ruling 6913660232 parameter 7) + * + * `await ctx.text('follow_up_subject', { lead })` answers one of the hook's + * declared `texts` (see `HookSchema.texts`) in the ORGANIZATION's language, + * translated through `hooks..texts..message`, the declared + * `message` as the fallback, its `{{ }}` holes filled from `params`. A key + * the hook does not declare rejects the call, and so does a Localization + * setting that cannot be read. + * + * The runtime binds it on every path a hook runs on — a sandboxed `js` body + * and an in-process `handler` (`buildHookTextSurface`). The save-time check + * reads the literal spelling `ctx.text('key'`, so a key asked for through + * an alias or a computed name is only judged when the hook runs. + * + * Runtime-only, like {@link api} and {@link notice}: a live function, so the + * RUNTIME schema is `z.unknown()` (JSON Schema `{}`) and the type is a static + * cast. Optional for the same reason they are: a context parsed without the + * runtime carries none. + */ + text: (z.unknown().optional() as unknown as z.ZodOptional>) + .describe( + 'Answer one of the hook\'s declared texts: `await ctx.text(KEY, params?)` returns the sentence in the ' + + 'organization\'s language (translated through hooks..texts..message, the declared message as the ' + + 'fallback, holes filled from params). Bound by the runtime on every path a hook runs on; a key the hook does ' + + 'not declare rejects the call', + ), + /** * Current User Info * Convenience shortcut for session.userId + additional user metadata. @@ -1963,6 +1991,12 @@ export type HookEventType = z.input; * a non-empty string. */ export type HookNoticeSetter = (message: string) => void; +/** + * The function a hook calls as `ctx.text(key, params?)` (#34374) — see + * `HookContext.text` and `HookSchema.texts`. Resolves to the declared sentence + * in the organization's language; rejects a key the hook does not declare. + */ +export type HookTextReader = (key: string, params?: Record) => Promise; export type HookContext = z.input; /** * The engine's dispatch marker (#6966) — see `HookContext.dispatch`. Named so From 0d0744ce1e8b49633d76d2f70b9ddf6d7353d686 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:55:12 +0000 Subject: [PATCH 03/17] feat(platform-objects): the hook texts row in the eleven metadata-forms packs en regenerated from the form source; the ten translated packs carry hand-written translations following each pack's refusals wording. Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .../apps/translations/ar.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/de.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/en.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/es-ES.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/fr.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/fr.source-hashes.generated.ts | 1 + .../translations/ja-JP.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/ko.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/pt-BR.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/ru.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/zh-CN.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/zh-Hant.metadata-forms.generated.ts | 12 ++++++++++++ 12 files changed, 133 insertions(+) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 63f7f7fb176..16f18cf9f14 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const arMetadataForms: NonNullable = { label: "المعاملات", helpText: "الأسماء التي يمكن للجمل ملؤها (مثل state): يرمي المتن { code, params: { state } } ويعرض العنصر النائب {{ state }} قيمتها. عند الغياب: الجمل نص عادي" }, + texts: { + label: "النصوص", + helpText: "الجمل التي يكتبها الخطاف في السجلات، مفهرسة بالمفتاح بصيغة snake_case الذي تطلبه شيفرته عبر ctx.text (مثل follow_up_subject). يتلقى الخطاف الرسالة المُعلنة بلغة المؤسسة، مترجمة، مع الرسالة المُعلنة بديلًا عند غياب الترجمة. لمتن JavaScript ‏(L2) أو معالج؛ ويُرفض في متن التعبير" + }, + "texts.message": { + label: "الرسالة", + helpText: "الجملة التي يكتبها الخطاف عندما تطلب شيفرته هذا المفتاح. نص عادي، ما لم يُعلن الإدخال params: عندها يملأ العنصر النائب {{ name }} معاملًا مُعلنًا" + }, + "texts.params": { + label: "المعاملات", + helpText: "الأسماء التي يمكن للجملة ملؤها (مثل lead): تطلب الشيفرة ctx.text(key, { lead }) ويعرض العنصر النائب {{ lead }} قيمتها. عند الغياب: الجملة نص عادي" + }, handler: { label: "المعالج", helpText: "اسم دالة المعالج (مُهمَل — يُفضَّل `body`)" diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 8fc7676271b..720eb0354bf 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const deMetadataForms: NonNullable = { label: "Parameter", helpText: "Namen, die die Sätze füllen dürfen (z. B. state): Der Rumpf wirft { code, params: { state } }, und ein Platzhalter {{ state }} zeigt den Wert. Fehlt er: Die Sätze sind einfacher Text" }, + texts: { + label: "Texte", + helpText: "Sätze, die der Hook in Datensätze schreibt, nach dem snake_case-Schlüssel, den sein Code mit ctx.text anfragt (z. B. follow_up_subject). Der Hook erhält die deklarierte Meldung in der Sprache der Organisation, übersetzt, mit der deklarierten Meldung als Rückfall. Für einen JavaScript-Rumpf (L2) oder einen Handler; bei einem Ausdrucksrumpf abgelehnt" + }, + "texts.message": { + label: "Meldung", + helpText: "Der Satz, den der Hook schreibt, wenn sein Code diesen Schlüssel anfragt. Einfacher Text, außer der Eintrag deklariert params: dann füllt ein Platzhalter {{ name }} einen deklarierten Parameter" + }, + "texts.params": { + label: "Parameter", + helpText: "Namen, die der Satz füllen darf (z. B. lead): Der Code fragt ctx.text(key, { lead }) an, und ein Platzhalter {{ lead }} zeigt den Wert. Fehlt er: Der Satz ist einfacher Text" + }, handler: { label: "Handler", helpText: "Name der Handler-Funktion (veraltet – besser `body`)" diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 328473cddb0..c4e81aac640 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const enMetadataForms: NonNullable = { label: "Params", helpText: "Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text" }, + texts: { + label: "Texts", + helpText: "Sentences the hook writes into records, keyed by the snake_case key its code asks for with ctx.text (e.g. follow_up_subject). The hook gets the declared message in the organization's language, translated, with the declared message as the fallback. For a JavaScript (L2) body or a handler; refused on an expression body" + }, + "texts.message": { + label: "Message", + helpText: "The sentence the hook writes when its code asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param" + }, + "texts.params": { + label: "Params", + helpText: "Names the sentence may fill (e.g. lead): the code asks for ctx.text(key, { lead }), and a {{ lead }} hole renders it. Absent: the sentence is plain text" + }, handler: { label: "Handler", helpText: "Handler function name (deprecated — prefer `body`)" diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 8109d542dc4..0666f3ea388 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const esESMetadataForms: NonNullable = label: "Parámetros", helpText: "Nombres que las frases pueden rellenar (p. ej. state): el cuerpo lanza { code, params: { state } } y un marcador {{ state }} muestra su valor. Si se omite: las frases son texto plano" }, + texts: { + label: "Textos", + helpText: "Frases que el gancho escribe en los registros, indexadas por la clave snake_case que su código pide con ctx.text (p. ej. follow_up_subject). El gancho recibe el mensaje declarado en el idioma de la organización, traducido, con el mensaje declarado como respaldo. Para un cuerpo JavaScript (L2) o un manejador; se rechaza en un cuerpo de expresión" + }, + "texts.message": { + label: "Mensaje", + helpText: "La frase que escribe el gancho cuando su código pide esta clave. Texto plano, salvo que la entrada declare params: entonces un marcador {{ name }} se rellena con un parámetro declarado" + }, + "texts.params": { + label: "Parámetros", + helpText: "Nombres que la frase puede rellenar (p. ej. lead): el código pide ctx.text(key, { lead }) y un marcador {{ lead }} muestra su valor. Si se omite: la frase es texto plano" + }, handler: { label: "Manejador", helpText: "Nombre de función manejadora (obsoleto — preferir `body`)" diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 338d452a1af..2e47bd7c82d 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const frMetadataForms: NonNullable = { label: "Paramètres", helpText: "Les noms que les phrases peuvent remplir (par ex. state) : le corps lève { code, params: { state } }, et un espace réservé {{ state }} en affiche la valeur. Absent : les phrases sont du texte brut" }, + texts: { + label: "Textes", + helpText: "Les phrases que le hook écrit dans les enregistrements, indexées par la clé snake_case que son code demande avec ctx.text (par ex. follow_up_subject). Le hook reçoit le message déclaré dans la langue de l’organisation, traduit, avec le message déclaré comme repli. Pour un corps JavaScript (L2) ou un gestionnaire ; refusé sur un corps expression" + }, + "texts.message": { + label: "Message", + helpText: "La phrase que le hook écrit lorsque son code demande cette clé. Texte brut, sauf si l’entrée déclare des params : un espace réservé {{ name }} reçoit alors un paramètre déclaré" + }, + "texts.params": { + label: "Paramètres", + helpText: "Les noms que la phrase peut remplir (par ex. lead) : le code demande ctx.text(key, { lead }), et un espace réservé {{ lead }} en affiche la valeur. Absent : la phrase est du texte brut" + }, handler: { label: "Gestionnaire", helpText: "Nom de la fonction de gestion (obsolète — préférez `body`)" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 052e7f2ba4d..88c0f192be0 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -66,6 +66,7 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.hook.fields.description.label": "779a4342c8eb6707", "metadataForms.hook.fields.refusals.message.label": "2af15199795c25b9", "metadataForms.hook.fields.refusals.reasons.message.label": "2af15199795c25b9", + "metadataForms.hook.fields.texts.message.label": "2af15199795c25b9", "metadataForms.hook.label": "248bb1cdc692252d", "metadataForms.object.fields.description.label": "779a4342c8eb6707", "metadataForms.object.fields.fields.description.label": "779a4342c8eb6707", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 3f6cd992f09..63371ee0c03 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const jaJPMetadataForms: NonNullable = label: "パラメーター", helpText: "文に埋め込める名前(例: state)。本体が { code, params: { state } } をスローすると、{{ state }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" }, + texts: { + label: "テキスト", + helpText: "フックがレコードに書き込む文。コードが ctx.text で要求する snake_case のキー(例: follow_up_subject)をキーとします。フックには宣言したメッセージが組織の言語に翻訳されて返り、翻訳がない場合は宣言したメッセージが返ります。JavaScript(L2)本体またはハンドラーで使用可能。expression 本体では拒否されます" + }, + "texts.message": { + label: "メッセージ", + helpText: "コードがこのキーを要求したときにフックが書き込む文。プレーンテキスト。ただしエントリが params を宣言している場合、{{ name }} プレースホルダーに宣言済みのパラメーターが入ります" + }, + "texts.params": { + label: "パラメーター", + helpText: "文に埋め込める名前(例: lead)。コードが ctx.text(key, { lead }) を要求すると、{{ lead }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" + }, handler: { label: "ハンドラー", helpText: "ハンドラー関数名(非推奨 — `body` を推奨)" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 83b6a3e1992..119caa20a0b 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const koMetadataForms: NonNullable = { label: "매개변수", helpText: "문장에 채울 수 있는 이름(예: state)입니다. 본문이 { code, params: { state } }를 던지면 {{ state }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" }, + texts: { + label: "텍스트", + helpText: "훅이 레코드에 쓰는 문장으로, 코드가 ctx.text로 요청하는 snake_case 키(예: follow_up_subject)를 키로 합니다. 훅은 선언된 메시지를 조직의 언어로 번역해 받으며, 번역이 없으면 선언된 메시지를 받습니다. JavaScript(L2) 본문 또는 핸들러용이며, expression 본문에서는 거부됩니다" + }, + "texts.message": { + label: "메시지", + helpText: "코드가 이 키를 요청할 때 훅이 쓰는 문장입니다. 일반 텍스트이며, 항목이 params를 선언하면 {{ name }} 자리 표시자에 선언된 매개변수가 채워집니다" + }, + "texts.params": { + label: "매개변수", + helpText: "문장에 채울 수 있는 이름(예: lead)입니다. 코드가 ctx.text(key, { lead })를 요청하면 {{ lead }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" + }, handler: { label: "핸들러", helpText: "핸들러 함수 이름(사용 중단, `body` 권장)" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 364cb7ba667..dea2e09a05d 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const ptBRMetadataForms: NonNullable = label: "Parâmetros", helpText: "Nomes que as frases podem preencher (por exemplo state): o corpo lança { code, params: { state } } e um marcador {{ state }} mostra o valor. Ausente: as frases são texto simples" }, + texts: { + label: "Textos", + helpText: "Frases que o hook escreve nos registros, indexadas pela chave snake_case que o código dele pede com ctx.text (por exemplo follow_up_subject). O hook recebe a mensagem declarada no idioma da organização, traduzida, com a mensagem declarada como alternativa. Para um corpo JavaScript (L2) ou um handler; recusado em um corpo de expressão" + }, + "texts.message": { + label: "Mensagem", + helpText: "A frase que o hook escreve quando o código dele pede esta chave. Texto simples, a menos que a entrada declare params: então um marcador {{ name }} é preenchido com um parâmetro declarado" + }, + "texts.params": { + label: "Parâmetros", + helpText: "Nomes que a frase pode preencher (por exemplo lead): o código pede ctx.text(key, { lead }) e um marcador {{ lead }} mostra o valor. Ausente: a frase é texto simples" + }, handler: { label: "Handler", helpText: "Nome da função handler (obsoleto — prefira `body`)" diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index ef3ff534857..0397923e065 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const ruMetadataForms: NonNullable = { label: "Параметры", helpText: "Имена, которые могут заполнять фразы (например, state): тело выбрасывает { code, params: { state } }, и заполнитель {{ state }} показывает значение. Если отсутствует: фразы — простой текст" }, + texts: { + label: "Тексты", + helpText: "Фразы, которые хук записывает в записи, с ключами в snake_case, которые его код запрашивает через ctx.text (например, follow_up_subject). Хук получает объявленное сообщение в переводе на язык организации, а без перевода — само объявленное сообщение. Для тела JavaScript (L2) или обработчика; для тела-выражения отклоняется" + }, + "texts.message": { + label: "Сообщение", + helpText: "Фраза, которую хук записывает, когда его код запрашивает этот ключ. Простой текст, если запись не объявляет params: тогда заполнитель {{ name }} подставляет объявленный параметр" + }, + "texts.params": { + label: "Параметры", + helpText: "Имена, которые может заполнять фраза (например, lead): код запрашивает ctx.text(key, { lead }), и заполнитель {{ lead }} показывает значение. Если отсутствует: фраза — простой текст" + }, handler: { label: "Обработчик", helpText: "Имя функции-обработчика (устарело — используйте `body`)" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 6305508ab42..6e820738da2 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const zhCNMetadataForms: NonNullable = label: "参数", helpText: "句子可填入的名称(例如 state):正文抛出 { code, params: { state } },{{ state }} 占位符即显示该值。不填:句子为纯文本" }, + texts: { + label: "文本", + helpText: "钩子写入记录的句子,以其代码通过 ctx.text 请求的 snake_case 键为键(例如 follow_up_subject)。钩子得到按组织语言翻译的声明句子,无翻译时回退为声明的句子。适用于 JavaScript(L2)正文或处理器;表达式正文声明会被拒绝" + }, + "texts.message": { + label: "句子", + helpText: "代码请求此键时钩子写入的句子。纯文本;若该条目声明了参数,则 {{ name }} 占位符填入一个已声明的参数" + }, + "texts.params": { + label: "参数", + helpText: "句子可填入的名称(例如 lead):代码请求 ctx.text(key, { lead }),{{ lead }} 占位符即显示该值。不填:句子为纯文本" + }, handler: { label: "处理器", helpText: "处理器函数名(已废弃——建议使用 body)" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 8672e220bf2..ad8ce45755d 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -989,6 +989,18 @@ export const zhHantMetadataForms: NonNullable label: "參數", helpText: "句子可填入的名稱(例如 state):內文丟擲 { code, params: { state } },{{ state }} 預留位置即顯示該值。不填:句子為純文字" }, + texts: { + label: "文字", + helpText: "掛鉤寫入記錄的句子,以其程式碼透過 ctx.text 請求的 snake_case 鍵為鍵(例如 follow_up_subject)。掛鉤取得依組織語言翻譯的宣告句子,無翻譯時退回宣告的句子。適用於 JavaScript(L2)內文或處理器;運算式內文宣告會被拒絕" + }, + "texts.message": { + label: "句子", + helpText: "程式碼請求此鍵時掛鉤寫入的句子。純文字;若該條目宣告了參數,則 {{ name }} 預留位置填入一個已宣告的參數" + }, + "texts.params": { + label: "參數", + helpText: "句子可填入的名稱(例如 lead):程式碼請求 ctx.text(key, { lead }),{{ lead }} 預留位置即顯示該值。不填:句子為純文字" + }, handler: { label: "處理器", helpText: "處理器函式名(已廢棄——建議使用 body)" From 5fb220661625850ac4a45b2ad0c781a5fa4b6bcf Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 11:57:25 +0000 Subject: [PATCH 04/17] test(spec): a parsed hook context needs its engine reference Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook-context-text.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/spec/src/data/hook-context-text.test.ts b/packages/spec/src/data/hook-context-text.test.ts index 2fe4f41bc96..8a55448892d 100644 --- a/packages/spec/src/data/hook-context-text.test.ts +++ b/packages/spec/src/data/hook-context-text.test.ts @@ -71,8 +71,8 @@ describe('HookContext.text — the declared-text call a typed handler makes', () it('the parse keeps the bound function instead of stripping it', () => { const text: HookTextReader = async () => 'sentence'; - const parsed = HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {}, text }); - expect(parsed.text).toBe(text); - expect('text' in HookContextSchema.parse({ object: 'crm_lead', event: 'afterInsert', input: {} })).toBe(false); + const bare = { object: 'crm_lead', event: 'afterInsert', input: {}, ql: {} }; + expect(HookContextSchema.parse({ ...bare, text }).text).toBe(text); + expect('text' in HookContextSchema.parse(bare)).toBe(false); }); }); From 13feefb0de0d4524e75cf117155ba325ae685291 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:06:04 +0000 Subject: [PATCH 05/17] test(spec): the typed hook context literal carries its engine reference Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook-context-text.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spec/src/data/hook-context-text.test.ts b/packages/spec/src/data/hook-context-text.test.ts index 8a55448892d..07f5f0b41d1 100644 --- a/packages/spec/src/data/hook-context-text.test.ts +++ b/packages/spec/src/data/hook-context-text.test.ts @@ -46,6 +46,7 @@ describe('HookContext.text — the declared-text call a typed handler makes', () object: 'crm_lead', event: 'afterInsert', input: {}, + ql: {}, text: async (key, params) => { asked.push([key, params]); return `Follow up with qualified lead: ${String(params?.lead)}`; From 772b1c3a07651c131137a4d66d80c304e7c50e11 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:06:50 +0000 Subject: [PATCH 06/17] chore(spec): regenerate the artifacts HookContext.text moves, add the changeset Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .changeset/34575-hook-texts-studio-row.md | 12 ++++++++++++ content/docs/references/data/hook.mdx | 1 + packages/spec/api-surface/data.json | 1 + packages/spec/authorable-surface/data.json | 1 + packages/spec/export-origins/data.json | 1 + 5 files changed, 16 insertions(+) create mode 100644 .changeset/34575-hook-texts-studio-row.md diff --git a/.changeset/34575-hook-texts-studio-row.md b/.changeset/34575-hook-texts-studio-row.md new file mode 100644 index 00000000000..eb656062b83 --- /dev/null +++ b/.changeset/34575-hook-texts-studio-row.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +--- + +feat(spec): the Studio hook form offers a hook's declared `texts`, and `HookContext` declares `ctx.text` + +Clause-②: yes +Metadata-protocol: none + +- **Studio hook form.** `hookForm` gains a `texts` row beside `refusals`: a key-only record keyed by the snake_case key the hook's code asks for with `ctx.text`, each entry editing its `message` and `params`. An author editing a hook in the Studio can now write the `texts` the schema has accepted since 18.6.0, instead of going through the metadata API or the package source. The row's label and help text ship in all eleven metadata-forms locale packs of `@objectstack/platform-objects`. Nothing about what a hook may declare changes. +- **`HookContext.text`.** `HookContext` now declares `text?: (key: string, params?: Record) => Promise` (named `HookTextReader`), the call the runtime already binds on every path a hook runs on, declared the way `api` and `notice` are: `z.unknown()` at parse, a static cast for the type, optional because a context parsed without the runtime carries none. A typed handler no longer needs a local type to call `ctx.text`. `HookContextSchema.parse` now keeps a bound `text` instead of stripping it. \ No newline at end of file diff --git a/content/docs/references/data/hook.mdx b/content/docs/references/data/hook.mdx index 5dacd667e99..4cb224fc03a 100644 --- a/content/docs/references/data/hook.mdx +++ b/content/docs/references/data/hook.mdx @@ -122,6 +122,7 @@ L2 sandboxed JS body — runs inside an isolated VM with declared capabilities | **ql** | `any` | ✅ | ObjectQL Engine Reference | | **api** | `any` | optional | Cross-object data access (IScopedContext — `object(name)` + `transaction(cb)`) | | **notice** | `any` | optional | Tell the person who made THIS insert/update what the save set in motion: `ctx.notice(message)` hands one non-empty string to the write's own `onNotice` listener, answered as the create/update `notice`. Bound by the engine on every insert/update dispatch (a no-op when nothing listens); absent on find/delete | +| **text** | `any` | optional | Answer one of the hook's declared texts: `await ctx.text(KEY, params?)` returns the sentence in the organization's language (translated through hooks.``.texts.``.message, the declared message as the fallback, holes filled from params). Bound by the runtime on every path a hook runs on; a key the hook does not declare rejects the call | | **user** | `{ id?: string; name?: string; email?: string; organizationId?: string }` | optional | Current user info shortcut | ### Nested Shape: `HookContext.dispatch` diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index d69183d4b25..ba883cf2404 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -419,6 +419,7 @@ "HookRefusalSchema (const)", "HookSchema (const)", "HookText (type)", + "HookTextReader (type)", "HookTextSchema (const)", "HookUpdateDoc (type)", "HookUpdateOptions (type)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 73e8740e18e..b26e8b55698 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -491,6 +491,7 @@ "data/HookContext:result", "data/HookContext:session", "data/HookContext:submitted", + "data/HookContext:text", "data/HookContext:transaction", "data/HookContext:user", "data/HookRefusal:message", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index aabb17a6b31..6ce59e36a38 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -409,6 +409,7 @@ "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookText": "src/data/hook.zod.ts#HookText (type)", + "HookTextReader": "src/data/hook.zod.ts#HookTextReader (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)", From 3d0f92b1960d94707a78ac1f2d6d94281077f1d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:13:05 +0000 Subject: [PATCH 07/17] test(platform-objects): the hook form's texts record joins the enumerated children Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .../translations/action-body-panel-echo-decisions.test.ts | 8 ++++++-- .../hook-execution-panel-echo-decisions.test.ts | 5 +++-- .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts index 28836024b59..aeabac85761 100644 --- a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts @@ -705,9 +705,11 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, // 9 since #26835: the hook form offers the `refusals` record, whose two // entry fields (`message`, `status`) are enumerated the same way. 12 since // #33657: the entry also offers `reasons` (a record of `{ message }`) and - // `params`, three more enumerated children. + // `params`, three more enumerated children. 14 since #34575: the form + // offers the `texts` record, whose entry fields (`message`, `params`) are + // enumerated the same way. expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0); - expect(HOOK_ENUMERATED.skipped.length).toBe(12); + expect(HOOK_ENUMERATED.skipped.length).toBe(14); for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries'); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs'); @@ -716,6 +718,8 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons'); expect(HOOK_ENUMERATED.skipped).toContain('refusals.reasons.message'); expect(HOOK_ENUMERATED.skipped).toContain('refusals.params'); + expect(HOOK_ENUMERATED.skipped).toContain('texts.message'); + expect(HOOK_ENUMERATED.skipped).toContain('texts.params'); // // ⇒ one composite, two forms, two different greens: a lit control that // passes on a sibling repeater, and a dark control that is right about diff --git a/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts index a16a1620b59..7367c3de712 100644 --- a/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/hook-execution-panel-echo-decisions.test.ts @@ -785,9 +785,10 @@ describe('#19403 round 6 — the composite blind spot, hook side, CLOSED', () => // round 5 wrote down. Seven children sit enumerated and outside it — 9 // since #26835, when the `refusals` record's `message` / `status` joined, // and 12 since #33657, when its `reasons` (with `reasons.message`) and - // `params` joined. + // `params` joined, and 14 since #34575, when the `texts` record's + // `message` / `params` joined. expect(HOOK_ENUMERATED.covered.length, 'hookForm enumerates no repeater row properties').toBe(0); - expect(HOOK_ENUMERATED.skipped.length).toBe(12); + expect(HOOK_ENUMERATED.skipped.length).toBe(14); for (const child of SHARED_BODY_CHILDREN) expect(HOOK_ENUMERATED.skipped).toContain(`body.${child}`); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.maxRetries'); expect(HOOK_ENUMERATED.skipped).toContain('retryPolicy.backoffMs'); diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index b6691bf30e5..f5cb0f238c8 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1286,7 +1286,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 741 since #33657: the hook form's refusal entry offers `reasons` (with // its `message`) and `params` — three row labels, authored in all three // locales. - expect(translated.length, `${locale} positive control`).toBe(741); + // 744 since #34575: the hook form offers the `texts` record and its + // `message` / `params` entry fields — three row labels, authored in all + // three locales. + expect(translated.length, `${locale} positive control`).toBe(744); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From b702af98f78e55e7ef47fd2b7ecef10bf97ca69e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 12:52:41 +0000 Subject: [PATCH 08/17] chore(changeset): HookContext.text is an added protocol member, spec at minor Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .changeset/34575-hook-texts-studio-row.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.changeset/34575-hook-texts-studio-row.md b/.changeset/34575-hook-texts-studio-row.md index eb656062b83..fb5cd505b22 100644 --- a/.changeset/34575-hook-texts-studio-row.md +++ b/.changeset/34575-hook-texts-studio-row.md @@ -1,12 +1,14 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/platform-objects': patch --- feat(spec): the Studio hook form offers a hook's declared `texts`, and `HookContext` declares `ctx.text` -Clause-②: yes -Metadata-protocol: none +Clause-②: yes (widening) +Metadata-protocol: added + +The added key is the type member `HookContext.text` (the authorable-surface record lists `HookContext` members); nothing a stack writes changes. - **Studio hook form.** `hookForm` gains a `texts` row beside `refusals`: a key-only record keyed by the snake_case key the hook's code asks for with `ctx.text`, each entry editing its `message` and `params`. An author editing a hook in the Studio can now write the `texts` the schema has accepted since 18.6.0, instead of going through the metadata API or the package source. The row's label and help text ship in all eleven metadata-forms locale packs of `@objectstack/platform-objects`. Nothing about what a hook may declare changes. - **`HookContext.text`.** `HookContext` now declares `text?: (key: string, params?: Record) => Promise` (named `HookTextReader`), the call the runtime already binds on every path a hook runs on, declared the way `api` and `notice` are: `z.unknown()` at parse, a static cast for the type, optional because a context parsed without the runtime carries none. A typed handler no longer needs a local type to call `ctx.text`. `HookContextSchema.parse` now keeps a bound `text` instead of stripping it. \ No newline at end of file From ab850bfb0ab2a42a8232bf72d8d76f52ff1d5f6e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:11:55 +0000 Subject: [PATCH 09/17] feat(spec): the Studio action form offers the action's declared texts The action form gains a texts row beside the script body: a key-only record keyed by the snake_case key the body asks for with ctx.text, each entry editing message and params, gated like the body. The action/texts omit row is retired from the reconciliation ledger. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC --- .../metadata-form-declared-rows.pin.test.ts | 54 +++++++++++++++++++ .../metadata-form-zod-reconciliation.test.ts | 12 ----- packages/spec/src/ui/action.form.ts | 17 ++++++ 3 files changed, 71 insertions(+), 12 deletions(-) diff --git a/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts b/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts index e806b0555e5..ecb18c7d157 100644 --- a/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts +++ b/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts @@ -43,6 +43,7 @@ import { describe, it, expect } from 'vitest'; import { METADATA_FORM_REGISTRY } from './metadata-form-registry'; +import { ActionTextSchema } from '../ui/action.zod'; type FormEntry = { field?: string; @@ -252,3 +253,56 @@ describe('hook.condition declares the CEL predicate language it edits', () => { expect(row.language).toBe('expression'); }); }); + +/** + * **The action form edits the action's declared sentences beside its script + * body** (ruling 6913660232, parameter 7: an action declares its sentences). + * + * `ActionSchema.texts` is a record keyed by the snake_case key the body asks + * for with `ctx.text`, each entry `{ message, params? }` with no member that + * echoes its key, so its row is the hook form's: a `key-only-record`, which + * adds, renames and removes keys and never writes the key into the entry. The + * reconciliation gate proves the key and its entry keys are offered somewhere + * on the form; it does not read the control, the gate or where the row sits, + * so this pin keeps all three. + */ +describe('action.texts is a key-only record beside the script body', () => { + type Section = { label?: string; fields?: FormEntry[] }; + const behaviorRows = () => + ((((METADATA_FORM_REGISTRY.action as any)?.sections ?? []) as Section[]).find((s) => s.label === 'Behavior') + ?.fields ?? []) as FormEntry[]; + const indexOf = (key: string) => behaviorRows().findIndex((r) => r?.field === key); + /** A row's entry controls, as `field:type[:widget][!]` (`!` = required). */ + const entryFaces = (row: FormEntry | undefined) => + (row?.fields ?? []).map( + (f) => `${f.field}:${f.type}${f.widget ? `:${f.widget}` : ''}${(f as { required?: boolean }).required ? '!' : ''}`, + ); + + it('CONTROLS: the probe reads the hook form texts row it mirrors, and reports a known absence', () => { + const [hookRow] = rowFor('hook', 'texts'); + expect(hookRow?.widget, 'lit control: the hook form row this one copies').toBe('key-only-record'); + expect(entryFaces(hookRow)).toEqual(['message:textarea!', 'params:tags']); + expect(rowFor('action', 'noSuchKeyAtAll'), 'dark control: a key the action form does not offer').toHaveLength(0); + expect(indexOf('body'), 'the Behavior section holds the script body').toBeGreaterThanOrEqual(0); + }); + + it('is offered once, as a key-only record whose entry controls are the served entry keys', () => { + const [row, ...extra] = rowFor('action', 'texts'); + expect(row, '`texts` is declared by ActionSchema and live; the action form must offer it').toBeDefined(); + expect(extra, 'one row only').toEqual([]); + expect(row.type).toBe('record'); + expect(row.widget).toBe('key-only-record'); + expect(row.helpText).toContain('ctx.text'); + expect(entryFaces(row)).toEqual(['message:textarea!', 'params:tags']); + expect((row.fields ?? []).map((f) => f.field)).toEqual(Object.keys((ActionTextSchema as any).shape)); + }); + + it('is gated like the body, and sits after it in the Behavior section', () => { + const [body] = rowFor('action', 'body'); + const [row] = rowFor('action', 'texts'); + expect(row.visibleWhen).toEqual({ dialect: 'cel', source: "data.type == 'script'" }); + expect(row.visibleWhen).toEqual(body.visibleWhen); + expect(indexOf('texts')).toBeGreaterThan(indexOf('body')); + expect(indexOf('texts'), 'beside the body, before the param dialog rows').toBeLessThan(indexOf('params')); + }); +}); 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 88456f34fd4..3cb2ec6e687 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -475,18 +475,6 @@ const LEDGER: ReadonlyArray = [ key: 'refusals', why: "live, not yet offered in the Studio — the refusals a `script` action's `js` body throws by code (answered with the declared sentence in the caller's locale) are validated at parse (SCREAMING_SNAKE codes, the hook entry's closed-scope holes over declared `params`, a literal code or reason the catalogue does not declare refused at save) and read at run time, and they are declared in the action's package source beside the body that throws them. The Studio row, a key-only record, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then an action authored in the Studio declares `refusals` through the metadata API or its package source", }, - // #34374 (action half) — an action's declared texts land in the action's - // source first, as its refusal catalogue (#34273) and a hook's declared - // texts did. The Studio row (a key-only record, with its help text in the - // eleven metadata-forms bundles) is a follow-up, so this row records why the - // key is not offered. - { - kind: 'omit', - type: 'action', - path: ROOT_PATH, - key: 'texts', - why: "live, not yet offered in the Studio — the sentences a `script` action's `js` body 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 action does not declare refused at save) and read at run time, and they are declared in the action's package source beside the body 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 an action 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/ui/action.form.ts b/packages/spec/src/ui/action.form.ts index c86ce3de265..5b9c751cbce 100644 --- a/packages/spec/src/ui/action.form.ts +++ b/packages/spec/src/ui/action.form.ts @@ -63,6 +63,23 @@ export const actionForm = defineForm({ { field: 'memoryMb', type: 'number', helpText: 'Per-invocation memory cap (MB, max 256)' }, ], }, + // The action's declared texts sit beside the body that asks for them, + // as on the hook form, and take its row: a record keyed by the + // snake_case key the code asks for, an entry `{ message, params? }` + // with no member that echoes its key, so the key-only record control. + // Gated like `body`: the parse refuses `texts` on every action but a + // `script` one (and on its `expression` body, which the help text says). + { + field: 'texts', + type: 'record', + widget: 'key-only-record', + visibleWhen: "data.type == 'script'", + helpText: "Sentences the action writes into records, keyed by the snake_case key its body asks for with ctx.text (e.g. email_subject). The body gets the declared message in the organization's language, translated, with the declared message as the fallback. For a script action's JavaScript (L2) body; refused on an expression body", + fields: [ + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the action writes when its body asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param' }, + { field: 'params', type: 'tags', helpText: 'Names the sentence may fill (e.g. subject): the body asks for ctx.text(key, { subject }), and a {{ subject }} hole renders it. Absent: the sentence is plain text' }, + ], + }, { field: 'params', type: 'repeater', From e2f6d2f7c94d3ffe2d4dda8abec207e5afd72111 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:20:21 +0000 Subject: [PATCH 10/17] feat(platform-objects): the action texts row's label and help text in the eleven metadata-forms packs en regenerated from the form; the ten translated locales hand-written from each pack's hook texts wording. The action enumerated-children pin moves 7 to 9 and the translated row-label pin 744 to 747. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC --- .../action-body-panel-echo-decisions.test.ts | 13 +++++++++---- .../translations/ar.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/de.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/en.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/es-ES.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/fr.metadata-forms.generated.ts | 12 ++++++++++++ .../apps/translations/fr.source-hashes.generated.ts | 1 + .../translations/ja-JP.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/ko.metadata-forms.generated.ts | 12 ++++++++++++ .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- .../translations/pt-BR.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/ru.metadata-forms.generated.ts | 12 ++++++++++++ .../translations/zh-CN.metadata-forms.generated.ts | 12 ++++++++++++ .../zh-Hant.metadata-forms.generated.ts | 12 ++++++++++++ 14 files changed, 146 insertions(+), 5 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts index aeabac85761..984c47fd687 100644 --- a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts @@ -661,8 +661,12 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, // `type === 'repeater'`, and `body` is a `composite`. All five echoed in // all three locales, and they are five of the six keys this round decides. // 7 since the action form offers the `onSuccess` composite — its two - // children, `navigate` and `openIn`, authored in all three locales. - expect(ACTION_ENUMERATED.skipped.length).toBe(7); + // children, `navigate` and `openIn`, authored in all three locales. 9 + // since #35096: the form offers the `texts` record, whose entry fields + // (`message`, `params`) are enumerated the same way. + expect(ACTION_ENUMERATED.skipped.length).toBe(9); + expect(ACTION_ENUMERATED.skipped).toContain('texts.message'); + expect(ACTION_ENUMERATED.skipped).toContain('texts.params'); for (const child of SHARED_BODY_CHILDREN) { expect(ACTION_ENUMERATED.skipped).toContain(`body.${child}`); expect( @@ -728,8 +732,9 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, const coveredParents = new Set(ACTION_ENUMERATED.covered.map((k) => k.replace(/\.[^.]+$/, ''))); const skippedParents = new Set(ACTION_ENUMERATED.skipped.map((k) => k.replace(/\.[^.]+$/, ''))); expect([...coveredParents]).toEqual(['params']); - // `onSuccess` since the action form offers it as a composite beside `body`. - expect([...skippedParents]).toEqual(['body', 'onSuccess']); + // `onSuccess` since the action form offers it as a composite beside `body`, + // and `texts` since #35096 (the record row after `body`). + expect([...skippedParents]).toEqual(['body', 'texts', 'onSuccess']); for (const parent of ['params', 'body']) { expect(ACTION_ENUMERATED.covered.includes(parent), `${parent} is not itself a row property`).toBe(false); expect(ACTION_ENUMERATED.skipped.includes(parent), `${parent} is not itself an unwalked child`).toBe(false); diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 16f18cf9f14..7781054f475 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const arMetadataForms: NonNullable = { label: "الذاكرة (ميغابايت)", helpText: "حد الذاكرة لكل استدعاء (ميغابايت، بحد أقصى 256)" }, + texts: { + label: "النصوص", + helpText: "الجمل التي يكتبها الإجراء في السجلات، مفهرسة بالمفتاح بصيغة snake_case الذي يطلبه متنه عبر ctx.text (مثل email_subject). يتلقى المتن الرسالة المُعلنة بلغة المؤسسة، مترجمة، مع الرسالة المُعلنة بديلًا عند غياب الترجمة. لمتن JavaScript ‏(L2) في إجراء script؛ ويُرفض في متن التعبير" + }, + "texts.message": { + label: "الرسالة", + helpText: "الجملة التي يكتبها الإجراء عندما يطلب متنه هذا المفتاح. نص عادي، ما لم يُعلن الإدخال params: عندها يملأ العنصر النائب {{ name }} معاملًا مُعلنًا" + }, + "texts.params": { + label: "المعاملات", + helpText: "الأسماء التي يمكن للجملة ملؤها (مثل subject): يطلب المتن ctx.text(key, { subject }) ويعرض العنصر النائب {{ subject }} قيمتها. عند الغياب: الجملة نص عادي" + }, params: { label: "المعلمات", helpText: "معلمات إدخال المستخدم (إظهار نموذج قبل التنفيذ)" diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 720eb0354bf..9c7ee1747d2 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const deMetadataForms: NonNullable = { label: "Speicher (MB)", helpText: "Speicherobergrenze pro Aufruf (MB, max. 256)" }, + texts: { + label: "Texte", + helpText: "Sätze, die die Aktion in Datensätze schreibt, nach dem snake_case-Schlüssel, den ihr Rumpf mit ctx.text anfragt (z. B. email_subject). Der Rumpf erhält die deklarierte Meldung in der Sprache der Organisation, übersetzt, mit der deklarierten Meldung als Rückfall. Für den JavaScript-Rumpf (L2) einer script-Aktion; bei einem Ausdrucksrumpf abgelehnt" + }, + "texts.message": { + label: "Meldung", + helpText: "Der Satz, den die Aktion schreibt, wenn ihr Rumpf diesen Schlüssel anfragt. Einfacher Text, außer der Eintrag deklariert params: dann füllt ein Platzhalter {{ name }} einen deklarierten Parameter" + }, + "texts.params": { + label: "Parameter", + helpText: "Namen, die der Satz füllen darf (z. B. subject): Der Rumpf fragt ctx.text(key, { subject }) an, und ein Platzhalter {{ subject }} zeigt den Wert. Fehlt er: Der Satz ist einfacher Text" + }, params: { label: "Parameter", helpText: "Benutzereingabeparameter (Formular vor der Ausführung anzeigen)" diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index c4e81aac640..4a8be27af0c 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const enMetadataForms: NonNullable = { label: "Memory Mb", helpText: "Per-invocation memory cap (MB, max 256)" }, + texts: { + label: "Texts", + helpText: "Sentences the action writes into records, keyed by the snake_case key its body asks for with ctx.text (e.g. email_subject). The body gets the declared message in the organization's language, translated, with the declared message as the fallback. For a script action's JavaScript (L2) body; refused on an expression body" + }, + "texts.message": { + label: "Message", + helpText: "The sentence the action writes when its body asks for this key. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param" + }, + "texts.params": { + label: "Params", + helpText: "Names the sentence may fill (e.g. subject): the body asks for ctx.text(key, { subject }), and a {{ subject }} hole renders it. Absent: the sentence is plain text" + }, params: { label: "Params", helpText: "User input parameters (show form before executing)" diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 0666f3ea388..7644921b76f 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const esESMetadataForms: NonNullable = label: "Memoria (MB)", helpText: "Límite de memoria por invocación (MB, máx. 256)" }, + texts: { + label: "Textos", + helpText: "Frases que la acción escribe en los registros, indexadas por la clave snake_case que su cuerpo pide con ctx.text (p. ej. email_subject). El cuerpo recibe el mensaje declarado en el idioma de la organización, traducido, con el mensaje declarado como respaldo. Para el cuerpo JavaScript (L2) de una acción script; se rechaza en un cuerpo de expresión" + }, + "texts.message": { + label: "Mensaje", + helpText: "La frase que escribe la acción cuando su cuerpo pide esta clave. Texto plano, salvo que la entrada declare params: entonces un marcador {{ name }} se rellena con un parámetro declarado" + }, + "texts.params": { + label: "Parámetros", + helpText: "Nombres que la frase puede rellenar (p. ej. subject): el cuerpo pide ctx.text(key, { subject }) y un marcador {{ subject }} muestra su valor. Si se omite: la frase es texto plano" + }, params: { label: "Parámetros", helpText: "Parámetros de entrada de usuario (muestra el formulario antes de ejecutar)" diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 2e47bd7c82d..40d71241960 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const frMetadataForms: NonNullable = { label: "Mémoire (Mo)", helpText: "Plafond de mémoire par appel (Mo, 256 max.)" }, + texts: { + label: "Textes", + helpText: "Les phrases que l’action écrit dans les enregistrements, indexées par la clé snake_case que son corps demande avec ctx.text (par ex. email_subject). Le corps reçoit le message déclaré dans la langue de l’organisation, traduit, avec le message déclaré comme repli. Pour le corps JavaScript (L2) d’une action script ; refusé sur un corps expression" + }, + "texts.message": { + label: "Message", + helpText: "La phrase que l’action écrit lorsque son corps demande cette clé. Texte brut, sauf si l’entrée déclare des params : un espace réservé {{ name }} reçoit alors un paramètre déclaré" + }, + "texts.params": { + label: "Paramètres", + helpText: "Les noms que la phrase peut remplir (par ex. subject) : le corps demande ctx.text(key, { subject }), et un espace réservé {{ subject }} en affiche la valeur. Absent : la phrase est du texte brut" + }, params: { label: "Paramètres", helpText: "Paramètres saisis par l’utilisateur (afficher un formulaire avant l’exécution)" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 8399fd2d550..a053bb454f9 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -21,6 +21,7 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.action.fields.body.source.label": "8fe786e8e29c8cec", "metadataForms.action.fields.description.label": "779a4342c8eb6707", "metadataForms.action.fields.mode.label": "74dde5013435abdc", + "metadataForms.action.fields.texts.message.label": "2af15199795c25b9", "metadataForms.action.fields.type.label": "901bb552898b2cab", "metadataForms.action.fields.visible.label": "7f733614bc9cea97", "metadataForms.action.label": "a36bba313a7aa9ab", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 63371ee0c03..293c8f77095 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const jaJPMetadataForms: NonNullable = label: "メモリ(MB)", helpText: "呼び出しごとのメモリ上限(MB、最大 256)" }, + texts: { + label: "テキスト", + helpText: "アクションがレコードに書き込む文。本文が ctx.text で要求する snake_case のキー(例: email_subject)をキーとします。本文には宣言したメッセージが組織の言語に翻訳されて返り、翻訳がない場合は宣言したメッセージが返ります。script アクションの JavaScript(L2)本文で使用可能。expression 本文では拒否されます" + }, + "texts.message": { + label: "メッセージ", + helpText: "本文がこのキーを要求したときにアクションが書き込む文。プレーンテキスト。ただしエントリが params を宣言している場合、{{ name }} プレースホルダーに宣言済みのパラメーターが入ります" + }, + "texts.params": { + label: "パラメーター", + helpText: "文に埋め込める名前(例: subject)。本文が ctx.text(key, { subject }) を要求すると、{{ subject }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" + }, params: { label: "パラメーター", helpText: "ユーザー入力パラメーター(実行前にフォームを表示)" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 119caa20a0b..c42918c97f0 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const koMetadataForms: NonNullable = { label: "메모리(MB)", helpText: "호출당 메모리 상한(MB, 최대 256)" }, + texts: { + label: "텍스트", + helpText: "작업이 레코드에 쓰는 문장으로, 본문이 ctx.text로 요청하는 snake_case 키(예: email_subject)를 키로 합니다. 본문은 선언된 메시지를 조직의 언어로 번역해 받으며, 번역이 없으면 선언된 메시지를 받습니다. script 작업의 JavaScript(L2) 본문용이며, expression 본문에서는 거부됩니다" + }, + "texts.message": { + label: "메시지", + helpText: "본문이 이 키를 요청할 때 작업이 쓰는 문장입니다. 일반 텍스트이며, 항목이 params를 선언하면 {{ name }} 자리 표시자에 선언된 매개변수가 채워집니다" + }, + "texts.params": { + label: "매개변수", + helpText: "문장에 채울 수 있는 이름(예: subject)입니다. 본문이 ctx.text(key, { subject })를 요청하면 {{ subject }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" + }, params: { label: "매개변수", helpText: "사용자 입력 매개변수(실행 전에 양식 표시)" diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index f5cb0f238c8..ba93c71a8d3 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1289,7 +1289,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 744 since #34575: the hook form offers the `texts` record and its // `message` / `params` entry fields — three row labels, authored in all // three locales. - expect(translated.length, `${locale} positive control`).toBe(744); + // 747 since #35096: the action form offers the `texts` record and its + // `message` / `params` entry fields — three row labels, authored in all + // three locales. + expect(translated.length, `${locale} positive control`).toBe(747); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index dea2e09a05d..17cd2f7ea80 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const ptBRMetadataForms: NonNullable = label: "Memória (MB)", helpText: "Limite de memória por invocação (MB, máx. 256)" }, + texts: { + label: "Textos", + helpText: "Frases que a ação escreve nos registros, indexadas pela chave snake_case que o corpo dela pede com ctx.text (por exemplo email_subject). O corpo recebe a mensagem declarada no idioma da organização, traduzida, com a mensagem declarada como alternativa. Para o corpo JavaScript (L2) de uma ação script; recusado em um corpo de expressão" + }, + "texts.message": { + label: "Mensagem", + helpText: "A frase que a ação escreve quando o corpo dela pede esta chave. Texto simples, a menos que a entrada declare params: então um marcador {{ name }} é preenchido com um parâmetro declarado" + }, + "texts.params": { + label: "Parâmetros", + helpText: "Nomes que a frase pode preencher (por exemplo subject): o corpo pede ctx.text(key, { subject }) e um marcador {{ subject }} mostra o valor. Ausente: a frase é texto simples" + }, params: { label: "Parâmetros", helpText: "Parâmetros de entrada do usuário (mostrar um formulário antes de executar)" diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 0397923e065..b965f08eb5d 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const ruMetadataForms: NonNullable = { label: "Память (МБ)", helpText: "Ограничение памяти на вызов (МБ, максимум 256)" }, + texts: { + label: "Тексты", + helpText: "Фразы, которые действие записывает в записи, с ключами в snake_case, которые его тело запрашивает через ctx.text (например, email_subject). Тело получает объявленное сообщение в переводе на язык организации, а без перевода — само объявленное сообщение. Для тела JavaScript (L2) действия script; для тела-выражения отклоняется" + }, + "texts.message": { + label: "Сообщение", + helpText: "Фраза, которую действие записывает, когда его тело запрашивает этот ключ. Простой текст, если запись не объявляет params: тогда заполнитель {{ name }} подставляет объявленный параметр" + }, + "texts.params": { + label: "Параметры", + helpText: "Имена, которые может заполнять фраза (например, subject): тело запрашивает ctx.text(key, { subject }), и заполнитель {{ subject }} показывает значение. Если отсутствует: фраза — простой текст" + }, params: { label: "Параметры", helpText: "Параметры ввода пользователя (показать форму перед выполнением)" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 6e820738da2..ff89390b908 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const zhCNMetadataForms: NonNullable = label: "内存(MB)", helpText: "单次调用内存上限(MB,最大 256)" }, + texts: { + label: "文本", + helpText: "操作写入记录的句子,以其正文通过 ctx.text 请求的 snake_case 键为键(例如 email_subject)。正文得到按组织语言翻译的声明句子,无翻译时回退为声明的句子。适用于 script 操作的 JavaScript(L2)正文;表达式正文声明会被拒绝" + }, + "texts.message": { + label: "句子", + helpText: "正文请求此键时操作写入的句子。纯文本;若该条目声明了参数,则 {{ name }} 占位符填入一个已声明的参数" + }, + "texts.params": { + label: "参数", + helpText: "句子可填入的名称(例如 subject):正文请求 ctx.text(key, { subject }),{{ subject }} 占位符即显示该值。不填:句子为纯文本" + }, params: { label: "参数", helpText: "执行前向用户收集的输入参数" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index ad8ce45755d..005ecee258e 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -1893,6 +1893,18 @@ export const zhHantMetadataForms: NonNullable label: "記憶體(MB)", helpText: "單次呼叫記憶體上限(MB,最大 256)" }, + texts: { + label: "文字", + helpText: "操作寫入記錄的句子,以其內文透過 ctx.text 請求的 snake_case 鍵為鍵(例如 email_subject)。內文取得依組織語言翻譯的宣告句子,無翻譯時退回宣告的句子。適用於 script 操作的 JavaScript(L2)內文;運算式內文宣告會被拒絕" + }, + "texts.message": { + label: "句子", + helpText: "內文請求此鍵時操作寫入的句子。純文字;若該條目宣告了參數,則 {{ name }} 預留位置填入一個已宣告的參數" + }, + "texts.params": { + label: "參數", + helpText: "句子可填入的名稱(例如 subject):內文請求 ctx.text(key, { subject }),{{ subject }} 預留位置即顯示該值。不填:句子為純文字" + }, params: { label: "參數", helpText: "執行前向使用者收集的輸入參數" From 26fbd428f8a0229bf49372f8e889d26e06cc7b79 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:21:09 +0000 Subject: [PATCH 11/17] feat(spec): the Studio action form offers the action's refusal catalogue The action form gains a refusals row between the script body and texts: the hook form's key-only record (message, status, reasons, params), the entry the one factory builds for both, gated like the body. The action/refusals omit row is retired from the reconciliation ledger. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC --- .../metadata-form-declared-rows.pin.test.ts | 51 +++++++++++++++---- .../metadata-form-zod-reconciliation.test.ts | 11 ---- packages/spec/src/ui/action.form.ts | 30 +++++++++++ 3 files changed, 72 insertions(+), 20 deletions(-) diff --git a/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts b/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts index ecb18c7d157..4cd5b8ad431 100644 --- a/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts +++ b/packages/spec/src/system/metadata-form-declared-rows.pin.test.ts @@ -43,7 +43,7 @@ import { describe, it, expect } from 'vitest'; import { METADATA_FORM_REGISTRY } from './metadata-form-registry'; -import { ActionTextSchema } from '../ui/action.zod'; +import { ActionRefusalSchema, ActionTextSchema } from '../ui/action.zod'; type FormEntry = { field?: string; @@ -261,32 +261,44 @@ describe('hook.condition declares the CEL predicate language it edits', () => { * `ActionSchema.texts` is a record keyed by the snake_case key the body asks * for with `ctx.text`, each entry `{ message, params? }` with no member that * echoes its key, so its row is the hook form's: a `key-only-record`, which - * adds, renames and removes keys and never writes the key into the entry. The - * reconciliation gate proves the key and its entry keys are offered somewhere - * on the form; it does not read the control, the gate or where the row sits, - * so this pin keeps all three. + * adds, renames and removes keys and never writes the key into the entry. + * `ActionSchema.refusals` is the same record shape keyed by the + * SCREAMING_SNAKE code the body throws, its entry the hook refusal entry + * (`{ message, status?, reasons?, params? }`, `reasons` the same shape one + * level down), so it takes the hook form's `refusals` row. The + * reconciliation gate proves the keys and their entry keys are offered + * somewhere on the form; it does not read the control, the gate or where the + * rows sit, so this pin keeps all three. */ -describe('action.texts is a key-only record beside the script body', () => { +describe('action.refusals and action.texts are key-only records beside the script body', () => { type Section = { label?: string; fields?: FormEntry[] }; const behaviorRows = () => ((((METADATA_FORM_REGISTRY.action as any)?.sections ?? []) as Section[]).find((s) => s.label === 'Behavior') ?.fields ?? []) as FormEntry[]; const indexOf = (key: string) => behaviorRows().findIndex((r) => r?.field === key); + const REFUSAL_FACES = [ + 'message:textarea!', + 'status:number', + 'reasons:record:key-only-record', + 'params:tags', + ] as const; /** A row's entry controls, as `field:type[:widget][!]` (`!` = required). */ const entryFaces = (row: FormEntry | undefined) => (row?.fields ?? []).map( (f) => `${f.field}:${f.type}${f.widget ? `:${f.widget}` : ''}${(f as { required?: boolean }).required ? '!' : ''}`, ); - it('CONTROLS: the probe reads the hook form texts row it mirrors, and reports a known absence', () => { + it('CONTROLS: the probe reads the hook form rows it mirrors, and reports a known absence', () => { const [hookRow] = rowFor('hook', 'texts'); expect(hookRow?.widget, 'lit control: the hook form row this one copies').toBe('key-only-record'); expect(entryFaces(hookRow)).toEqual(['message:textarea!', 'params:tags']); + const [hookRefusals] = rowFor('hook', 'refusals'); + expect(entryFaces(hookRefusals)).toEqual([...REFUSAL_FACES]); expect(rowFor('action', 'noSuchKeyAtAll'), 'dark control: a key the action form does not offer').toHaveLength(0); expect(indexOf('body'), 'the Behavior section holds the script body').toBeGreaterThanOrEqual(0); }); - it('is offered once, as a key-only record whose entry controls are the served entry keys', () => { + it('offers texts once, as a key-only record whose entry controls are the served entry keys', () => { const [row, ...extra] = rowFor('action', 'texts'); expect(row, '`texts` is declared by ActionSchema and live; the action form must offer it').toBeDefined(); expect(extra, 'one row only').toEqual([]); @@ -297,7 +309,28 @@ describe('action.texts is a key-only record beside the script body', () => { expect((row.fields ?? []).map((f) => f.field)).toEqual(Object.keys((ActionTextSchema as any).shape)); }); - it('is gated like the body, and sits after it in the Behavior section', () => { + it('offers refusals once, as a key-only record whose entry controls are the served entry keys', () => { + const [row, ...extra] = rowFor('action', 'refusals'); + expect(row, '`refusals` is declared by ActionSchema and live; the action form must offer it').toBeDefined(); + expect(extra, 'one row only').toEqual([]); + expect(row.type).toBe('record'); + expect(row.widget).toBe('key-only-record'); + expect(row.helpText).toContain('SCREAMING_SNAKE'); + expect(entryFaces(row)).toEqual([...REFUSAL_FACES]); + expect((row.fields ?? []).map((f) => f.field)).toEqual(Object.keys((ActionRefusalSchema as any).shape)); + const reasons = (row.fields ?? []).find((f) => f.field === 'reasons'); + expect(entryFaces(reasons), 'a reason is `{ message }`, the hook row\'s nested record').toEqual(['message:textarea!']); + }); + + it('refusals is gated like the body, and sits between it and texts', () => { + const [body] = rowFor('action', 'body'); + const [row] = rowFor('action', 'refusals'); + expect(row.visibleWhen).toEqual(body.visibleWhen); + expect(indexOf('refusals')).toBe(indexOf('body') + 1); + expect(indexOf('texts')).toBe(indexOf('refusals') + 1); + }); + + it('texts is gated like the body, and sits after it in the Behavior section', () => { const [body] = rowFor('action', 'body'); const [row] = rowFor('action', 'texts'); expect(row.visibleWhen).toEqual({ dialect: 'cel', source: "data.type == 'script'" }); 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 3cb2ec6e687..5a062fefce0 100644 --- a/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts +++ b/packages/spec/src/system/metadata-form-zod-reconciliation.test.ts @@ -464,17 +464,6 @@ 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", }, - // #34273 — an action's refusal catalogue lands in the action's source - // first, as a hook's declared texts did (#34374). The Studio row (a - // key-only record, with its help text in the eleven metadata-forms - // bundles) is a follow-up, so this row records why the key is not offered. - { - kind: 'omit', - type: 'action', - path: ROOT_PATH, - key: 'refusals', - why: "live, not yet offered in the Studio — the refusals a `script` action's `js` body throws by code (answered with the declared sentence in the caller's locale) are validated at parse (SCREAMING_SNAKE codes, the hook entry's closed-scope holes over declared `params`, a literal code or reason the catalogue does not declare refused at save) and read at run time, and they are declared in the action's package source beside the body that throws them. The Studio row, a key-only record, needs its labels and help text translated in the eleven metadata-forms bundles and is owed to a follow-up card; until then an action authored in the Studio declares `refusals` 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/ui/action.form.ts b/packages/spec/src/ui/action.form.ts index 5b9c751cbce..04b4afc2048 100644 --- a/packages/spec/src/ui/action.form.ts +++ b/packages/spec/src/ui/action.form.ts @@ -63,6 +63,36 @@ export const actionForm = defineForm({ { field: 'memoryMb', type: 'number', helpText: 'Per-invocation memory cap (MB, max 256)' }, ], }, + // The action's refusal catalogue sits beside the body that throws its + // codes, as on the hook form, and takes that form's row: a record keyed + // by the code, an entry with no member that echoes its key, so the + // key-only record control; an entry's `reasons` is the same shape one + // level down. The entry is the hook entry, built by the one factory + // (`declaredRefusalEntrySchema`), so its four controls are the hook + // row's. Gated like `body`: the parse refuses `refusals` on every + // action but a `script` one (and on its `expression` body, which the + // help text says). + { + field: 'refusals', + type: 'record', + widget: 'key-only-record', + visibleWhen: "data.type == 'script'", + helpText: "Refusal catalogue, keyed by the SCREAMING_SNAKE code the action's body throws (e.g. SIGN_IN_REQUIRED). The caller reads the declared message, translated into their language, with the declared status. For a script action's JavaScript (L2) body; refused on an expression body", + fields: [ + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the user reads when the body throws this code. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param' }, + { field: 'status', type: 'number', helpText: 'HTTP status of the refusal (400–499). Absent: 400' }, + { + field: 'reasons', + type: 'record', + widget: 'key-only-record', + helpText: 'Further sentences under this same code, keyed by the snake_case reason the body throws beside the code ({ code, reason }). The wire code and status stay this entry\'s; a reason not declared here is refused. Absent: a thrown reason is not read', + fields: [ + { field: 'message', type: 'textarea', required: true, helpText: 'The sentence the user reads when the body throws this reason under the code. Its {{ }} holes follow the entry\'s params' }, + ], + }, + { field: 'params', type: 'tags', helpText: 'Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text' }, + ], + }, // The action's declared texts sit beside the body that asks for them, // as on the hook form, and take its row: a record keyed by the // snake_case key the code asks for, an entry `{ message, params? }` From 52a32ad1b4ded3c8e083053447479ae88693ee88 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:28:38 +0000 Subject: [PATCH 12/17] feat(platform-objects): the action refusals row's label and help text in the eleven metadata-forms packs en regenerated from the form; the ten translated locales reuse each pack's hook refusals entries for the five entry fields (the en sources are identical) and hand-write the top row. The action enumerated-children pin moves 9 to 14 and the translated row-label pin 747 to 753. Adds the changeset for both rows. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC --- .../35096-action-form-texts-refusals-rows.md | 12 ++++++++++ .../action-body-panel-echo-decisions.test.ts | 13 ++++++---- .../ar.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../de.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../de.source-hashes.generated.ts | 1 + .../en.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../es-ES.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../fr.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../fr.source-hashes.generated.ts | 2 ++ .../ja-JP.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../ko.metadata-forms.generated.ts | 24 +++++++++++++++++++ ...ect-lifecycle-panel-echo-decisions.test.ts | 4 +++- .../pt-BR.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../pt-BR.source-hashes.generated.ts | 1 + .../ru.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../zh-CN.metadata-forms.generated.ts | 24 +++++++++++++++++++ .../zh-Hant.metadata-forms.generated.ts | 24 +++++++++++++++++++ 17 files changed, 292 insertions(+), 5 deletions(-) create mode 100644 .changeset/35096-action-form-texts-refusals-rows.md diff --git a/.changeset/35096-action-form-texts-refusals-rows.md b/.changeset/35096-action-form-texts-refusals-rows.md new file mode 100644 index 00000000000..18052b79cf3 --- /dev/null +++ b/.changeset/35096-action-form-texts-refusals-rows.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +--- + +feat(spec): the Studio action form offers an action's declared `refusals` and `texts` + +Clause-②: no +Metadata-protocol: none + +- **Studio action form.** `actionForm` gains two rows in the Behavior section, right after the script `body`, each shown only on a `type: 'script'` action as the body is: `refusals`, a key-only record keyed by the SCREAMING_SNAKE code the body throws, each entry editing its `message`, `status`, `reasons` (a key-only record of `{ message }`) and `params`; and `texts`, a key-only record keyed by the snake_case key the body asks for with `ctx.text`, each entry editing its `message` and `params`. They are the hook form's two rows, because the action entries are the hook entries. An author editing an action in the Studio can now write the `refusals` and `texts` the schema already accepts, instead of going through the metadata API or the package source. Nothing about what an action may declare changes. +- **Locale packs.** The rows' labels and help text ship in all eleven metadata-forms locale packs of `@objectstack/platform-objects`. diff --git a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts index 984c47fd687..dcd8766f4ee 100644 --- a/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/action-body-panel-echo-decisions.test.ts @@ -663,10 +663,14 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, // 7 since the action form offers the `onSuccess` composite — its two // children, `navigate` and `openIn`, authored in all three locales. 9 // since #35096: the form offers the `texts` record, whose entry fields - // (`message`, `params`) are enumerated the same way. - expect(ACTION_ENUMERATED.skipped.length).toBe(9); + // (`message`, `params`) are enumerated the same way. 14 since #34823: the + // form offers the `refusals` record, the hook row's five entry fields. + expect(ACTION_ENUMERATED.skipped.length).toBe(14); expect(ACTION_ENUMERATED.skipped).toContain('texts.message'); expect(ACTION_ENUMERATED.skipped).toContain('texts.params'); + for (const child of ['message', 'status', 'reasons', 'reasons.message', 'params']) { + expect(ACTION_ENUMERATED.skipped).toContain(`refusals.${child}`); + } for (const child of SHARED_BODY_CHILDREN) { expect(ACTION_ENUMERATED.skipped).toContain(`body.${child}`); expect( @@ -733,8 +737,9 @@ describe('#19403 round 5 — the blind spot, FIFTH shape: one schema, two forms, const skippedParents = new Set(ACTION_ENUMERATED.skipped.map((k) => k.replace(/\.[^.]+$/, ''))); expect([...coveredParents]).toEqual(['params']); // `onSuccess` since the action form offers it as a composite beside `body`, - // and `texts` since #35096 (the record row after `body`). - expect([...skippedParents]).toEqual(['body', 'texts', 'onSuccess']); + // `texts` since #35096 and `refusals` (with its nested `reasons`) since + // #34823, the two record rows after `body`. + expect([...skippedParents]).toEqual(['body', 'refusals', 'refusals.reasons', 'texts', 'onSuccess']); for (const parent of ['params', 'body']) { expect(ACTION_ENUMERATED.covered.includes(parent), `${parent} is not itself a row property`).toBe(false); expect(ACTION_ENUMERATED.skipped.includes(parent), `${parent} is not itself an unwalked child`).toBe(false); diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 7781054f475..969e94f0ff9 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const arMetadataForms: NonNullable = { label: "الذاكرة (ميغابايت)", helpText: "حد الذاكرة لكل استدعاء (ميغابايت، بحد أقصى 256)" }, + refusals: { + label: "حالات الرفض", + helpText: "فهرس حالات الرفض، مفهرس برمز SCREAMING_SNAKE الذي يرميه متن الإجراء (مثل SIGN_IN_REQUIRED). يقرأ المستدعي الرسالة المُعلنة، مترجمة إلى لغته، مع الحالة المُعلنة. لمتن JavaScript ‏(L2) في إجراء script؛ ويُرفض في متن التعبير" + }, + "refusals.message": { + label: "الرسالة", + helpText: "الجملة التي يقرؤها المستخدم عندما يرمي المتن هذا الرمز. نص عادي، ما لم يُعلن الإدخال params: عندها يملأ العنصر النائب {{ name }} معاملًا مُعلنًا" + }, + "refusals.status": { + label: "الحالة", + helpText: "حالة HTTP للرفض (400–499). عند الغياب: 400" + }, + "refusals.reasons": { + label: "الأسباب", + helpText: "جمل إضافية تحت الرمز نفسه، مفهرسة بالسبب بصيغة snake_case الذي يرميه المتن بجانب الرمز ({ code, reason }). يبقى الرمز والحالة المُرسَلان لهذا الإدخال؛ ويُرفض سبب غير مُعلن هنا. عند الغياب: لا يُقرأ السبب المرمي" + }, + "refusals.reasons.message": { + label: "الرسالة", + helpText: "الجملة التي يقرؤها المستخدم عندما يرمي المتن هذا السبب تحت الرمز. تتبع عناصرها النائبة {{ }} معاملات params للإدخال" + }, + "refusals.params": { + label: "المعاملات", + helpText: "الأسماء التي يمكن للجمل ملؤها (مثل state): يرمي المتن { code, params: { state } } ويعرض العنصر النائب {{ state }} قيمتها. عند الغياب: الجمل نص عادي" + }, texts: { label: "النصوص", helpText: "الجمل التي يكتبها الإجراء في السجلات، مفهرسة بالمفتاح بصيغة snake_case الذي يطلبه متنه عبر ctx.text (مثل email_subject). يتلقى المتن الرسالة المُعلنة بلغة المؤسسة، مترجمة، مع الرسالة المُعلنة بديلًا عند غياب الترجمة. لمتن JavaScript ‏(L2) في إجراء script؛ ويُرفض في متن التعبير" diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 9c7ee1747d2..c8d4084fda3 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const deMetadataForms: NonNullable = { label: "Speicher (MB)", helpText: "Speicherobergrenze pro Aufruf (MB, max. 256)" }, + refusals: { + label: "Ablehnungen", + helpText: "Katalog der Ablehnungen, nach dem SCREAMING_SNAKE-Code, den der Rumpf der Aktion wirft (z. B. SIGN_IN_REQUIRED). Der Aufrufer liest die deklarierte Meldung, übersetzt in seine Sprache, mit dem deklarierten Status. Für den JavaScript-Rumpf (L2) einer script-Aktion; bei einem Ausdrucksrumpf abgelehnt" + }, + "refusals.message": { + label: "Meldung", + helpText: "Der Satz, den der Benutzer liest, wenn der Rumpf diesen Code wirft. Einfacher Text, außer der Eintrag deklariert params: dann füllt ein Platzhalter {{ name }} einen deklarierten Parameter" + }, + "refusals.status": { + label: "Status", + helpText: "HTTP-Status der Ablehnung (400–499). Fehlt er: 400" + }, + "refusals.reasons": { + label: "Gründe", + helpText: "Weitere Sätze unter demselben Code, nach dem snake_case-Grund, den der Rumpf neben dem Code wirft ({ code, reason }). Gesendeter Code und Status bleiben die dieses Eintrags; ein hier nicht deklarierter Grund wird abgelehnt. Fehlt er: Ein geworfener Grund wird nicht gelesen" + }, + "refusals.reasons.message": { + label: "Meldung", + helpText: "Der Satz, den der Benutzer liest, wenn der Rumpf diesen Grund unter dem Code wirft. Seine {{ }}-Platzhalter folgen den params des Eintrags" + }, + "refusals.params": { + label: "Parameter", + helpText: "Namen, die die Sätze füllen dürfen (z. B. state): Der Rumpf wirft { code, params: { state } }, und ein Platzhalter {{ state }} zeigt den Wert. Fehlt er: Die Sätze sind einfacher Text" + }, texts: { label: "Texte", helpText: "Sätze, die die Aktion in Datensätze schreibt, nach dem snake_case-Schlüssel, den ihr Rumpf mit ctx.text anfragt (z. B. email_subject). Der Rumpf erhält die deklarierte Meldung in der Sprache der Organisation, übersetzt, mit der deklarierten Meldung als Rückfall. Für den JavaScript-Rumpf (L2) einer script-Aktion; bei einem Ausdrucksrumpf abgelehnt" diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 628a3fca820..445d412b292 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -20,6 +20,7 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.action.fields.name.label": "5274417ff1ccaf01", "metadataForms.action.fields.patch.label": "815f68570a78eba1", + "metadataForms.action.fields.refusals.status.label": "64a420165247654b", "metadataForms.agent.fields.avatar.label": "0f06369995b69b8b", "metadataForms.agent.fields.name.label": "5274417ff1ccaf01", "metadataForms.app.fields.branding.label": "ec6e391065514b64", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 4a8be27af0c..07ed12ef3d1 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const enMetadataForms: NonNullable = { label: "Memory Mb", helpText: "Per-invocation memory cap (MB, max 256)" }, + refusals: { + label: "Refusals", + helpText: "Refusal catalogue, keyed by the SCREAMING_SNAKE code the action's body throws (e.g. SIGN_IN_REQUIRED). The caller reads the declared message, translated into their language, with the declared status. For a script action's JavaScript (L2) body; refused on an expression body" + }, + "refusals.message": { + label: "Message", + helpText: "The sentence the user reads when the body throws this code. Plain text, unless the entry declares params: then a {{ name }} hole fills a declared param" + }, + "refusals.status": { + label: "Status", + helpText: "HTTP status of the refusal (400–499). Absent: 400" + }, + "refusals.reasons": { + label: "Reasons", + helpText: "Further sentences under this same code, keyed by the snake_case reason the body throws beside the code ({ code, reason }). The wire code and status stay this entry's; a reason not declared here is refused. Absent: a thrown reason is not read" + }, + "refusals.reasons.message": { + label: "Message", + helpText: "The sentence the user reads when the body throws this reason under the code. Its {{ }} holes follow the entry's params" + }, + "refusals.params": { + label: "Params", + helpText: "Names the sentences may fill (e.g. state): the body throws { code, params: { state } }, and a {{ state }} hole renders it. Absent: the sentences are plain text" + }, texts: { label: "Texts", helpText: "Sentences the action writes into records, keyed by the snake_case key its body asks for with ctx.text (e.g. email_subject). The body gets the declared message in the organization's language, translated, with the declared message as the fallback. For a script action's JavaScript (L2) body; refused on an expression body" diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 7644921b76f..5eba73a2fcb 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const esESMetadataForms: NonNullable = label: "Memoria (MB)", helpText: "Límite de memoria por invocación (MB, máx. 256)" }, + refusals: { + label: "Rechazos", + helpText: "Catálogo de rechazos, indexado por el código SCREAMING_SNAKE que lanza el cuerpo de la acción (p. ej. SIGN_IN_REQUIRED). Quien llama recibe el mensaje declarado, traducido a su idioma, con el estado declarado. Para el cuerpo JavaScript (L2) de una acción script; se rechaza en un cuerpo de expresión" + }, + "refusals.message": { + label: "Mensaje", + helpText: "La frase que lee el usuario cuando el cuerpo lanza este código. Texto plano, salvo que la entrada declare params: entonces un marcador {{ name }} se rellena con un parámetro declarado" + }, + "refusals.status": { + label: "Estado", + helpText: "Estado HTTP del rechazo (400–499). Si se omite: 400" + }, + "refusals.reasons": { + label: "Motivos", + helpText: "Más frases bajo este mismo código, indexadas por el motivo snake_case que el cuerpo lanza junto al código ({ code, reason }). El código y el estado que se envían siguen siendo los de esta entrada; se rechaza un motivo no declarado aquí. Si se omite: no se lee un motivo lanzado" + }, + "refusals.reasons.message": { + label: "Mensaje", + helpText: "La frase que lee el usuario cuando el cuerpo lanza este motivo bajo el código. Sus marcadores {{ }} siguen los params de la entrada" + }, + "refusals.params": { + label: "Parámetros", + helpText: "Nombres que las frases pueden rellenar (p. ej. state): el cuerpo lanza { code, params: { state } } y un marcador {{ state }} muestra su valor. Si se omite: las frases son texto plano" + }, texts: { label: "Textos", helpText: "Frases que la acción escribe en los registros, indexadas por la clave snake_case que su cuerpo pide con ctx.text (p. ej. email_subject). El cuerpo recibe el mensaje declarado en el idioma de la organización, traducido, con el mensaje declarado como respaldo. Para el cuerpo JavaScript (L2) de una acción script; se rechaza en un cuerpo de expresión" diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 40d71241960..11aedf59a1e 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const frMetadataForms: NonNullable = { label: "Mémoire (Mo)", helpText: "Plafond de mémoire par appel (Mo, 256 max.)" }, + refusals: { + label: "Refus", + helpText: "Catalogue des refus, indexé par le code SCREAMING_SNAKE que lève le corps de l’action (par ex. SIGN_IN_REQUIRED). L’appelant lit le message déclaré, traduit dans sa langue, avec le statut déclaré. Pour le corps JavaScript (L2) d’une action script ; refusé sur un corps expression" + }, + "refusals.message": { + label: "Message", + helpText: "La phrase que lit l’utilisateur lorsque le corps lève ce code. Texte brut, sauf si l’entrée déclare des params : un espace réservé {{ name }} reçoit alors un paramètre déclaré" + }, + "refusals.status": { + label: "Statut", + helpText: "Statut HTTP du refus (400–499). Absent : 400" + }, + "refusals.reasons": { + label: "Motifs", + helpText: "D’autres phrases sous ce même code, indexées par le motif snake_case que le corps lève avec le code ({ code, reason }). Le code et le statut transmis restent ceux de cette entrée ; un motif non déclaré ici est refusé. Absent : un motif levé n’est pas lu" + }, + "refusals.reasons.message": { + label: "Message", + helpText: "La phrase que lit l’utilisateur lorsque le corps lève ce motif sous ce code. Ses espaces réservés {{ }} suivent les params de l’entrée" + }, + "refusals.params": { + label: "Paramètres", + helpText: "Les noms que les phrases peuvent remplir (par ex. state) : le corps lève { code, params: { state } }, et un espace réservé {{ state }} en affiche la valeur. Absent : les phrases sont du texte brut" + }, texts: { label: "Textes", helpText: "Les phrases que l’action écrit dans les enregistrements, indexées par la clé snake_case que son corps demande avec ctx.text (par ex. email_subject). Le corps reçoit le message déclaré dans la langue de l’organisation, traduit, avec le message déclaré comme repli. Pour le corps JavaScript (L2) d’une action script ; refusé sur un corps expression" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index a053bb454f9..e75dd623269 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -21,6 +21,8 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.action.fields.body.source.label": "8fe786e8e29c8cec", "metadataForms.action.fields.description.label": "779a4342c8eb6707", "metadataForms.action.fields.mode.label": "74dde5013435abdc", + "metadataForms.action.fields.refusals.message.label": "2af15199795c25b9", + "metadataForms.action.fields.refusals.reasons.message.label": "2af15199795c25b9", "metadataForms.action.fields.texts.message.label": "2af15199795c25b9", "metadataForms.action.fields.type.label": "901bb552898b2cab", "metadataForms.action.fields.visible.label": "7f733614bc9cea97", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 293c8f77095..bd8e14e3b95 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const jaJPMetadataForms: NonNullable = label: "メモリ(MB)", helpText: "呼び出しごとのメモリ上限(MB、最大 256)" }, + refusals: { + label: "拒否カタログ", + helpText: "アクションの本文がスローする SCREAMING_SNAKE のコード(例: SIGN_IN_REQUIRED)をキーとする拒否カタログ。呼び出し元には宣言したメッセージ(その言語に翻訳)と宣言したステータスが返ります。script アクションの JavaScript(L2)本文で使用可能。expression 本文では拒否されます" + }, + "refusals.message": { + label: "メッセージ", + helpText: "本体がこのコードをスローしたときにユーザーが読む文。プレーンテキスト。ただしエントリが params を宣言している場合、{{ name }} プレースホルダーに宣言済みのパラメーターが入ります" + }, + "refusals.status": { + label: "ステータス", + helpText: "拒否の HTTP ステータス(400–499)。未指定: 400" + }, + "refusals.reasons": { + label: "理由", + helpText: "同じコードの下に置く追加の文。本体がコードと一緒にスローする snake_case の理由({ code, reason })をキーとします。送信されるコードとステータスはこのエントリのものです。ここで宣言されていない理由は拒否されます。未指定: スローされた理由は読まれません" + }, + "refusals.reasons.message": { + label: "メッセージ", + helpText: "本体がこのコードの下でこの理由をスローしたときにユーザーが読む文。{{ }} プレースホルダーはエントリの params に従います" + }, + "refusals.params": { + label: "パラメーター", + helpText: "文に埋め込める名前(例: state)。本体が { code, params: { state } } をスローすると、{{ state }} プレースホルダーにその値が表示されます。未指定: 文はプレーンテキストです" + }, texts: { label: "テキスト", helpText: "アクションがレコードに書き込む文。本文が ctx.text で要求する snake_case のキー(例: email_subject)をキーとします。本文には宣言したメッセージが組織の言語に翻訳されて返り、翻訳がない場合は宣言したメッセージが返ります。script アクションの JavaScript(L2)本文で使用可能。expression 本文では拒否されます" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index c42918c97f0..40b1cc97e17 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const koMetadataForms: NonNullable = { label: "메모리(MB)", helpText: "호출당 메모리 상한(MB, 최대 256)" }, + refusals: { + label: "거부", + helpText: "작업 본문이 던지는 SCREAMING_SNAKE 코드(예: SIGN_IN_REQUIRED)를 키로 하는 거부 카탈로그입니다. 호출자는 선언된 메시지를 자신의 언어로 번역해 선언된 상태와 함께 읽습니다. script 작업의 JavaScript(L2) 본문용이며, expression 본문에서는 거부됩니다" + }, + "refusals.message": { + label: "메시지", + helpText: "본문이 이 코드를 던질 때 사용자가 읽는 문장입니다. 일반 텍스트이며, 항목이 params를 선언하면 {{ name }} 자리 표시자에 선언된 매개변수가 채워집니다" + }, + "refusals.status": { + label: "상태", + helpText: "거부의 HTTP 상태(400–499)입니다. 없으면 400" + }, + "refusals.reasons": { + label: "사유", + helpText: "같은 코드 아래의 추가 문장으로, 본문이 코드와 함께 던지는 snake_case 사유({ code, reason })를 키로 합니다. 전송되는 코드와 상태는 이 항목의 것을 따릅니다. 여기에 선언되지 않은 사유는 거부됩니다. 없으면 던진 사유를 읽지 않습니다" + }, + "refusals.reasons.message": { + label: "메시지", + helpText: "본문이 이 코드 아래에서 이 사유를 던질 때 사용자가 읽는 문장입니다. {{ }} 자리 표시자는 항목의 params를 따릅니다" + }, + "refusals.params": { + label: "매개변수", + helpText: "문장에 채울 수 있는 이름(예: state)입니다. 본문이 { code, params: { state } }를 던지면 {{ state }} 자리 표시자에 그 값이 표시됩니다. 없으면 문장은 일반 텍스트입니다" + }, texts: { label: "텍스트", helpText: "작업이 레코드에 쓰는 문장으로, 본문이 ctx.text로 요청하는 snake_case 키(예: email_subject)를 키로 합니다. 본문은 선언된 메시지를 조직의 언어로 번역해 받으며, 번역이 없으면 선언된 메시지를 받습니다. script 작업의 JavaScript(L2) 본문용이며, expression 본문에서는 거부됩니다" diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index ba93c71a8d3..ba33b396b50 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1292,7 +1292,9 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 747 since #35096: the action form offers the `texts` record and its // `message` / `params` entry fields — three row labels, authored in all // three locales. - expect(translated.length, `${locale} positive control`).toBe(747); + // 753 since #34823: the action form offers the `refusals` record and its + // five entry fields — six row labels, authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(753); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index 17cd2f7ea80..6d9f813ef9f 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const ptBRMetadataForms: NonNullable = label: "Memória (MB)", helpText: "Limite de memória por invocação (MB, máx. 256)" }, + refusals: { + label: "Recusas", + helpText: "Catálogo de recusas, indexado pelo código SCREAMING_SNAKE que o corpo da ação lança (por exemplo SIGN_IN_REQUIRED). O chamador lê a mensagem declarada, traduzida para o idioma dele, com o status declarado. Para o corpo JavaScript (L2) de uma ação script; recusado em um corpo de expressão" + }, + "refusals.message": { + label: "Mensagem", + helpText: "A frase que o usuário lê quando o corpo lança este código. Texto simples, a menos que a entrada declare params: então um marcador {{ name }} é preenchido com um parâmetro declarado" + }, + "refusals.status": { + label: "Status", + helpText: "Status HTTP da recusa (400–499). Ausente: 400" + }, + "refusals.reasons": { + label: "Motivos", + helpText: "Outras frases sob este mesmo código, indexadas pelo motivo snake_case que o corpo lança junto com o código ({ code, reason }). O código e o status enviados continuam sendo os desta entrada; um motivo não declarado aqui é recusado. Ausente: um motivo lançado não é lido" + }, + "refusals.reasons.message": { + label: "Mensagem", + helpText: "A frase que o usuário lê quando o corpo lança este motivo sob o código. Seus marcadores {{ }} seguem os params da entrada" + }, + "refusals.params": { + label: "Parâmetros", + helpText: "Nomes que as frases podem preencher (por exemplo state): o corpo lança { code, params: { state } } e um marcador {{ state }} mostra o valor. Ausente: as frases são texto simples" + }, texts: { label: "Textos", helpText: "Frases que a ação escreve nos registros, indexadas pela chave snake_case que o corpo dela pede com ctx.text (por exemplo email_subject). O corpo recebe a mensagem declarada no idioma da organização, traduzida, com a mensagem declarada como alternativa. Para o corpo JavaScript (L2) de uma ação script; recusado em um corpo de expressão" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index c86d9109f75..9c13fe5b331 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -19,6 +19,7 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.action.fields.patch.label": "815f68570a78eba1", + "metadataForms.action.fields.refusals.status.label": "64a420165247654b", "metadataForms.agent.fields.avatar.label": "0f06369995b69b8b", "metadataForms.dashboard.fields.widgets.label": "bd4bf82396edd638", "metadataForms.dashboard.sections.layout.label": "7f508ea1bb2c3a6b", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index b965f08eb5d..d9020d5f148 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const ruMetadataForms: NonNullable = { label: "Память (МБ)", helpText: "Ограничение памяти на вызов (МБ, максимум 256)" }, + refusals: { + label: "Отказы", + helpText: "Каталог отказов с ключами — кодами SCREAMING_SNAKE, которые выбрасывает тело действия (например, SIGN_IN_REQUIRED). Вызывающий получает объявленное сообщение в переводе на свой язык и с объявленным статусом. Для тела JavaScript (L2) действия script; для тела-выражения отклоняется" + }, + "refusals.message": { + label: "Сообщение", + helpText: "Фраза, которую видит пользователь, когда тело выбрасывает этот код. Простой текст, если запись не объявляет params: тогда заполнитель {{ name }} подставляет объявленный параметр" + }, + "refusals.status": { + label: "Статус", + helpText: "HTTP-статус отказа (400–499). Если отсутствует: 400" + }, + "refusals.reasons": { + label: "Причины", + helpText: "Дополнительные фразы под тем же кодом с ключами — причинами в snake_case, которые тело выбрасывает вместе с кодом ({ code, reason }). Передаваемые код и статус остаются от этой записи; причина, не объявленная здесь, отклоняется. Если отсутствует: выброшенная причина не читается" + }, + "refusals.reasons.message": { + label: "Сообщение", + helpText: "Фраза, которую видит пользователь, когда тело выбрасывает эту причину под этим кодом. Её заполнители {{ }} следуют params записи" + }, + "refusals.params": { + label: "Параметры", + helpText: "Имена, которые могут заполнять фразы (например, state): тело выбрасывает { code, params: { state } }, и заполнитель {{ state }} показывает значение. Если отсутствует: фразы — простой текст" + }, texts: { label: "Тексты", helpText: "Фразы, которые действие записывает в записи, с ключами в snake_case, которые его тело запрашивает через ctx.text (например, email_subject). Тело получает объявленное сообщение в переводе на язык организации, а без перевода — само объявленное сообщение. Для тела JavaScript (L2) действия script; для тела-выражения отклоняется" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index ff89390b908..3d427ef4bc8 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const zhCNMetadataForms: NonNullable = label: "内存(MB)", helpText: "单次调用内存上限(MB,最大 256)" }, + refusals: { + label: "拒绝目录", + helpText: "拒绝目录,以操作正文抛出的 SCREAMING_SNAKE 错误码为键(例如 SIGN_IN_REQUIRED)。调用方读到声明的提示语(按其语言翻译)和声明的状态码。适用于 script 操作的 JavaScript(L2)正文;表达式正文声明会被拒绝" + }, + "refusals.message": { + label: "提示语", + helpText: "正文抛出此错误码时用户读到的句子。纯文本;若该条目声明了参数,则 {{ name }} 占位符填入一个已声明的参数" + }, + "refusals.status": { + label: "状态码", + helpText: "拒绝的 HTTP 状态码(400–499)。不填:400" + }, + "refusals.reasons": { + label: "原因", + helpText: "同一错误码下的更多句子,以正文在错误码旁抛出的 snake_case 原因为键({ code, reason })。线上的错误码和状态码仍取本条目的;未在此声明的原因会被拒绝。不填:抛出的原因不被读取" + }, + "refusals.reasons.message": { + label: "提示语", + helpText: "正文在此错误码下抛出此原因时用户读到的句子。其中的 {{ }} 占位符遵循本条目的参数" + }, + "refusals.params": { + label: "参数", + helpText: "句子可填入的名称(例如 state):正文抛出 { code, params: { state } },{{ state }} 占位符即显示该值。不填:句子为纯文本" + }, texts: { label: "文本", helpText: "操作写入记录的句子,以其正文通过 ctx.text 请求的 snake_case 键为键(例如 email_subject)。正文得到按组织语言翻译的声明句子,无翻译时回退为声明的句子。适用于 script 操作的 JavaScript(L2)正文;表达式正文声明会被拒绝" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 005ecee258e..2875fa9f66c 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -1893,6 +1893,30 @@ export const zhHantMetadataForms: NonNullable label: "記憶體(MB)", helpText: "單次呼叫記憶體上限(MB,最大 256)" }, + refusals: { + label: "拒絕目錄", + helpText: "拒絕目錄,以操作內文丟擲的 SCREAMING_SNAKE 錯誤碼為鍵(例如 SIGN_IN_REQUIRED)。呼叫方讀到宣告的提示語(依其語言翻譯)和宣告的狀態碼。適用於 script 操作的 JavaScript(L2)內文;運算式內文宣告會被拒絕" + }, + "refusals.message": { + label: "提示語", + helpText: "內文丟擲此錯誤碼時使用者讀到的句子。純文字;若該條目宣告了參數,則 {{ name }} 預留位置填入一個已宣告的參數" + }, + "refusals.status": { + label: "狀態碼", + helpText: "拒絕的 HTTP 狀態碼(400–499)。不填:400" + }, + "refusals.reasons": { + label: "原因", + helpText: "同一錯誤碼下的更多句子,以內文在錯誤碼旁丟擲的 snake_case 原因為鍵({ code, reason })。線上的錯誤碼和狀態碼仍取本條目的;未在此宣告的原因會被拒絕。不填:丟擲的原因不被讀取" + }, + "refusals.reasons.message": { + label: "提示語", + helpText: "內文在此錯誤碼下丟擲此原因時使用者讀到的句子。其中的 {{ }} 預留位置遵循本條目的參數" + }, + "refusals.params": { + label: "參數", + helpText: "句子可填入的名稱(例如 state):內文丟擲 { code, params: { state } },{{ state }} 預留位置即顯示該值。不填:句子為純文字" + }, texts: { label: "文字", helpText: "操作寫入記錄的句子,以其內文透過 ctx.text 請求的 snake_case 鍵為鍵(例如 email_subject)。內文取得依組織語言翻譯的宣告句子,無翻譯時退回宣告的句子。適用於 script 操作的 JavaScript(L2)內文;運算式內文宣告會被拒絕" From ef816f88a6242dbe88b564ba58ce1c5acdd27ad0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 20:15:52 +0000 Subject: [PATCH 13/17] test(lint): the shipped-forms predicate census counts the action texts and refusals gates The two new action form rows are each gated on data.type == 'script', so the shipped-predicate pin moves 91 to 93 and the literal-comparison pin 65 to 67 (on main as of 5c5b54d3, merged in the previous commit). Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC --- packages/lint/src/validate-predicate-path-refs.test.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/lint/src/validate-predicate-path-refs.test.ts b/packages/lint/src/validate-predicate-path-refs.test.ts index 8d38546b7e9..32b1a46de94 100644 --- a/packages/lint/src/validate-predicate-path-refs.test.ts +++ b/packages/lint/src/validate-predicate-path-refs.test.ts @@ -699,7 +699,10 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // It is 91 today, an ADDITION of ONE: #29462 offered the field form's // `referenceNameVisible` row, gated on `data.type in ['lookup','user']`. It // is an in-list, so it does not reach the literal-comparison census below. - expect(predicates, 'the shipped metadata forms carry no predicates at all').toBe(91); + // It is 93 today, an ADDITION of TWO: #35096 and #34823 offered the action + // form's `texts` and `refusals` rows, each gated like `body` on + // `data.type == 'script'`. They reach the literal-comparison census below. + expect(predicates, 'the shipped metadata forms carry no predicates at all').toBe(93); const findings = validatePredicatePathRefs(corrupted); expect(findings).toHaveLength(predicates); @@ -827,7 +830,10 @@ describe('#7010 corpus — shipped METADATA_FORM_REGISTRY', () => { // It is 65 today: #35047's `field :: percentDisplay` gate also opens for a // percent formula, `data.type == 'formula' && data.returnType == 'percent'`, // two more single-quoted literal comparisons. - expect(comparisons, 'no shipped predicate carries an `==`/`!=` literal comparison').toBe(65); + // It is 67 today: #35096's `action :: texts` and #34823's + // `action :: refusals` rows are each gated on `data.type == 'script'`, two + // single-quoted literal comparisons. + expect(comparisons, 'no shipped predicate carries an `==`/`!=` literal comparison').toBe(67); const rhsFindings = validatePredicatePathRefs(corrupted) .filter((f) => f.rule === PREDICATE_RHS_PATH_SHAPED); From d821bb82bd618301383c721ea22164270a1c3fed Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 21:58:59 +0000 Subject: [PATCH 14/17] fix(spec): the save door's literal ctx.text reader also reads ctx.text?.( and ctx.text!( Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook-refusal-codes.ts | 19 ++++++++----- packages/spec/src/data/hook-texts.test.ts | 28 ++++++++++++++++++++ packages/spec/src/data/hook.zod.ts | 8 +++--- packages/spec/src/ui/action-texts.test.ts | 22 +++++++++++++++ packages/spec/src/ui/action.zod.ts | 3 ++- 5 files changed, 70 insertions(+), 10 deletions(-) diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 0c2d935587f..b86ed8f7aab 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -423,8 +423,9 @@ function undeclaredRefusalReasonAtRun( * (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. + * LITERALLY — `ctx.text('key'`, `ctx.text?.('key'` or `ctx.text!('key'` — and + * `texts` does not declare is refused at save ({@link hookTextKeysAskedIn}); + * any other key is refused when the hook runs. */ /** @@ -433,15 +434,21 @@ function undeclaredRefusalReasonAtRun( */ 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. */ +/** + * `ctx.text('key'` — the call a hook's code asks for a declared text with — and + * its optional-call `ctx.text?.('key'` and non-null `ctx.text!('key'` shapes, + * which strict TypeScript reaches for because `HookContext.text` is optional. + * All three ask for the key literally. A `!` on the next line is not the + * non-null shape (it ends the statement), so it is read only on the same line. + */ const TEXT_CALL = new RegExp( - String.raw`(?['"\x60])(?[a-z][a-z0-9]*(?:_[a-z0-9]+)*)\k`, + 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 + * The text keys a hook's source asks for LITERALLY — `ctx.text('key', …)`, + * `ctx.text?.('key', …)` or `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. */ diff --git a/packages/spec/src/data/hook-texts.test.ts b/packages/spec/src/data/hook-texts.test.ts index 893fe0b3e19..d677d430821 100644 --- a/packages/spec/src/data/hook-texts.test.ts +++ b/packages/spec/src/data/hook-texts.test.ts @@ -105,6 +105,34 @@ describe('Hook.texts — a key the source asks for literally is refused at save expect(hookTextKeysAskedIn(source)).toEqual(['follow_up_subject']); }); + // The optional-call and non-null call shapes are literal asks too: strict + // TypeScript reaches for them once `HookContext.text` is optional. + const SHAPES = [ + ['ctx.text?.(', (k: string) => `ctx.text?.('${k}')`], + ['await ctx.text?.(', (k: string) => `await ctx.text?.('${k}', { lead: ctx.input.name })`], + ['ctx.text!(', (k: string) => `ctx.text!('${k}')`], + ['await ctx.text!(', (k: string) => `await ctx.text!('${k}', { lead: ctx.input.name })`], + ] as const; + + it.each(SHAPES)('refuses an undeclared key asked for as %s at save, with the same sentence', (_shape, ask) => { + const r = HookSchema.safeParse({ ...base, body: body(`const s = ${ask('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.each(SHAPES)('CONTROL: a declared key asked for as %s, and a computed key in that shape, pass the save', (_shape, ask) => { + const computed = ask('follow_up_subject').replace("'follow_up_subject'", 'k'); + const source = `${ask('follow_up_subject')};\nconst k = pick(); ${computed};`; + expect(HookSchema.safeParse({ ...base, body: body(source), texts }).success).toBe(true); + expect(hookTextKeysAskedIn(source)).toEqual(['follow_up_subject']); + }); + + it('reads the shapes with whitespace around the operator; CONTROL: a `!` on the next line ends the statement and is not read', () => { + expect(hookTextKeysAskedIn("ctx.text ?. ('a_key'); ctx.text !('b_key');")).toEqual(['a_key', 'b_key']); + expect(hookTextKeysAskedIn("ctx.text\n!('c_key');")).toEqual([]); + }); + 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/); diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 49b2f0174c7..861b9113d0d 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -816,7 +816,8 @@ export const HookSchema = lazySchema(() => strictObject( * 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 + * — `ctx.text('key')`, `ctx.text?.('key')` or `ctx.text!('key')` — 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 @@ -1939,8 +1940,9 @@ export const HookContextSchema = lazySchema(() => z.object({ * * The runtime binds it on every path a hook runs on — a sandboxed `js` body * and an in-process `handler` (`buildHookTextSurface`). The save-time check - * reads the literal spelling `ctx.text('key'`, so a key asked for through - * an alias or a computed name is only judged when the hook runs. + * reads the literal spellings `ctx.text('key'`, `ctx.text?.('key'` and + * `ctx.text!('key'`, so a key asked for through an alias or a computed name + * is only judged when the hook runs. * * Runtime-only, like {@link api} and {@link notice}: a live function, so the * RUNTIME schema is `z.unknown()` (JSON Schema `{}`) and the type is a static diff --git a/packages/spec/src/ui/action-texts.test.ts b/packages/spec/src/ui/action-texts.test.ts index 0b430117784..6e2952ff2c2 100644 --- a/packages/spec/src/ui/action-texts.test.ts +++ b/packages/spec/src/ui/action-texts.test.ts @@ -130,6 +130,28 @@ describe('Action.texts — a key the body asks for literally is refused at save expect(ActionSchema.safeParse({ ...base, body: body(source), texts: TEXTS }).success).toBe(true); }); + // The optional-call and non-null call shapes are literal asks too, read by + // the one key reader the hook door shares. + const SHAPES = [ + ['ctx.text?.(', (k: string) => `ctx.text?.('${k}')`], + ['await ctx.text?.(', (k: string) => `await ctx.text?.('${k}', { subject: input.subject })`], + ['ctx.text!(', (k: string) => `ctx.text!('${k}')`], + ['await ctx.text!(', (k: string) => `await ctx.text!('${k}', { subject: input.subject })`], + ] as const; + + it.each(SHAPES)('refuses an undeclared key asked for as %s at save, with the same sentence', (_shape, ask) => { + const r = ActionSchema.safeParse({ ...base, body: body(`const line = ${ask('email_body')};`), texts: TEXTS }); + expect(r.success).toBe(false); + const issue = issuesOf(r).find((i) => i.path.join('.') === 'body.source')!; + expect(issue.message).toBe(undeclaredActionTextKeyAtSave('email_body', ['email_subject'])); + }); + + it.each(SHAPES)('CONTROL: a declared key asked for as %s, and a computed key in that shape, pass the save', (_shape, ask) => { + const computed = ask('email_subject').replace("'email_subject'", 'k'); + const source = `${ask('email_subject')};\nconst k = pick(); ${computed};`; + expect(ActionSchema.safeParse({ ...base, body: body(source), texts: TEXTS }).success).toBe(true); + }); + it('CONTROL: an action that declares no texts is not read for ctx.text calls (the run-time fault names it)', () => { expect(ActionSchema.safeParse({ ...base, body: body("await ctx.text('anything');") }).success).toBe(true); expect(undeclaredActionTextAtRun('send_email', 'anything', [])).toMatch(/^action 'send_email' asked for text 'anything'.*declared: none/); diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index bd2687980dc..245fe8989bb 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -1572,7 +1572,8 @@ const actionObject = () => strictObject({ * rejects the call. A string the body builds itself is written as it is * (parameter 4). * - * A key the body asks for literally that `texts` does not declare is + * A key the body asks for literally that `texts` does not declare — + * `ctx.text('key')`, `ctx.text?.('key')` or `ctx.text!('key')` — is * refused at save; any other undeclared key is refused when the action * runs, as a fault naming the action and the key. Served where an action * runs code of its own: a `type: 'script'` action's sandboxed `js` body — From 2a7c8c927a2d15e040da29f199be628727d4ddf4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:01:03 +0000 Subject: [PATCH 15/17] fix(spec): register the narrowing and add its changeset Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .changeset/35512-text-call-shapes.md | 18 +++++++++++ ...k-action-text-key-optional-call-refused.ts | 30 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 .changeset/35512-text-call-shapes.md create mode 100644 packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts diff --git a/.changeset/35512-text-call-shapes.md b/.changeset/35512-text-call-shapes.md new file mode 100644 index 00000000000..ebb3622a6b8 --- /dev/null +++ b/.changeset/35512-text-call-shapes.md @@ -0,0 +1,18 @@ +--- +'@objectstack/spec': minor +--- + +fix(spec): the save door refuses an undeclared text key asked for as `ctx.text?.('k')` or `ctx.text!('k')`, as it already did for `ctx.text('k')` + +Clause-②: no (narrowing) +Metadata-protocol: narrowed + +**BREAKING** for a hook or a `type: 'script'` action that declares `texts` and whose code asks for a key `texts` does not declare through the optional-call or non-null shape. + +- FROM: `HookSchema` and `ActionSchema` refused a key asked for literally and not declared in `texts` only for the plain call `ctx.text('k')`. `await ctx.text?.('k')`, `ctx.text?.('k')`, `await ctx.text!('k')` and `ctx.text!('k')` with an undeclared key parsed green, and the runtime refused the key only when the hook or action ran. +- TO: each of those shapes is refused at save with the sentence the plain call already gets, at `body.source` (or `handler` for an in-process hook handler). Whitespace around the operator is read too (`ctx.text ?. ('k')`, `ctx.text !('k')`); a `!` on the next line ends the statement and is not a call. +- Fix: declare the key under `texts.KEY` with the sentence the record keeps, or ask for one of the declared keys. A declared key is accepted in every shape. + +A key that arrives any other way (a variable, a computed name) is still judged when the code runs. + + diff --git a/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts b/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts new file mode 100644 index 00000000000..0692ae841c1 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts @@ -0,0 +1,30 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// The D3 entry for the save door's literal `ctx.text` reader reading the +// optional-call `ctx.text?.('key')` and non-null `ctx.text!('key')` shapes +// (ruling 6913660232 parameter 7: a key asked for literally that `texts` does +// not declare is refused at save). It narrows the hook's and the action's +// accept set; no key is removed, so there is no tombstone and no D2 +// conversion: which sentence the author meant is a judgement about the hook. +export const entry: SemanticMigration = { + id: 'hook-action-text-key-optional-call-refused', + surface: + 'hook.body.source / hook.handler and action.body.source on a hook or a type: script action that declares ' + + 'texts: a literal ctx.text?.(KEY) or ctx.text!(KEY) call, awaited or not, whose KEY texts does not declare', + replacement: + 'Declare the key under texts.KEY with the sentence the record keeps, or ask for one of the declared keys. ' + + 'The call shape is unchanged: ctx.text?.(KEY) and ctx.text!(KEY) stay legal for a declared key.', + reason: + 'A key a hook or an action asks for literally that its texts does not declare was refused at save only for ' + + 'the plain call ctx.text(KEY). The optional-call and non-null shapes, which strict TypeScript reaches for ' + + 'because HookContext.text is optional, passed the save, and the runtime refused the key only when the code ' + + 'ran, as a fault naming the hook or action and the key. The save now refuses them with the same sentence, ' + + 'at body.source (or handler). A key that arrives any other way (a variable, a computed name) is still ' + + 'judged when the code runs. There is no mechanical rewrite: the code already failed at run time for that ' + + 'key, and whether to declare it or ask for another is a judgement about the sentence.', + acceptanceCriteria: + 'objectstack validate reports no issue at body.source or handler for any hook or action that declares texts, ' + + 'and every key its code asks for through ctx.text, ctx.text?.( or ctx.text!( is a key of its texts.', +}; From 269566b8c479ac1c9192593eee89ef8904a88bdd Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:07:21 +0000 Subject: [PATCH 16/17] docs(spec): rewrap the key reader's TSDoc Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- packages/spec/src/data/hook-refusal-codes.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index b86ed8f7aab..502c37b1891 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -448,8 +448,9 @@ const TEXT_CALL = new RegExp( /** * The text keys a hook's source asks for LITERALLY — `ctx.text('key', …)`, - * `ctx.text?.('key', …)` or `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. + * `ctx.text?.('key', …)` or `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[] { From 0acd17d22771e033de2fe8233b64433119c187ff Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:03:21 +0000 Subject: [PATCH 17/17] fix(spec): drop the non-null ctx.text arm; pin the handler optional call; docs name ctx.text?.( Claude-Session: https://claude.ai/code/session_01L6bhgX6mQpVU8yUysiRAFC Co-authored-by: Claude --- .changeset/35512-text-call-shapes.md | 10 +++--- content/docs/automation/hooks.mdx | 5 +-- packages/spec/src/data/hook-refusal-codes.ts | 23 ++++++------ packages/spec/src/data/hook-texts.test.ts | 23 ++++++++---- packages/spec/src/data/hook.zod.ts | 16 ++++----- ...k-action-text-key-optional-call-refused.ts | 36 ++++++++++--------- packages/spec/src/ui/action-texts.test.ts | 7 ++-- packages/spec/src/ui/action.zod.ts | 9 +++-- 8 files changed, 71 insertions(+), 58 deletions(-) diff --git a/.changeset/35512-text-call-shapes.md b/.changeset/35512-text-call-shapes.md index ebb3622a6b8..b084e4a66de 100644 --- a/.changeset/35512-text-call-shapes.md +++ b/.changeset/35512-text-call-shapes.md @@ -2,16 +2,16 @@ '@objectstack/spec': minor --- -fix(spec): the save door refuses an undeclared text key asked for as `ctx.text?.('k')` or `ctx.text!('k')`, as it already did for `ctx.text('k')` +fix(spec): the save door refuses an undeclared text key asked for as `ctx.text?.('k')`, as it already did for `ctx.text('k')` Clause-②: no (narrowing) Metadata-protocol: narrowed -**BREAKING** for a hook or a `type: 'script'` action that declares `texts` and whose code asks for a key `texts` does not declare through the optional-call or non-null shape. +**BREAKING** for a hook that declares `texts` and whose code asks for a key `texts` does not declare through the optional call `ctx.text?.('k')`. Action `texts` is read the same way from the release that introduces it, so no released action is affected. -- FROM: `HookSchema` and `ActionSchema` refused a key asked for literally and not declared in `texts` only for the plain call `ctx.text('k')`. `await ctx.text?.('k')`, `ctx.text?.('k')`, `await ctx.text!('k')` and `ctx.text!('k')` with an undeclared key parsed green, and the runtime refused the key only when the hook or action ran. -- TO: each of those shapes is refused at save with the sentence the plain call already gets, at `body.source` (or `handler` for an in-process hook handler). Whitespace around the operator is read too (`ctx.text ?. ('k')`, `ctx.text !('k')`); a `!` on the next line ends the statement and is not a call. -- Fix: declare the key under `texts.KEY` with the sentence the record keeps, or ask for one of the declared keys. A declared key is accepted in every shape. +- FROM: `HookSchema` refused a key asked for literally and not declared in `texts` only for the plain call `ctx.text('k')`. `ctx.text?.('k')` and `await ctx.text?.('k')` with an undeclared key parsed green, and the runtime refused the key only when the hook ran. +- TO: the optional call is refused at save with the sentence the plain call already gets, at `body.source` for a `js` body or at `handler` for an in-process handler. Whitespace or a line break around `?.` is read too. +- Fix: declare the key under `texts.KEY` with the sentence the record keeps, or ask for one of the declared keys. A declared key is accepted in both shapes. A key that arrives any other way (a variable, a computed name) is still judged when the code runs. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index eea8c232784..b18e975b6ac 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -497,8 +497,9 @@ export const leadFollowUp = { 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. + saved if the hook names it literally in `ctx.text('key')` or + `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. diff --git a/packages/spec/src/data/hook-refusal-codes.ts b/packages/spec/src/data/hook-refusal-codes.ts index 502c37b1891..c61afafd781 100644 --- a/packages/spec/src/data/hook-refusal-codes.ts +++ b/packages/spec/src/data/hook-refusal-codes.ts @@ -423,9 +423,9 @@ function undeclaredRefusalReasonAtRun( * (parameter 4). * * The same two halves as a refusal code: a key the hook's source asks for - * LITERALLY — `ctx.text('key'`, `ctx.text?.('key'` or `ctx.text!('key'` — and - * `texts` does not declare is refused at save ({@link hookTextKeysAskedIn}); - * any other key is refused when the hook runs. + * LITERALLY — `ctx.text('key'` or `ctx.text?.('key'` — and `texts` does not + * declare is refused at save ({@link hookTextKeysAskedIn}); any other key is + * refused when the hook runs. */ /** @@ -436,19 +436,22 @@ 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 — and - * its optional-call `ctx.text?.('key'` and non-null `ctx.text!('key'` shapes, - * which strict TypeScript reaches for because `HookContext.text` is optional. - * All three ask for the key literally. A `!` on the next line is not the - * non-null shape (it ends the statement), so it is read only on the same line. + * its optional-call shape `ctx.text?.('key'`, which strict TypeScript reaches + * for because `HookContext.text` is optional. Both ask for the key literally. + * + * A non-null `ctx.text!('key'` is not read: it is TypeScript with no + * JavaScript form. A handler's `!` is erased before the save reads + * `Function.prototype.toString()`, so it arrives as the plain call; in a `js` + * body it is a syntax error, and the body never runs. */ const TEXT_CALL = new RegExp( - String.raw`(?['"\x60])(?[a-z][a-z0-9]*(?:_[a-z0-9]+)*)\k`, + 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', …)`, - * `ctx.text?.('key', …)` or `ctx.text!('key', …)` — in first-seen order: + * The text keys a hook's source asks for LITERALLY — `ctx.text('key', …)` or + * `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. diff --git a/packages/spec/src/data/hook-texts.test.ts b/packages/spec/src/data/hook-texts.test.ts index d677d430821..65c2583c7c4 100644 --- a/packages/spec/src/data/hook-texts.test.ts +++ b/packages/spec/src/data/hook-texts.test.ts @@ -105,13 +105,11 @@ describe('Hook.texts — a key the source asks for literally is refused at save expect(hookTextKeysAskedIn(source)).toEqual(['follow_up_subject']); }); - // The optional-call and non-null call shapes are literal asks too: strict - // TypeScript reaches for them once `HookContext.text` is optional. + // The optional-call shape is a literal ask too: strict TypeScript reaches for + // it once `HookContext.text` is optional. const SHAPES = [ ['ctx.text?.(', (k: string) => `ctx.text?.('${k}')`], ['await ctx.text?.(', (k: string) => `await ctx.text?.('${k}', { lead: ctx.input.name })`], - ['ctx.text!(', (k: string) => `ctx.text!('${k}')`], - ['await ctx.text!(', (k: string) => `await ctx.text!('${k}', { lead: ctx.input.name })`], ] as const; it.each(SHAPES)('refuses an undeclared key asked for as %s at save, with the same sentence', (_shape, ask) => { @@ -128,9 +126,20 @@ describe('Hook.texts — a key the source asks for literally is refused at save expect(hookTextKeysAskedIn(source)).toEqual(['follow_up_subject']); }); - it('reads the shapes with whitespace around the operator; CONTROL: a `!` on the next line ends the statement and is not read', () => { - expect(hookTextKeysAskedIn("ctx.text ?. ('a_key'); ctx.text !('b_key');")).toEqual(['a_key', 'b_key']); - expect(hookTextKeysAskedIn("ctx.text\n!('c_key');")).toEqual([]); + it('reads the optional call with whitespace or a line break around the operator', () => { + expect(hookTextKeysAskedIn("ctx.text ?. ('a_key'); ctx.text\n ?.('b_key');")).toEqual(['a_key', 'b_key']); + }); + + it('refuses an inline handler asking ctx.text?.() for an undeclared key, at handler (the strict-TypeScript case)', () => { + const handler = async (ctx: any) => { await ctx.text?.('follow_up_title'); }; + const r = HookSchema.safeParse({ ...base, handler, texts }); + expect(r.success).toBe(false); + const issue = r.error!.issues.find((i) => i.path.join('.') === 'handler')!; + expect(issue.message).toBe(undeclaredHookTextKeyAtSave('follow_up_title', ['follow_up_subject'], 'handler')); + }); + + it('does not read a non-null ctx.text!() — TypeScript only: a handler reaches the save with the `!` erased, and a js body holding it never compiles', () => { + expect(hookTextKeysAskedIn("ctx.text!('a_key');")).toEqual([]); }); it('a hook that declares no texts is not read for ctx.text calls (the run-time fault names it)', () => { diff --git a/packages/spec/src/data/hook.zod.ts b/packages/spec/src/data/hook.zod.ts index 861b9113d0d..22e986432ab 100644 --- a/packages/spec/src/data/hook.zod.ts +++ b/packages/spec/src/data/hook.zod.ts @@ -337,8 +337,9 @@ 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. + * (`ctx.text('key')` or `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: { @@ -816,9 +817,8 @@ export const HookSchema = lazySchema(() => strictObject( * hook builds itself is written as it is (parameter 4). * * A key the hook's source asks for literally that `texts` does not declare - * — `ctx.text('key')`, `ctx.text?.('key')` or `ctx.text!('key')` — 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 + * — `ctx.text('key')` or `ctx.text?.('key')` — 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. @@ -1940,9 +1940,9 @@ export const HookContextSchema = lazySchema(() => z.object({ * * The runtime binds it on every path a hook runs on — a sandboxed `js` body * and an in-process `handler` (`buildHookTextSurface`). The save-time check - * reads the literal spellings `ctx.text('key'`, `ctx.text?.('key'` and - * `ctx.text!('key'`, so a key asked for through an alias or a computed name - * is only judged when the hook runs. + * reads the literal spellings `ctx.text('key'` and `ctx.text?.('key'`, so a + * key asked for through an alias or a computed name is only judged when the + * hook runs. * * Runtime-only, like {@link api} and {@link notice}: a live function, so the * RUNTIME schema is `z.unknown()` (JSON Schema `{}`) and the type is a static diff --git a/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts b/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts index 0692ae841c1..bde170bccf7 100644 --- a/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts +++ b/packages/spec/src/migrations/entries/semantic/18.hook-action-text-key-optional-call-refused.ts @@ -3,28 +3,30 @@ import type { SemanticMigration } from '../../types.js'; // The D3 entry for the save door's literal `ctx.text` reader reading the -// optional-call `ctx.text?.('key')` and non-null `ctx.text!('key')` shapes -// (ruling 6913660232 parameter 7: a key asked for literally that `texts` does -// not declare is refused at save). It narrows the hook's and the action's -// accept set; no key is removed, so there is no tombstone and no D2 -// conversion: which sentence the author meant is a judgement about the hook. +// optional-call shape `ctx.text?.('key')` (ruling 6913660232 parameter 7: a +// key asked for literally that `texts` does not declare is refused at save). +// It narrows the hook's accept set, the released half; the action half +// (`ActionSchema.texts`) ships already narrowed. No key is removed, so there is +// no tombstone and no D2 conversion: which sentence the author meant is a +// judgement about the hook. export const entry: SemanticMigration = { id: 'hook-action-text-key-optional-call-refused', surface: - 'hook.body.source / hook.handler and action.body.source on a hook or a type: script action that declares ' - + 'texts: a literal ctx.text?.(KEY) or ctx.text!(KEY) call, awaited or not, whose KEY texts does not declare', + 'hook.body.source / hook.handler on a hook that declares texts: a literal optional call ctx.text?.(KEY), ' + + 'awaited or not, whose KEY texts does not declare. A type: script action\'s body.source is read the same ' + + 'way from the release that introduces action texts, so no released action is affected', replacement: 'Declare the key under texts.KEY with the sentence the record keeps, or ask for one of the declared keys. ' - + 'The call shape is unchanged: ctx.text?.(KEY) and ctx.text!(KEY) stay legal for a declared key.', + + 'The optional call stays legal for a declared key.', reason: - 'A key a hook or an action asks for literally that its texts does not declare was refused at save only for ' - + 'the plain call ctx.text(KEY). The optional-call and non-null shapes, which strict TypeScript reaches for ' - + 'because HookContext.text is optional, passed the save, and the runtime refused the key only when the code ' - + 'ran, as a fault naming the hook or action and the key. The save now refuses them with the same sentence, ' - + 'at body.source (or handler). A key that arrives any other way (a variable, a computed name) is still ' - + 'judged when the code runs. There is no mechanical rewrite: the code already failed at run time for that ' - + 'key, and whether to declare it or ask for another is a judgement about the sentence.', + 'A key a hook asks for literally that its texts does not declare was refused at save only for the plain ' + + 'call ctx.text(KEY). The optional call ctx.text?.(KEY), which strict TypeScript reaches for because ' + + 'HookContext.text is optional, passed the save, and the runtime refused the key only when the hook ran, ' + + 'as a fault naming the hook and the key. The save now refuses it with the same sentence, at body.source ' + + 'or handler. A key that arrives any other way (a variable, a computed name) is still judged when the code ' + + 'runs. There is no mechanical rewrite: the hook already failed at run time for that key, and whether to ' + + 'declare it or ask for another is a judgement about the sentence.', acceptanceCriteria: - 'objectstack validate reports no issue at body.source or handler for any hook or action that declares texts, ' - + 'and every key its code asks for through ctx.text, ctx.text?.( or ctx.text!( is a key of its texts.', + 'objectstack validate reports no issue at body.source or handler for any hook that declares texts, and ' + + 'every key its code asks for through ctx.text or the optional call ctx.text?.( is a key of its texts.', }; diff --git a/packages/spec/src/ui/action-texts.test.ts b/packages/spec/src/ui/action-texts.test.ts index 6e2952ff2c2..f33373c8143 100644 --- a/packages/spec/src/ui/action-texts.test.ts +++ b/packages/spec/src/ui/action-texts.test.ts @@ -130,13 +130,12 @@ describe('Action.texts — a key the body asks for literally is refused at save expect(ActionSchema.safeParse({ ...base, body: body(source), texts: TEXTS }).success).toBe(true); }); - // The optional-call and non-null call shapes are literal asks too, read by - // the one key reader the hook door shares. + // The optional-call shape is a literal ask too, read by the one key reader + // the hook door shares. (An action's door reads `body.source` alone: it has + // no handler path.) const SHAPES = [ ['ctx.text?.(', (k: string) => `ctx.text?.('${k}')`], ['await ctx.text?.(', (k: string) => `await ctx.text?.('${k}', { subject: input.subject })`], - ['ctx.text!(', (k: string) => `ctx.text!('${k}')`], - ['await ctx.text!(', (k: string) => `await ctx.text!('${k}', { subject: input.subject })`], ] as const; it.each(SHAPES)('refuses an undeclared key asked for as %s at save, with the same sentence', (_shape, ask) => { diff --git a/packages/spec/src/ui/action.zod.ts b/packages/spec/src/ui/action.zod.ts index 245fe8989bb..e804106fe59 100644 --- a/packages/spec/src/ui/action.zod.ts +++ b/packages/spec/src/ui/action.zod.ts @@ -1573,9 +1573,8 @@ const actionObject = () => strictObject({ * (parameter 4). * * A key the body asks for literally that `texts` does not declare — - * `ctx.text('key')`, `ctx.text?.('key')` or `ctx.text!('key')` — is - * refused at save; any other undeclared key is refused when the action - * runs, as a fault naming the action and the key. Served where an action + * `ctx.text('key')` or `ctx.text?.('key')` — is refused at save; any other + * undeclared key is refused when the action runs, as a fault naming the action and the key. Served where an action * runs code of its own: a `type: 'script'` action's sandboxed `js` body — * which is also what `os build` lowers an inline `target` function to. * Refused on every other action: another `type` (its `target` is a URL, @@ -2659,8 +2658,8 @@ export type ActionText = z.input; * [#34374 PR2] The object-level check on an action's `texts`, the twin of * `HookSchema`'s: `texts` nothing the action runs could ask for is refused at * `texts`, and a key the body's source asks for literally - * (`ctx.text('key')`) that `texts` does not declare is refused at - * `body.source`, one issue each. A key that arrives any other way is the + * (`ctx.text('key')` or `ctx.text?.('key')`) that `texts` does not declare is + * refused at `body.source`, one issue each. A key that arrives any other way is the * run-time refusal's. */ function refuseUndeclaredLiteralActionTextKey(