Skip to content

Commit 7976cc1

Browse files
committed
test(i18n): pin a tenant-rewritten rule message on the refusal and on /meta (red)
ADR-0029 D9.2a: under a non-default locale the packaged translation of a validation rule message must not replace a tenant's rewrite of it. Red first, on both readers: translateObject's validations overlay, the rule evaluator's authored message, and the two together off one registry. Claude-Session: https://claude.ai/code/session_01L6bhgW82YGUW8s8X4Dgiqc Co-authored-by: Claude <noreply@anthropic.com>
1 parent 57c51aa commit 7976cc1

3 files changed

Lines changed: 361 additions & 0 deletions

File tree

Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* ADR-0029 D9.2a — a tenant's rewrite of a packaged rule message beats the
5+
* packaged translation, on BOTH readers of the rule, and the two still agree.
6+
*
7+
* A packaged object declares two rules and ships their `zh-CN` translations at
8+
* `objects.<o>._validations.<rule>.message`. A tenant overlays the object
9+
* (ADR-0029 D9) and rewrites one of the two messages, keeping the rule's name.
10+
* The catalog translates the PACKAGED rule, so under `zh-CN`:
11+
*
12+
* - the rewritten rule must answer the tenant's own sentence, as written;
13+
* - the rule the tenant left alone must still answer its translation.
14+
*
15+
* Both readers are driven off ONE real registry: the refusal of a real write
16+
* (the engine's validator), and the served object as `/meta` translates it —
17+
* `translateObject` over the resolved object, with the packaged base the
18+
* serving layer hands it (`getPackagedObjectBase`, the accessor `/meta` reads
19+
* through `packagedObjectBaseOf`). For every header they must be one string.
20+
*/
21+
22+
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
23+
import { preferredLocaleFromHeader, translateObject } from '@objectstack/spec/system';
24+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
25+
import { ObjectQL } from './index.js';
26+
27+
const OBJ = 'tr_duty';
28+
const PKG = 'com.objectstack.test.tenant-rewrite';
29+
30+
const PACKAGED = {
31+
returned_needs_note: 'Say why the duty is being returned.',
32+
done_needs_owner: 'A finished duty needs an owner.',
33+
};
34+
const ZH = {
35+
returned_needs_note: '请写明打回的原因。',
36+
done_needs_owner: '已完成的职责需要负责人。',
37+
};
38+
const REWRITE = 'Tell the owner what to change before you send it back.';
39+
40+
const rules = (returnedMessage: string) => [
41+
{
42+
type: 'script',
43+
name: 'returned_needs_note',
44+
message: returnedMessage,
45+
condition: "record.status == 'returned' && record.return_note == null",
46+
fields: ['return_note'],
47+
},
48+
{
49+
type: 'script',
50+
name: 'done_needs_owner',
51+
message: PACKAGED.done_needs_owner,
52+
condition: "record.status == 'done' && record.owner == null",
53+
fields: ['owner'],
54+
},
55+
];
56+
57+
const body = (returnedMessage: string) => ({
58+
name: OBJ,
59+
label: 'Duty',
60+
fields: {
61+
status: { type: 'text', label: 'Status' },
62+
return_note: { type: 'text', label: 'Return note' },
63+
owner: { type: 'text', label: 'Owner' },
64+
},
65+
validations: rules(returnedMessage),
66+
});
67+
68+
const BUNDLE: Record<string, any> = {
69+
en: {
70+
objects: {
71+
[OBJ]: {
72+
_validations: {
73+
returned_needs_note: { message: PACKAGED.returned_needs_note },
74+
done_needs_owner: { message: PACKAGED.done_needs_owner },
75+
},
76+
},
77+
},
78+
},
79+
'zh-CN': {
80+
objects: {
81+
[OBJ]: {
82+
_validations: {
83+
returned_needs_note: { message: ZH.returned_needs_note },
84+
done_needs_owner: { message: ZH.done_needs_owner },
85+
},
86+
},
87+
},
88+
},
89+
};
90+
91+
/** `FileI18nAdapter.t()`-shaped: the locale exactly, then the fallback, then the key echoed. */
92+
function servedI18n(bundle: Record<string, any>, fallbackLocale = 'en') {
93+
const dig = (data: unknown, key: string): unknown =>
94+
key.split('.').reduce<unknown>(
95+
(cur, part) => (cur && typeof cur === 'object' ? (cur as any)[part] : undefined),
96+
data,
97+
);
98+
return {
99+
t(key: string, locale: string): string {
100+
const exact = dig(bundle[locale], key);
101+
if (typeof exact === 'string') return exact;
102+
const fallback = dig(bundle[fallbackLocale], key);
103+
return typeof fallback === 'string' ? fallback : key;
104+
},
105+
getLocales: () => Object.keys(bundle),
106+
};
107+
}
108+
109+
function makeDriver() {
110+
const rows = new Map<string, any>();
111+
return {
112+
name: 'com.objectstack.driver.memory.tr',
113+
version: '1.0.0',
114+
async connect() { /* noop */ },
115+
async disconnect() { /* noop */ },
116+
async initObjects() { /* noop */ },
117+
async find() { return [...rows.values()]; },
118+
async findOne(_o: string, options?: any) { return rows.get(String(options?.where?.id)) ?? null; },
119+
async count() { return rows.size; },
120+
async create(_o: string, data: any) { rows.set(String(data.id), data); return data; },
121+
async update(_o: string, data: any) { return data; },
122+
async delete() { return false; },
123+
} as any;
124+
}
125+
126+
describe('ADR-0029 D9.2a a tenant-rewritten rule message, on the refusal and on /meta', () => {
127+
let engine: ObjectQL;
128+
let protocol: any;
129+
130+
/** Boot the packaged object, then (optionally) the tenant's overlay layer. */
131+
async function boot(overlay: boolean) {
132+
engine = new ObjectQL();
133+
engine.registerDriver(makeDriver(), true);
134+
await engine.init();
135+
engine.setI18nService(servedI18n(BUNDLE) as any);
136+
engine.registry.registerObject(body(PACKAGED.returned_needs_note) as any, PKG);
137+
if (overlay) {
138+
engine.registry.registerObject({ ...body(REWRITE), _provenance: 'org' } as any, PKG, undefined, 'overlay');
139+
}
140+
protocol = new ObjectStackProtocolImplementation(engine as any);
141+
}
142+
143+
afterEach(async () => {
144+
try { await engine?.destroy(); } catch { /* noop */ }
145+
});
146+
147+
async function refusal(header: string, data: Record<string, unknown>): Promise<string> {
148+
try {
149+
await engine.insert(OBJ, data, { context: { locale: preferredLocaleFromHeader(header) } } as any);
150+
} catch (e: any) {
151+
return String(e?.fields?.[0]?.message ?? e?.message);
152+
}
153+
throw new Error('expected the write to be rejected');
154+
}
155+
156+
function served(header: string): Record<string, string> {
157+
const doc = translateObject(engine.registry.getObject(OBJ) as any, BUNDLE as any, {
158+
locale: preferredLocaleFromHeader(header),
159+
fallbackChain: ['en'],
160+
packagedBase: protocol.getPackagedObjectBase(OBJ),
161+
}) as any;
162+
return Object.fromEntries(doc.validations.map((r: any) => [r.name, r.message]));
163+
}
164+
165+
async function table() {
166+
const out: Record<string, unknown> = {};
167+
for (const header of ['zh-CN', 'zh', 'en']) {
168+
out[header] = {
169+
served: served(header),
170+
refusal: {
171+
returned_needs_note: await refusal(header, { id: 'r1', status: 'returned' }),
172+
done_needs_owner: await refusal(header, { id: 'r2', status: 'done' }),
173+
},
174+
};
175+
}
176+
return out;
177+
}
178+
179+
describe('with the tenant overlay', () => {
180+
beforeEach(async () => { await boot(true); });
181+
182+
it('the overlay is what both readers see, over a packaged owner that is still there', () => {
183+
expect((engine.registry.getObject(OBJ) as any).validations[0].message).toBe(REWRITE);
184+
expect((protocol.getPackagedObjectBase(OBJ) as any).validations[0].message).toBe(PACKAGED.returned_needs_note);
185+
});
186+
187+
it('serves and refuses with the rewrite as written, and still translates the untouched rule', async () => {
188+
const both = (zh: string) => ({ returned_needs_note: REWRITE, done_needs_owner: zh });
189+
expect(await table()).toEqual({
190+
'zh-CN': { served: both(ZH.done_needs_owner), refusal: both(ZH.done_needs_owner) },
191+
zh: { served: both(ZH.done_needs_owner), refusal: both(ZH.done_needs_owner) },
192+
en: { served: both(PACKAGED.done_needs_owner), refusal: both(PACKAGED.done_needs_owner) },
193+
});
194+
});
195+
});
196+
197+
describe('control: no overlay', () => {
198+
beforeEach(async () => { await boot(false); });
199+
200+
it('translates both packaged rules on both readers', async () => {
201+
expect(await table()).toEqual({
202+
'zh-CN': { served: ZH, refusal: ZH },
203+
zh: { served: ZH, refusal: ZH },
204+
en: { served: PACKAGED, refusal: PACKAGED },
205+
});
206+
});
207+
});
208+
});

‎packages/objectql/src/validation/rule-validator.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2649,3 +2649,83 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
26492649
expect(err.message).not.toBe('这条不该出现。');
26502650
});
26512651
});
2652+
2653+
/**
2654+
* ADR-0029 D9.2a — a tenant's rewrite of a rule message beats the packaged
2655+
* translation in the refusal.
2656+
*
2657+
* The catalog entry at `objects.<o>._validations.<rule>.message` translates
2658+
* the PACKAGED rule. When the served rule's message diverged from the packaged
2659+
* rule of the same name, the sentence is the tenant's own and is returned as
2660+
* written, judged by `scalarOverridesPackagedBase` (the one comparison `/meta`
2661+
* judges the same message by). `messages.packagedRule` is the engine's lookup
2662+
* into the packaged owner's declaration; absent means no packaged base is
2663+
* known, and the catalog applies as it always did.
2664+
*/
2665+
describe('evaluateValidationRules — a tenant-rewritten rule message beats the packaged translation (ADR-0029 D9.2a)', () => {
2666+
const PACKAGED = 'A standing duty must declare a frequency.';
2667+
const REWRITE = 'Pick how often this duty repeats.';
2668+
const ZH = '常规任务必须设置频率。';
2669+
const KEY = 'zh-CN|objects.duly_duty._validations.standing_no_frequency.message';
2670+
const t = (key: string, locale: string) => ({ [KEY]: ZH } as Record<string, string>)[`${locale}|${key}`] ?? key;
2671+
2672+
const failing = (schema: any, data: Record<string, unknown>, opts: Record<string, unknown>) => {
2673+
try {
2674+
evaluateValidationRules(schema, data, 'insert', opts);
2675+
} catch (e) {
2676+
return (e as ValidationError).fields;
2677+
}
2678+
throw new Error('expected a ValidationError');
2679+
};
2680+
2681+
const scriptRule = (message: string) => ({
2682+
type: 'script',
2683+
name: 'standing_no_frequency',
2684+
message,
2685+
condition: "record.frequency == null || record.frequency == ''",
2686+
fields: ['frequency'],
2687+
});
2688+
const schemaWith = (message: string) => ({
2689+
fields: { frequency: { type: 'select', label: '频率' } },
2690+
validations: [scriptRule(message)],
2691+
});
2692+
const packagedRule = (name: string) => (name === 'standing_no_frequency' ? scriptRule(PACKAGED) : undefined);
2693+
const messages = (extra: Record<string, unknown> = {}) =>
2694+
({ locale: 'zh-CN', objectName: 'duly_duty', translate: t, ...extra });
2695+
2696+
it('returns the rewrite as written in a non-default locale', () => {
2697+
const [err] = failing(schemaWith(REWRITE), {}, { messages: messages({ packagedRule }) });
2698+
expect(err.message).toBe(REWRITE);
2699+
expect(err.code).toBe('rule_violation');
2700+
expect(err.field).toBe('frequency');
2701+
});
2702+
2703+
it('still translates a rule whose message is the packaged one', () => {
2704+
const [err] = failing(schemaWith(PACKAGED), {}, { messages: messages({ packagedRule }) });
2705+
expect(err.message).toBe(ZH);
2706+
});
2707+
2708+
it('counts a rule the packaged object does not declare as authored', () => {
2709+
const [err] = failing(schemaWith(REWRITE), {}, { messages: messages({ packagedRule: () => undefined }) });
2710+
expect(err.message).toBe(REWRITE);
2711+
});
2712+
2713+
it('infers nothing without a packaged base: the catalog applies, as before', () => {
2714+
const [err] = failing(schemaWith(REWRITE), {}, { messages: messages() });
2715+
expect(err.message).toBe(ZH);
2716+
});
2717+
2718+
it('judges a conditional branch against the packaged branch of the same name', () => {
2719+
const conditional = (branchMessage: string) => ({
2720+
type: 'conditional',
2721+
name: 'standing_gate',
2722+
message: 'wrapper',
2723+
when: 'true',
2724+
then: { ...scriptRule(branchMessage) },
2725+
});
2726+
const packaged = (name: string) => (name === 'standing_no_frequency' ? scriptRule(PACKAGED) : undefined);
2727+
const schema = (m: string) => ({ fields: { frequency: { type: 'select' } }, validations: [conditional(m)] });
2728+
expect(failing(schema(REWRITE), {}, { messages: messages({ packagedRule: packaged }) })[0].message).toBe(REWRITE);
2729+
expect(failing(schema(PACKAGED), {}, { messages: messages({ packagedRule: packaged }) })[0].message).toBe(ZH);
2730+
});
2731+
});

