Skip to content

Commit 1333fcf

Browse files
committed
wip(i18n): hook refusal catalogue — spec, runtime, cli and lint halves
Claude-Session: https://claude.ai/code/session_01WGufzfyVQuRsL6SRGuKCem Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4373103 commit 1333fcf

16 files changed

Lines changed: 858 additions & 25 deletions

‎packages/cli/src/utils/i18n-coverage.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export interface CoverageIssue {
7171
| 'picklist'
7272
| 'page'
7373
| 'flow'
74+
| 'hook'
7475
| 'position'
7576
| 'permission'
7677
| 'metadataForm';
@@ -377,6 +378,12 @@ const COVERAGE_SOURCE: Record<ExpectedEntry['source'], CoverageIssue['source']>
377378
// locales (#11485). Its six approval flows stayed that invisible until
378379
// #24916.
379380
flow: 'flow',
381+
// A hook's declared refusal messages (`hooks.<h>.refusals.<CODE>.message`,
382+
// #26170) — the sentence a user reads when the app says "not yet", so it
383+
// keeps its own bucket and reports as `i18n/missing-hook`. Until the
384+
// catalogue existed a hook refusal had no key at all, and the family reported
385+
// `0 missing` while a zh-CN user read every refusal in English.
386+
hook: 'hook',
380387
// Security-catalog copy (`positions.<p>.label` / `.description`,
381388
// `permissions.<s>.label` / `.description`) — the author's own positions and
382389
// permission sets, read in Setup and on every approval step that waits on a
@@ -406,6 +413,7 @@ const SOURCE_NOUN: Record<CoverageIssue['source'], string> = {
406413
picklist: 'Picklist',
407414
page: 'Page',
408415
flow: 'Flow',
416+
hook: 'Hook',
409417
position: 'Position',
410418
permission: 'Permission set',
411419
metadataForm: 'Metadata form',
@@ -451,6 +459,7 @@ const SOURCE_SURFACE: Record<CoverageIssue['source'], string> = {
451459
picklist: 'picklists',
452460
page: 'pages',
453461
flow: 'flow screens, approval steps, toasts and refusals',
462+
hook: 'hook refusals',
454463
position: 'positions',
455464
permission: 'permission sets',
456465
metadataForm: 'metadata forms',

‎packages/cli/src/utils/i18n-extract.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@
122122
* ^ walked because the ledger's `flows` row is `live` and warns no
123123
* author; a group the ledger does warn on is left out of the walk
124124
* (see `authorWarnedTranslationGroups`)
125+
* hooks.<hook>.refusals.<CODE>.message (#26170)
125126
* positions.<position>.label / .description
126127
* permissions.<permission_set>.label / .description
127128
* metadataForms.<type>.label / .description
@@ -228,6 +229,7 @@ export interface ExpectedEntry {
228229
| 'picklist'
229230
| 'page'
230231
| 'flow'
232+
| 'hook'
231233
| 'position'
232234
| 'permission'
233235
| 'metadataType'
@@ -1673,6 +1675,9 @@ export function collectExpectedEntries(
16731675
// ── Screen flows (`flows.<flow>.screens.<node>.…`, #7646 / #11287) ─
16741676
walkScreenFlows(config, out);
16751677

1678+
// ── Hook refusal catalogues (`hooks.<hook>.refusals.<CODE>.message`) ─
1679+
walkHookRefusals(config, out);
1680+
16761681
// ── Object sections (fieldGroups + authored form/page sections) ───
16771682
// Deliberately a pass of its own: the two authoring surfaces live in
16781683
// `objects`, `views` and `pages`, and one section may be declared by more
@@ -2239,6 +2244,32 @@ function walkScreenFlows(config: any, out: ExpectedEntry[]): void {
22392244
}
22402245
}
22412246

2247+
/**
2248+
* Emit `hooks.<hook>.refusals.<CODE>.message` for every entry a hook's refusal
2249+
* catalogue declares (#26170, maintainer ruling 6431311681 letter A), seeded
2250+
* with the declared message.
2251+
*
2252+
* The sandboxed body runner reads exactly that key (`hookRefusalMessageKey`)
2253+
* in the caller's locale when the body throws the entry's code, so each
2254+
* declared entry is one demand, counted by the coverage gate under its own
2255+
* `hook` bucket. Keyed by hook name, not by the objects the hook binds, so a
2256+
* hook bound to several objects or to `'*'` is asked for one translation per
2257+
* code. A hook that declares no `refusals` has no key here: its throws carry
2258+
* no address a bundle could reach.
2259+
*/
2260+
function walkHookRefusals(config: any, out: ExpectedEntry[]): void {
2261+
const hooks: any[] = Array.isArray(config?.hooks) ? config.hooks : [];
2262+
for (const hook of hooks) {
2263+
const hookName = typeof hook?.name === 'string' && hook.name.length > 0 ? hook.name : undefined;
2264+
if (!hookName) continue;
2265+
const refusals = hook.refusals;
2266+
if (!refusals || typeof refusals !== 'object' || Array.isArray(refusals)) continue;
2267+
for (const [code, entry] of Object.entries<any>(refusals)) {
2268+
pushOptional(out, ['hooks', hookName, 'refusals', code, 'message'], inlineText(entry?.message), 'hook');
2269+
}
2270+
}
2271+
}
2272+
22422273
/**
22432274
* Iterate the canonical metadata form registry and emit translation entries
22442275
* for every metadata type's display label/description, plus the section and

‎packages/lint/src/validate-translation-references.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,12 @@
124124
* node, is pointed at `approvals.<node_id>.label` rather than told only that
125125
* the node is not a screen.
126126
*
127+
* `hooks.<name>.refusals.<CODE>.message` (#26170) is judged against the hook's
128+
* refusal catalogue: the hook must be one the stack defines (or a sibling
129+
* package's, through the artifact carrier), and the code one its `refusals`
130+
* declares — the body runner reads the key for a declared code and nothing
131+
* else. An unknown hook and an undeclared code are each an orphan.
132+
*
127133
* `flows.<name>.successMessage` / `.errorMessage` (#22507), the terminal
128134
* toasts, are judged against the flow itself: `translateFlow` overlays a toast
129135
* only where the flow AUTHORS one, so a translated toast over a flow that
@@ -493,6 +499,12 @@ interface Universe {
493499
dashboards: Map<string, { widgets: Set<string>; actions: Set<string> }>;
494500
/** Flow name (`Flow.name`) → its screen nodes and their declared fields. */
495501
flows: Map<string, FlowFacts>;
502+
/**
503+
* [#26170] Hook name (`Hook.name`) → the codes its refusal catalogue
504+
* (`HookSchema.refusals`) declares — what a `hooks.<name>.refusals.<CODE>`
505+
* key may name. Empty for a hook that declares no catalogue.
506+
*/
507+
hooks: Map<string, Set<string>>;
496508
/** Object-less actions — the ones `globalActions.*` may name. */
497509
globalActions: Map<string, AnyRec>;
498510
/** Action name → owning object, so a misfiled `globalActions` key can say where it belongs. */
@@ -1622,6 +1634,25 @@ function buildUniverse(stack: AnyRec): Universe {
16221634
collectFlowRecord(flow, { ownDeclaration: false });
16231635
}
16241636

1637+
// ── Hooks: the refusal codes `hooks.<name>.refusals.<CODE>` may name (#26170) ──
1638+
//
1639+
// The body runner reads `hooks.<hook>.refusals.<CODE>.message` for a code the
1640+
// hook's catalogue declares, so the universe is each hook's declared codes.
1641+
// `hooks` carries disposition `concat` in `COMPOSE_KEY_DISPOSITIONS`, so a
1642+
// sibling package's hooks are read through the artifact carrier; the
1643+
// declaration this leg is JUDGING keeps the slot, the flows' decision.
1644+
const hooks = new Map<string, Set<string>>();
1645+
const collectHookRecord = (hook: AnyRec, { ownDeclaration }: { ownDeclaration: boolean }) => {
1646+
const hookName = strName(hook.name);
1647+
if (!hookName) return;
1648+
if (!ownDeclaration && hooks.has(hookName)) return;
1649+
hooks.set(hookName, new Set(Object.keys(asRecord(hook.refusals))));
1650+
};
1651+
for (const hook of recordsOf(stack.hooks)) collectHookRecord(hook, { ownDeclaration: true });
1652+
for (const hook of artifactProvidedRecords(stack, 'hooks')) {
1653+
collectHookRecord(hook, { ownDeclaration: false });
1654+
}
1655+
16251656
// ── Picklists: the option values `picklists.<name>.options.<key>` may name (#23566) ──
16261657
//
16271658
// The runtime reads this face through `lookupPicklistOption`
@@ -1699,6 +1730,7 @@ function buildUniverse(stack: AnyRec): Universe {
16991730
contributedOnlyApps,
17001731
dashboards,
17011732
flows,
1733+
hooks,
17021734
globalActions,
17031735
actionOwners,
17041736
picklists,
@@ -2315,6 +2347,39 @@ export function validateTranslationReferences(stack: AnyRec): TranslationRefFind
23152347
);
23162348
}
23172349
}
2350+
2351+
// ── hooks.<name>.refusals.<CODE> (#26170) ───────────────────────────
2352+
for (const [hookName, rawHook] of Object.entries(asRecord(rawData.hooks))) {
2353+
const hookPath = `${base}.hooks.${hookName}`;
2354+
const declared = universe.hooks.get(hookName);
2355+
if (!declared) {
2356+
orphan(
2357+
`${inLocale} · hook "${hookName}"`,
2358+
hookPath,
2359+
`Translations are keyed to hook "${hookName}", which this stack does not define, so its ` +
2360+
`refusals keep their declared messages.` +
2361+
suggest(hookName, universe.hooks.keys()),
2362+
`Match the key to a hook's \`name\`, or drop it.`,
2363+
);
2364+
continue;
2365+
}
2366+
if (!isRec(rawHook)) continue;
2367+
for (const code of Object.keys(asRecord(rawHook.refusals))) {
2368+
if (declared.has(code)) continue;
2369+
orphan(
2370+
`${inLocale} · hook "${hookName}" · refusal "${code}"`,
2371+
`${hookPath}.refusals.${code}`,
2372+
declared.size === 0
2373+
? `Translations are keyed to refusal "${code}", but hook "${hookName}" declares no ` +
2374+
`\`refusals\`, so nothing resolves this key.`
2375+
: `Translations are keyed to refusal "${code}", a code hook "${hookName}" does not declare ` +
2376+
`under \`refusals\`, so nothing resolves this key.` +
2377+
suggest(code, declared),
2378+
`Refusal translations are keyed by a code the hook's \`refusals\` declares; declare it there, ` +
2379+
`or drop the key.`,
2380+
);
2381+
}
2382+
}
23182383
}
23192384
}
23202385

‎packages/objectql/src/engine-execution-plumbing.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,15 @@ export function buildSession(execCtx?: ExecutionContext): HookContext['session']
7979
// Nothing to say about the caller → say nothing. An object whose every
8080
// property is `undefined` conveys no more than no session at all, and
8181
// returning it would turn "no caller" into "an anonymous caller".
82-
return Object.values(session as Record<string, unknown>).some((v) => v !== undefined)
83-
? session
84-
: undefined;
82+
if (!Object.values(session as Record<string, unknown>).some((v) => v !== undefined)) return undefined;
83+
// [#26170] The caller's locale rides on a session that exists, so the
84+
// sandboxed body runner can answer a declared hook refusal in the caller's
85+
// language. It is asked AFTER the presence test on purpose: a locale alone
86+
// says how to speak, not who is speaking, and must not turn "no caller"
87+
// into a session either.
88+
const locale = (execCtx as { locale?: unknown }).locale;
89+
if (typeof locale === 'string' && locale.length > 0) (session as { locale?: string }).locale = locale;
90+
return session;
8591
}
8692

