Skip to content

Commit 08af21e

Browse files
committed
test(i18n): hook refusal catalogue pins; skill docs and changeset
The save-time reading now masks comments and string contents first, so a throw or code written inside either is never read as one. Claude-Session: https://claude.ai/code/session_01WGufzfyVQuRsL6SRGuKCem Co-authored-by: Claude <noreply@anthropic.com>
1 parent 108e7db commit 08af21e

8 files changed

Lines changed: 747 additions & 26 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/runtime': minor
4+
'@objectstack/objectql': minor
5+
'@objectstack/cli': minor
6+
'@objectstack/lint': minor
7+
---
8+
9+
feat(spec): a hook declares its refusal catalogue, and its body refuses by code, answered in the caller's language
10+
11+
Clause-②: yes (widening)
12+
Metadata-protocol: added
13+
14+
A hook can now declare `refusals`: one entry per SCREAMING_SNAKE code, each with the `message` the user reads and an optional 4xx `status` (default `400`). A sandboxed `body` then refuses by code only: it throws an error carrying a declared `code`, and the body runner answers with the entry. The message is translated through `hooks.<hook>.refusals.<CODE>.message` in the caller's locale, the code reaches the caller's error envelope, and the status is the entry's. The body's own error text and `status` are not what the caller reads.
15+
16+
- **Spec.** `HookSchema.refusals` (`HookRefusalSchema`: `message`, `status?`). A new `hooks` group on the translation bundle, `hooks.<hook>.refusals.<CODE>.message`, and `hookRefusalMessageKey`. `HookContext.session.locale` declares the caller's locale.
17+
- **Undeclared codes are refused loudly.** A code the body throws literally (`{ code: 'X' }`, or `e.code = 'X'; throw e`) that the catalogue does not declare fails the save at `body.source`. Any other undeclared code, and a throw with no code, is a `500` fault at run time that names the hook and the code. This applies only to a hook that declares `refusals`; a hook without one is answered exactly as before.
18+
- **Runtime.** The body runner resolves the throw against the catalogue and picks the translation through the `i18n` service, negotiated against the locales it holds. An error a `ctx.api` call raised that the body lets leave unchanged, a crash, and the sandbox's own faults pass through untouched. ObjectQL copies the request's locale onto the hook session.
19+
- **CLI.** `os i18n extract` scaffolds one key per declared entry and `os i18n check` counts them, in a new `hook` coverage bucket.
20+
- **Lint.** A translation keyed to a hook the stack does not define, or to a code its `refusals` does not declare, is reported as `translation-target-unknown`.
21+
22+
Nothing to do for existing hooks. To use it, declare `refusals` on a sandboxed hook and throw its codes.
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
// Copyright (c) 2026 ObjectStack contributors. Apache-2.0 license.
2+
//
3+
// objectstack#26170 — a hook's declared refusal catalogue joins the i18n
4+
// buckets as `hooks.<hook>.refusals.<CODE>.message` (maintainer ruling
5+
// 6431311681, letter A).
6+
//
7+
// A hook declaring `refusals: { <CODE>: { message, status? } }` refuses by code
8+
// only, and the sandboxed body runner reads the key in the caller's locale
9+
// before it answers. These pins are the CLI half: the walker scaffolds one key
10+
// per declared entry, the coverage gate demands it, and the key the walker
11+
// writes is the very address the runtime asks for (`hookRefusalMessageKey`),
12+
// so the two cannot drift.
13+
//
14+
// The ledger mock is `i18n-flow-refusal-coverage.test.ts`'s, for its reason:
15+
// these pins measure the bucket itself, whatever the shipped ledger says next.
16+
17+
import { describe, it, expect, vi } from 'vitest';
18+
19+
vi.mock('@objectstack/lint', async (importOriginal) => ({
20+
...(await importOriginal<typeof import('@objectstack/lint')>()),
21+
authorWarnedProperties: () => new Set<string>(),
22+
}));
23+
24+
import { collectExpectedEntries, extractTranslations } from '../src/utils/i18n-extract.js';
25+
import { computeI18nCoverage } from '../src/utils/i18n-coverage.js';
26+
import { TranslationDataSchema, hookRefusalMessageKey } from '@objectstack/spec/system';
27+
28+
const LIMIT = 'This order exceeds the customer credit limit.';
29+
const HOLD = 'The account is on hold.';
30+
31+
const creditGuard = {
32+
name: 'credit_guard',
33+
object: 'order',
34+
events: ['beforeInsert'],
35+
body: { language: 'js', source: "throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' });" },
36+
refusals: {
37+
CREDIT_LIMIT: { message: LIMIT },
38+
ACCOUNT_ON_HOLD: { message: HOLD, status: 409 },
39+
},
40+
};
41+
42+
/** A hook with no catalogue contributes nothing. */
43+
const plainHook = { name: 'stamp', object: 'order', events: ['beforeInsert'], handler: 'stamp' };
44+
45+
const hookEntries = (config: any) => collectExpectedEntries(config).filter((e) => e.path[0] === 'hooks');
46+
47+
describe('what the walker harvests from a hook catalogue (#26170)', () => {
48+
it('emits one key per declared entry, keyed as the runtime reads it, seeded with the message', () => {
49+
const entries = hookEntries({ hooks: [creditGuard, plainHook] });
50+
51+
expect(entries.map((e) => e.path.join('.'))).toEqual([
52+
hookRefusalMessageKey('credit_guard', 'CREDIT_LIMIT'),
53+
hookRefusalMessageKey('credit_guard', 'ACCOUNT_ON_HOLD'),
54+
]);
55+
expect(entries[0]).toMatchObject({ sourceValue: LIMIT, inline: LIMIT, source: 'hook' });
56+
});
57+
58+
it('harvests nothing from a stack whose hooks declare no catalogue', () => {
59+
expect(hookEntries({ hooks: [plainHook] })).toEqual([]);
60+
expect(hookEntries({})).toEqual([]);
61+
});
62+
});
63+
64+
describe('the coverage gate demands each declared refusal (#26170)', () => {
65+
const tree = (hooks?: Record<string, unknown>) => ({
66+
i18n: { defaultLocale: 'en', supportedLocales: ['en', 'zh-CN'] },
67+
hooks: [creditGuard],
68+
translations: [{ 'zh-CN': { ...(hooks ? { hooks } : {}) } }],
69+
});
70+
const zhHooks = (config: any) =>
71+
computeI18nCoverage(config).issues.filter((i) => i.locale === 'zh-CN' && i.key.startsWith('hooks.'));
72+
73+
it('reports each untranslated refusal in the hook bucket', () => {
74+
const issues = zhHooks(tree());
75+
expect(issues.map((i) => i.key).sort()).toEqual([
76+
'hooks.credit_guard.refusals.ACCOUNT_ON_HOLD.message',
77+
'hooks.credit_guard.refusals.CREDIT_LIMIT.message',
78+
]);
79+
expect(issues.every((i) => i.source === 'hook')).toBe(true);
80+
});
81+
82+
it('counts what is still missing once one is translated', () => {
83+
const issues = zhHooks(tree({ credit_guard: { refusals: { CREDIT_LIMIT: { message: '订单超出客户信用额度。' } } } }));
84+
expect(issues.map((i) => i.key)).toEqual(['hooks.credit_guard.refusals.ACCOUNT_ON_HOLD.message']);
85+
});
86+
87+
it('goes quiet once every entry is translated', () => {
88+
const issues = zhHooks(tree({
89+
credit_guard: {
90+
refusals: {
91+
CREDIT_LIMIT: { message: '订单超出客户信用额度。' },
92+
ACCOUNT_ON_HOLD: { message: '该客户账户已冻结。' },
93+
},
94+
},
95+
}));
96+
expect(issues).toEqual([]);
97+
});
98+
});
99+
100+
describe('the skeleton `os i18n extract` writes (#26170)', () => {
101+
const result = extractTranslations({ hooks: [creditGuard] }, { locales: ['en', 'zh-CN'] });
102+
103+
it('writes the message into the default locale and an empty slot into the others', () => {
104+
expect((result.bundles.en as any).hooks.credit_guard.refusals).toEqual({
105+
CREDIT_LIMIT: { message: LIMIT },
106+
ACCOUNT_ON_HOLD: { message: HOLD },
107+
});
108+
expect((result.bundles['zh-CN'] as any).hooks.credit_guard.refusals).toEqual({
109+
CREDIT_LIMIT: { message: '' },
110+
ACCOUNT_ON_HOLD: { message: '' },
111+
});
112+
});
113+
114+
it('parses through the schema it is written for, in every locale', () => {
115+
for (const [locale, bundle] of Object.entries(result.bundles)) {
116+
expect(TranslationDataSchema.safeParse(bundle).success, `skeleton for ${locale}`).toBe(true);
117+
}
118+
});
119+
});

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4512,3 +4512,60 @@ describe('validateTranslationReferences — reports', () => {
45124512
expect(findings).toEqual([]);
45134513
});
45144514
});
4515+
4516+
describe('validateTranslationReferences — hook refusals (#26170)', () => {
4517+
const creditStack = {
4518+
hooks: [
4519+
{
4520+
name: 'credit_guard',
4521+
object: 'order',
4522+
events: ['beforeInsert'],
4523+
body: { language: 'js', source: "throw Object.assign(new Error('x'), { code: 'CREDIT_LIMIT' });" },
4524+
refusals: { CREDIT_LIMIT: { message: 'Over the credit limit.' } },
4525+
},
4526+
{ name: 'stamp', object: 'order', events: ['beforeInsert'], handler: 'stamp' },
4527+
],
4528+
};
4529+
const bundle = (hooks: unknown) => ({ ...creditStack, translations: [{ 'zh-CN': { hooks } }] });
4530+
4531+
it('reports nothing for a translation of a declared code', () => {
4532+
expect(
4533+
validateTranslationReferences(bundle({ credit_guard: { refusals: { CREDIT_LIMIT: { message: '超出信用额度。' } } } })),
4534+
).toEqual([]);
4535+
});
4536+
4537+
it('refuses a code the hook does not declare, with the nearest declared code offered', () => {
4538+
const findings = validateTranslationReferences(bundle({ credit_guard: { refusals: { CREDIT_LIMT: { message: 'x' } } } }));
4539+
expect(findings).toHaveLength(1);
4540+
expect(findings[0].rule).toBe(TRANSLATION_TARGET_UNKNOWN);
4541+
expect(findings[0].severity).toBe('error');
4542+
expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.credit_guard.refusals.CREDIT_LIMT');
4543+
expect(findings[0].message).toContain('a code hook "credit_guard" does not declare under `refusals`');
4544+
expect(findings[0].message).toContain('Did you mean "CREDIT_LIMIT"?');
4545+
});
4546+
4547+
it('refuses a refusal key on a hook that declares no catalogue', () => {
4548+
const findings = validateTranslationReferences(bundle({ stamp: { refusals: { ANY: { message: 'x' } } } }));
4549+
expect(findings).toHaveLength(1);
4550+
expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.stamp.refusals.ANY');
4551+
expect(findings[0].message).toContain('hook "stamp" declares no `refusals`');
4552+
});
4553+
4554+
it('refuses a hook the stack does not define, at the hook level', () => {
4555+
const findings = validateTranslationReferences(bundle({ credit_gaurd: { refusals: { CREDIT_LIMIT: { message: 'x' } } } }));
4556+
expect(findings).toHaveLength(1);
4557+
expect(findings[0].path).toBe('translations[0]["zh-CN"].hooks.credit_gaurd');
4558+
expect(findings[0].message).toContain('hook "credit_gaurd", which this stack does not define');
4559+
expect(findings[0].message).toContain('Did you mean "credit_guard"?');
4560+
});
4561+
4562+
it('reads a sibling package\'s hooks through the artifact carrier', () => {
4563+
const { hooks: _own, ...rest } = creditStack;
4564+
const findings = validateTranslationReferences({
4565+
...rest,
4566+
packages: [{ manifest: { hooks: creditStack.hooks } }],
4567+
translations: [{ 'zh-CN': { hooks: { credit_guard: { refusals: { CREDIT_LIMIT: { message: '超出信用额度。' } } } } } }],
4568+
});
4569+
expect(findings).toEqual([]);
4570+
});
4571+
});
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26170] `HookContext.session.locale` — the caller's locale rides on the
5+
* session a hook receives, so the sandboxed body runner can answer a declared
6+
* hook refusal (`hooks.<hook>.refusals.<CODE>.message`) in the caller's
7+
* language.
8+
*/
9+
10+
import { describe, it, expect } from 'vitest';
11+
import { buildSession } from './engine-execution-plumbing.js';
12+
13+
describe('[#26170] buildSession carries the caller\'s locale', () => {
14+
it('copies `execCtx.locale` onto a session that exists', () => {
15+
expect(buildSession({ userId: 'u1', locale: 'zh-CN' } as any)).toMatchObject({ userId: 'u1', locale: 'zh-CN' });
16+
});
17+
18+
it('a locale alone does not make a session — it says how to speak, not who is speaking', () => {
19+
expect(buildSession({ locale: 'zh-CN' } as any)).toBeUndefined();
20+
});
21+
22+
it('writes no `locale` key when none was asked', () => {
23+
for (const locale of [undefined, '']) {
24+
expect(buildSession({ userId: 'u1', locale } as any)).not.toHaveProperty('locale');
25+
}
26+
});
27+
});

0 commit comments

Comments
 (0)