‎packages/spec/src/system/i18n-resolver.object-validations.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,76 @@ describe('#27135 the fields and actions overlays are unchanged', () => {
253253
expect('validations' in out).toBe(false);
254254
});
255255
});
256+
257+
/**
258+
* ADR-0029 D9.2a — the catalog LOSES to a tenant's rewrite of a rule message.
259+
*
260+
* The catalog translates the PACKAGED rule, so a served message that diverged
261+
* from the packaged rule of the same name is the tenant's own sentence and is
262+
* served as written, in every locale. The comparison is the one every other
263+
* string on the object is judged by (`valueOverridesPackagedBase`), against
264+
* the packaged object the serving layer hands over as `packagedBase`. The
265+
* refusal of the same write applies the same rule beside the evaluator, in
266+
* objectql's `engine-validation-tenant-rewrite`.
267+
*/
268+
describe('ADR-0029 D9.2a a tenant-rewritten rule message beats the packaged translation', () => {
269+
const REWRITE = {
270+
closed_is_final: 'Closed tickets stay closed — open a new one instead.',
271+
vip_branch: 'Every VIP ticket needs a named owner.',
272+
};
273+
274+
/** The tenant's overlay: two messages rewritten, one rule of its own. */
275+
const tenantDoc = () => {
276+
const doc = clone(DOC);
277+
doc.validations[0].message = REWRITE.closed_is_final;
278+
doc.validations[3].then.message = REWRITE.vip_branch;
279+
doc.validations.push(rule({
280+
type: 'script',
281+
name: 'tenant_only_rule',
282+
message: 'Our own rule, in our own words.',
283+
condition: 'record.owner == null',
284+
}));
285+
return doc;
286+
};
287+
288+
/** A catalog entry for the tenant's own rule too: it still must not apply. */
289+
const bundle = TranslationBundleSchema.parse({
290+
'zh-CN': localeData({ ...ZH, tenant_only_rule: '不该出现的译文。' }),
291+
});
292+
293+
it('serves the rewrite as written, and still translates every rule the tenant left alone', () => {
294+
const out = translateObject(tenantDoc(), bundle, { locale: 'zh-CN', packagedBase: clone(DOC) }) as any;
295+
expect(messagesOf(out)).toEqual({
296+
closed_is_final: REWRITE.closed_is_final,
297+
refund_needs_reason: ZH.refund_needs_reason,
298+
untranslated_rule: AUTHORED.untranslated_rule,
299+
wrapper: AUTHORED.wrapper,
300+
vip_branch: REWRITE.vip_branch,
301+
standard_branch: ZH.standard_branch,
302+
});
303+
// A rule the packaged object does not declare was authored after the fact.
304+
expect(out.validations[4].message).toBe('Our own rule, in our own words.');
305+
});
306+
307+
it('counts every named rule as authored when the packaged object declares none', () => {
308+
const { validations: _dropped, ...bare } = clone(DOC);
309+
const doc = tenantDoc();
310+
const out = translateObject(doc, bundle, { locale: 'zh-CN', packagedBase: bare }) as any;
311+
expect(out.validations).toBe(doc.validations);
312+
});
313+
314+
it('infers nothing without a packaged base: the catalog applies, as before', () => {
315+
const out = translateObject(tenantDoc(), bundle, { locale: 'zh-CN' }) as any;
316+
expect(out.validations[0].message).toBe(ZH.closed_is_final);
317+
expect(out.validations[3].then.message).toBe(ZH.vip_branch);
318+
});
319+
320+
it('is reached through the /meta door with the base the serving layer supplies', () => {
321+
const out = translateMetadataDocument('object', tenantDoc(), bundle, {
322+
locale: 'zh-CN',
323+
packagedBase: clone(DOC),
324+
}) as any;
325+
expect(out.validations[0].message).toBe(REWRITE.closed_is_final);
326+
expect(out.validations[1].message).toBe(ZH.refund_needs_reason);
327+
});
328+
});

0 commit comments

Comments
 (0)