8793
/** The body of `ObjectQL#buildProvenance`; the method's docblock there is its contract. */

‎packages/runtime/src/app-artifact-handlers.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ import {
145145
} from '@objectstack/types';
146146
import { SEMCONV } from '@objectstack/observability';
147147
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
148+
import type { HookRefusalI18nSource } from './sandbox/hook-refusal-catalogue.js';
148149
import {
149150
hookBodyRunnerFactory,
150151
actionBodyRunnerFactory,
@@ -189,6 +190,12 @@ export interface AppArtifactHandlerBindingOptions {
189190
* module, leaves this unset and binds such hooks as it always did.
190191
*/
191192
withholdHooksWithoutBody?: boolean;
193+
/**
194+
* [#26170] The `i18n` service a hook's declared refusal is translated
195+
* through, read at refusal time. Absent, a declared refusal is answered
196+
* with its declared message.
197+
*/
198+
i18n?: HookRefusalI18nSource;
192199
}
193200

194201
/** What one {@link bindAppArtifactHandlers} call bound. */
@@ -273,7 +280,7 @@ export function bindAppArtifactHandlers(
273280
ql.bindHooks(hooks, {
274281
packageId: owner,
275282
functions,
276-
bodyRunner: hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql, logger, appId }),
283+
bodyRunner: hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql, logger, appId, i18n: options.i18n }),
277284
// [#24289] A handler that runs in-process, an inline function or
278285
// the function a string `handler` names, is handed the
279286
// `ctx.title(field?)` a `body` gets in the sandbox. The binder

