Skip to content
Merged
20 changes: 20 additions & 0 deletions .changeset/35384-reader-labels-translate-object.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
'@objectstack/objectql': patch
'@objectstack/plugin-approvals': patch
'@objectstack/plugin-audit': patch
---

fix(objectql,approvals,audit): an authored rule message, an approval's object label and an activity summary's labels read as `/meta` serves them in a declared `i18n.sourceLocale`

Clause-②: no
Metadata-protocol: none

In a deployment whose `i18n.sourceLocale` differs from its `i18n.defaultLocale` (an app authored in English that defaults its users to Chinese, say), three readers still looked metadata text up through `II18nService.t()`, which falls back to the `defaultLocale` row when the reader's locale holds no entry. An `en` reader was shown the Chinese text where `GET /meta` and every other refusal label showed the English one as authored:

- objectql: the author-written message of a validation rule (`objects.<object>._validations.<rule>.message`) in a `400 VALIDATION_FAILED` refusal;
- plugin-approvals: the object label on the approvals inbox, the request page, the generic data door's request rows and the approval refusals that name an object;
- plugin-audit: the object, field and select-option labels inside an activity summary composed in the reader's language.

Each now resolves through `translateObject` (`@objectstack/spec/system`) over every locale the i18n service holds, with the resolve options the metadata route builds: the reader's locale, the declared fallback chain and the authored language (the declared `sourceLocale`, else `defaultLocale`). A reader in the authored language reads the text as written; every other reader reads the same row as before. `t()` keeps carrying the catalog sentences.

An i18n service that cannot hand its translations over (no `getLocales()` / `getTranslations()`) no longer has these labels and rule messages translated through `t()`: the authored text stands. Every service the platform ships implements both.
55 changes: 54 additions & 1 deletion packages/objectql/src/engine-label-source-locale.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,31 @@ const deal = {
}],
};

/**
* [#35384] An object whose rule carries an AUTHORED message: the sentence is
* metadata (`objects.<o>._validations.<rule>.message`), served by `/meta`'s
* `translateObjectValidations`.
*/
const task = {
name: 'lsl_task',
label: 'Task',
fields: {
id: { name: 'id', type: 'text' as const, primaryKey: true },
due: { name: 'due', type: 'text' as const, label: 'Due' },
},
validations: [{
type: 'script',
name: 'task_needs_due',
message: 'A task needs a due date.',
condition: "record.due == null || record.due == ''",
fields: ['due'],
}],
};

/** The deployment ships `zh-CN` rows only. */
const ZH_CN = {
objects: {
lsl_task: { label: '任务', _validations: { task_needs_due: { message: '任务必须设置截止日期。' } } },
lsl_account: { label: '客户', fields: { name: { label: '名称' } } },
lsl_deal: {
label: '商机',
Expand Down Expand Up @@ -147,7 +169,7 @@ async function makeEngine(i18n: ReturnType<typeof servedI18n>) {
const engine = new ObjectQL();
engine.registerDriver(makeStubDriver(), true);
await engine.init();
for (const o of [account, deal]) engine.registry.registerObject(o as any);
for (const o of [account, deal, task]) engine.registry.registerObject(o as any);
engine.setI18nService(i18n);
return engine;
}
Expand Down Expand Up @@ -213,3 +235,34 @@ describe('a refusal in the declared sourceLocale names labels as authored', () =
for (const word of ['客户', '商机', '所属客户']) expect(object.message).toContain(word);
});
});

/**
* [#35384] The authored rule message resolves by the same rule: through
* `translateObject` over the metadata route's `ResolveOptions`, so an `en`
* write in a deployment authored in English reads the sentence as written —
* what `/meta` serves the same rule's `message` as for an `en` request
* (`packages/rest/src/meta-i18n-declared-fallback-chain.test.ts` §6 pins that
* half) — never the `zh-CN` row `t()` falls back to.
*/
describe('an authored rule message in the declared sourceLocale reads as authored', () => {
const refusal = async (declared: Parameters<typeof servedI18n>[0], locale: string) =>
refused((await makeEngine(servedI18n(declared))).insert('lsl_task', { due: '' }, { context: { locale } as any }));

it('an en write reads the authored English sentence', async () => {
const err = await refusal(SOURCE_EN, 'en');
expect(err.code).toBe('VALIDATION_FAILED');
expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: 'A task needs a due date.' });
});