‎packages/runtime/src/app-plugin.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { SEED_WRITE_EXECUTION_CONTEXT } from '@objectstack/spec/kernel';
3636
import { applyProtection } from '@objectstack/spec/shared';
3737
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
3838
import { hookBodyRunnerFactory, actionBodyRunnerFactory } from './sandbox/body-runner.js';
39+
import { hookRefusalI18nReader } from './sandbox/hook-refusal-catalogue.js';
3940
import { bindAppArtifactHandlers, scheduleAppArtifactJobs } from './app-artifact-handlers.js';
4041
import { countServerTiming } from '@objectstack/observability';
4142

@@ -746,6 +747,7 @@ export class AppPlugin implements Plugin {
746747
ql,
747748
logger: ctx.logger,
748749
appId: 'runtime-authored',
750+
i18n: hookRefusalI18nReader(ctx),
749751
}));
750752
if (installed !== false) {
751753
ctx.logger.info('[AppPlugin] Installed default hook body runner (runtime-authored hooks can execute)');
@@ -1716,7 +1718,14 @@ export class AppPlugin implements Plugin {
17161718
handlerDefinition.manifest[key] = handlerSource[key];
17171719
}
17181720
}
1719-
bindAppArtifactHandlers(ql, handlerDefinition, { appId, logger: ctx.logger, source: 'AppPlugin' });
1721+
bindAppArtifactHandlers(ql, handlerDefinition, {
1722+
appId,
1723+
logger: ctx.logger,
1724+
source: 'AppPlugin',
1725+
// [#26170] A hook's declared refusal is answered in the caller's
1726+
// language, through the i18n service read at refusal time.
1727+
i18n: hookRefusalI18nReader(ctx),
1728+
});
17201729