it('CONTROL: a zh-CN write still reads the zh-CN row', async () => {
const err = await refusal(SOURCE_EN, 'zh-CN');
expect(err.code).toBe('VALIDATION_FAILED');
expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: '任务必须设置截止日期。' });
});

it('CONTROL: with no sourceLocale declared, an en write walks to the zh-CN row as before', async () => {
const err = await refusal({ defaultLocale: 'zh-CN' }, 'en');
expect(err.code).toBe('VALIDATION_FAILED');
expect(err.fields[0]).toMatchObject({ field: 'due', code: 'rule_violation', message: '任务必须设置截止日期。' });
});
});
31 changes: 26 additions & 5 deletions packages/objectql/src/engine-validation-locale-negotiation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ function servedI18n(bundle: Record<string, any>, fallbackLocale = 'en') {
return typeof fallback === 'string' ? fallback : key;
},
getLocales: () => Object.keys(bundle),
// [#35384] The authored rule message is metadata: it is read off the
// bundle by `translateObject`, as `/meta` reads it, never through `t()`.
getTranslations: (locale: string) => bundle[locale] ?? {},
getFallbackLocale: () => fallbackLocale,
};
}

Expand All @@ -105,6 +109,9 @@ const DUTY_SCHEMA = {
form: { type: 'select', label: 'Form' },
status: { type: 'select', label: 'Status' },
return_note: { type: 'text', label: 'Return note' },
// [#35384] Refused by a BUILT-IN message (`max_length`), the sentence the
// `t()` bridge still carries: the probe of what locale the bridge asks.
code: { type: 'text', label: 'Code', maxLength: 3 },
},
validations: [{
type: 'script',
Expand Down Expand Up @@ -168,6 +175,22 @@ async function refusalFor(header: string, i18n: ReturnType<typeof servedI18n>):
return (await refusalEnvelopeFor(header, i18n)).message;
}

/**
* [#35384] A write refused by a BUILT-IN message (`code` over its
* `maxLength`), which renders through the `t()` bridge — the one the locale
* negotiation below is asserted on, now that the authored rule message reads
* the bundle through `translateObject` instead.
*/
async function builtinRefusalFor(locale: string | undefined, i18n: Parameters<typeof makeEngine>[0]): Promise<unknown> {
const ql = await makeEngine(i18n);
try {
await ql.update('duly_duty', { id: 'r1', code: 'too long' }, { context: { locale } } as any);
} catch (e) {
return e;
}
throw new Error('expected the write to be rejected');
}

/** PATH B — the cross-path control: a document translator, same bundle, same header. */
function datasetStyleLabelsFor(header: string): string[] {
const locale = preferredLocaleFromHeader(header);
Expand Down Expand Up @@ -278,7 +301,7 @@ describe('#15757 the validation-message bridge negotiates the locale like every
it('asks the service for the locale it actually has, not the tag the client sent', async () => {
const i18n = servedI18n(BUNDLE);
expect(preferredLocaleFromHeader('zh')).toBe('zh');
await refusalFor('zh', i18n);
await builtinRefusalFor(preferredLocaleFromHeader('zh'), i18n);
expect(i18n.asked).not.toContain('zh');
expect(i18n.asked).toContain('zh-CN');
});
Expand All @@ -291,6 +314,7 @@ describe('#15757 the validation-message bridge negotiates the locale like every
it('leaves a locale with no match alone', async () => {
const i18n = servedI18n(BUNDLE);
expect(await refusalFor('de', i18n)).toBe(AUTHORED_EN);
await builtinRefusalFor('de', i18n);
expect(i18n.asked).toContain('de');
});

Expand All @@ -303,12 +327,9 @@ describe('#15757 the validation-message bridge negotiates the locale like every
*/
it('passes the tag through when the service cannot report its locales', async () => {
const asked: string[] = [];
const ql = await makeEngine({
await builtinRefusalFor('zh', {
t: (key: string, locale: string) => { asked.push(locale); return key; },
});
try {
await ql.update('duly_duty', { id: 'r1', status: 'returned' }, { context: { locale: 'zh' } } as any);
} catch { /* expected */ }
expect(asked).toContain('zh');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,10 @@ function servedI18n(bundle: Record<string, any>, fallbackLocale = 'en') {
return typeof fallback === 'string' ? fallback : key;
},
getLocales: () => Object.keys(bundle),
// [#35384] The refusal reads a rule message off the bundle by
// `translateObject`, as `/meta` does, never through `t()`.
getTranslations: (locale: string) => bundle[locale] ?? {},
getFallbackLocale: () => fallbackLocale,
};
}

Expand Down
89 changes: 59 additions & 30 deletions packages/objectql/src/validation/rule-validator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2464,25 +2464,38 @@ describe('evaluateValidationRules — built-in messages are localized (#3957)',
*
* The evaluator emitted the authored sentence verbatim, so a deployment with a
* complete `zh-CN` bundle read platform-generated refusals in Chinese and
* author-written refusals in English **inside one error envelope**. The
* built-in field catalog has resolved through `messages.translate` since #3957;
* what was missing was a key shape for an author's own rule, not a channel.
* author-written refusals in English **inside one error envelope**. What was
* missing was a key shape for an author's own rule, not a channel.
*
* These tests drive the SAME `ValidationMessageContext.translate` hook the
* built-in catalog uses (the engine's `i18nService`, `II18nService.t`
* semantics: the key is echoed back on a miss). If a second i18n path were ever
* added to objectql, this fixture would keep passing through the old one — so
* the address is asserted explicitly, not just the output.
* [#35384] The sentence is metadata (`objects.<o>._validations.<rule>.message`,
* the key `/meta`'s `translateObjectValidations` reads), so these tests drive
* `ValidationMessageContext.labelTranslation` — the bundle and the metadata
* route's `ResolveOptions` the refusal's labels read (#34030) — and never the
* `translate` (`t()`) hook, which carries the built-in messages only. A `t()`
* that would answer a rule message is wired beside it in the first test, so a
* reader that went back to `t()` reads the decoy.
*/
describe('evaluateValidationRules — authored rule messages resolve from the bundle (#14253)', () => {
/** An `II18nService.t`-shaped lookup over a flat key→string map. */
const service = (entries: Record<string, string>) => {
const seen: string[] = [];
/** A `locale|a.b.c` map as the nested per-locale bundle `getTranslations()` hands over. */
const bundleOf = (entries: Record<string, string>): Record<string, Record<string, unknown>> => {
const bundle: Record<string, Record<string, any>> = {};
for (const [address, value] of Object.entries(entries)) {
const [locale, key] = address.split('|');
const parts = key.split('.');
let cur = (bundle[locale] ??= {});
for (const part of parts.slice(0, -1)) cur = cur[part] ??= {};
cur[parts[parts.length - 1]] = value;
}
return bundle;
};
/** `labelTranslation` over `entries`, read in `locale`; counts its calls. */
const service = (entries: Record<string, string>, locale = 'zh-CN') => {
const calls = { count: 0 };
return {
seen,
t: (key: string, locale: string) => {
seen.push(`${locale}|${key}`);
return entries[`${locale}|${key}`] ?? key;
calls,
labelTranslation: () => {
calls.count += 1;
return { bundle: bundleOf(entries) as any, options: { locale } };
},
};
};
Expand Down Expand Up @@ -2512,49 +2525,62 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
}],
});

it('asks for objects.<object>._validations.<rule>.message, and returns what it gets', () => {
it('reads objects.<object>._validations.<rule>.message through labelTranslation, never t()', () => {
const i18n = service({
'zh-CN|objects.duly_duty._validations.standing_no_frequency.message':
'常规任务必须设置频率。',
// Another object's rule of the same name: not this refusal's address.
'zh-CN|objects.other_duty._validations.standing_no_frequency.message': 'WRONG — another object',
});
const [err] = failing(scriptSchema('A standing duty must declare a frequency.'), {}, 'insert', {
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
messages: {
locale: 'zh-CN',
objectName: 'duly_duty',
labelTranslation: i18n.labelTranslation,
translate: (key: string) => (key.includes('._validations.') ? 'WRONG — read through t()' : key),
},
});
expect(err.message).toBe('常规任务必须设置频率。');
expect(i18n.seen).toContain('zh-CN|objects.duly_duty._validations.standing_no_frequency.message');
// The wire vocabulary is unchanged — ADR-0114's `code` does not split
// because a sentence is now translatable.
expect(err.code).toBe('rule_violation');
expect(err.field).toBe('frequency');
});

it('keeps the authored sentence when the bundle has no entry (the key echoes back)', () => {
it('keeps the authored sentence when the bundle has no entry', () => {
const i18n = service({});
const [err] = failing(scriptSchema('A standing duty must declare a frequency.'), {}, 'insert', {
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
});
expect(err.message).toBe('A standing duty must declare a frequency.');
});

it('keeps the authored sentence when the service cannot hand its translations over', () => {
const [err] = failing(scriptSchema('authored'), {}, 'insert', {
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: () => undefined },
});
expect(err.message).toBe('authored');
});

it('does not consult the bundle without an object name or a locale', () => {
const i18n = service({
'zh-CN|objects.duly_duty._validations.standing_no_frequency.message': '常规任务必须设置频率。',
});
expect(failing(scriptSchema('authored'), {}, 'insert', {
messages: { locale: 'zh-CN', translate: i18n.t },
messages: { locale: 'zh-CN', labelTranslation: i18n.labelTranslation },
})[0].message).toBe('authored');
expect(failing(scriptSchema('authored'), {}, 'insert', {
messages: { objectName: 'duly_duty', translate: i18n.t },
messages: { objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
})[0].message).toBe('authored');
expect(i18n.seen).toEqual([]);
expect(i18n.calls.count).toBe(0);
});

it('survives a throwing i18n service — a 400 must not become a 500', () => {
const [err] = failing(scriptSchema('authored'), {}, 'insert', {
messages: {
locale: 'zh-CN',
objectName: 'duly_duty',
translate: () => { throw new Error('i18n exploded'); },
labelTranslation: () => { throw new Error('i18n exploded'); },
},
});
expect(err.message).toBe('authored');
Expand All @@ -2566,7 +2592,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
'zh-CN|objects.duly_duty._validations.contact_email.message': '联系邮箱格式不正确。',
'zh-CN|objects.duly_duty._validations.payload_shape.message': '负载结构不符合约定。',
});
const messages = { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t };
const messages = { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation };

const fsm = {
fields: { status: { type: 'select', label: '状态' } },
Expand Down Expand Up @@ -2623,7 +2649,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
}],
};
const [err] = failing(schema, { account_type: 'enterprise', approver: null }, 'insert', {
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
});
expect(err.message).toBe('企业客户需要审批人。');
});
Expand All @@ -2643,7 +2669,7 @@ describe('evaluateValidationRules — authored rule messages resolve from the bu
}],
};
const [err] = failing(schema, {}, 'insert', {
messages: { locale: 'zh-CN', objectName: 'duly_duty', translate: i18n.t },
messages: { locale: 'zh-CN', objectName: 'duly_duty', labelTranslation: i18n.labelTranslation },
});
expect(err.message).toMatch(/could not be evaluated/);
expect(err.message).not.toBe('这条不该出现。');
Expand All @@ -2666,8 +2692,11 @@ describe('evaluateValidationRules — a tenant-rewritten rule message beats the
const PACKAGED = 'A standing duty must declare a frequency.';
const REWRITE = 'Pick how often this duty repeats.';
const ZH = '常规任务必须设置频率。';
const KEY = 'zh-CN|objects.duly_duty._validations.standing_no_frequency.message';
const t = (key: string, locale: string) => ({ [KEY]: ZH } as Record<string, string>)[`${locale}|${key}`] ?? key;
// [#35384] The catalog entry as the bundle `labelTranslation` hands over.
const labelTranslation = () => ({
bundle: { 'zh-CN': { objects: { duly_duty: { _validations: { standing_no_frequency: { message: ZH } } } } } } as any,
options: { locale: 'zh-CN' },
});

const failing = (schema: any, data: Record<string, unknown>, opts: Record<string, unknown>) => {
try {
Expand All @@ -2691,7 +2720,7 @@ describe('evaluateValidationRules — a tenant-rewritten rule message beats the
});
const packagedRule = (name: string) => (name === 'standing_no_frequency' ? scriptRule(PACKAGED) : undefined);
const messages = (extra: Record<string, unknown> = {}) =>
({ locale: 'zh-CN', objectName: 'duly_duty', translate: t, ...extra });
({ locale: 'zh-CN', objectName: 'duly_duty', labelTranslation, ...extra });

it('returns the rewrite as written in a non-default locale', () => {
const [err] = failing(schemaWith(REWRITE), {}, { messages: messages({ packagedRule }) });
Expand Down
Loading
Loading