17211730
// [ADR-0110 D5] The action-governance inventory used to hang off a
17221731
// `kernel:ready` hook HERE. Moved to ObjectQLPlugin: AppPlugin is

‎packages/runtime/src/sandbox/body-runner.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,19 @@ import {
7373
storedMetadataFamilyTableList,
7474
} from '../stored-metadata-body-boundary.js';
7575
import { mapDataError } from '@objectstack/types';
76+
import { resolveHookRefusal, type HookRefusalI18nSource } from './hook-refusal-catalogue.js';
7677
import { isRelayedSandboxRefusal } from './quickjs-runner.js';
7778

7879
interface FactoryOptions {
7980
ql: any;
8081
appId: string;
8182
logger?: any;
83+
/**
84+
* [#26170] Where a hook's declared refusal is translated: the `i18n`
85+
* service, read at refusal time (see `resolveHookRefusal`). Absent, a
86+
* declared refusal is answered with its declared message.
87+
*/
88+
i18n?: HookRefusalI18nSource;
8289
}
8390

8491
/**
@@ -486,8 +493,13 @@ export function hookBodyRunnerFactory(
486493
});
487494
applyMutationsToInput(engineCtx, result, sandboxCtx.input);
488495
} catch (err: any) {
489-
logBodyThrow(opts, { kind: 'hook', name: hook.name }, err);
490-
throw err;
496+
// [#26170] A hook that declares `refusals` refuses by code only: the
497+
// body's throw is answered with the declared entry in the caller's
498+
// locale, or refused loudly when the catalogue cannot answer it.
499+
// Everything else leaves exactly as thrown.
500+
const answered = resolveHookRefusal(hook, err, engineCtx, { i18n: opts.i18n, logger: opts.logger });
501+
logBodyThrow(opts, { kind: 'hook', name: hook.name }, answered);
502+
throw answered;
491503
}
492504
};
493505
};

0 commit comments

Comments
 (0)