Skip to content

Commit 1a6b330

Browse files
committed
fix(i18n): a tenant-rewritten rule message beats the packaged translation on both readers
ADR-0029 D9.2a. translateObjectValidations (the /meta overlay) and the rule evaluator's authoredRuleMessage (the refusal) now apply the catalog only while the served message still equals the packaged rule's of the same name, judged by the one predicate: valueOverridesPackagedBase, which objectql reaches through the exported scalarOverridesPackagedBase (its key union gains 'message'). The engine's validation message context carries the packaged owner's rule lookup. Claude-Session: https://claude.ai/code/session_01L6bhgW82YGUW8s8X4Dgiqc Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7976cc1 commit 1a6b330

6 files changed

Lines changed: 166 additions & 15 deletions

File tree

‎packages/objectql/src/engine-validation-messages.ts‎

Lines changed: 71 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,15 @@
3333
* closure, which runs after `validationMessageContext` has returned and sees
3434
* whatever service `setI18nService` has installed by then, as it did.
3535
* `setI18nService` itself stays in the class: it is the field's setter.
36+
* `registry` (ADR-0029 D9.2a, the packaged rule lookup) goes as a getter too.
3637
*
3738
* This module imports the engine only as a TYPE, so there is no module cycle
3839
* at run time, and nothing re-exports it, so the published surface does not
3940
* move.
4041
*/
4142

4243
import type { ObjectQL } from './engine.js';
44+
import type { ValidationMessageContext } from './validation/record-validator.js';
4345
import { objectLabelKey, resolveBundleLocale } from '@objectstack/spec/system';
4446

4547
/**
@@ -52,22 +54,88 @@ import { objectLabelKey, resolveBundleLocale } from '@objectstack/spec/system';
5254
*/
5355
export interface ValidationMessageHost {
5456
readonly i18nService: ObjectQL['i18nService'];
57+
readonly registry: ObjectQL['registry'];
5558
negotiatedMessageLocale: ObjectQL['negotiatedMessageLocale'];
5659
}
5760

58-
/** The body of `ObjectQL#validationMessageContext`; the method's docblock there is its contract. */
61+
/**
62+
* The body of `ObjectQL#validationMessageContext`; the method's docblock there is its contract.
63+
*
64+
* [ADR-0029 D9.2a] It also carries `packagedRule` (`ValidationMessageContext`),
65+
* the lookup the rule evaluator judges a tenant's rewrite of a rule message by,
66+
* when the object has a packaged owner — see {@link packagedRuleLookup}.
67+
*/
5968
export function validationMessageContext(
60-
this: Pick<ValidationMessageHost, 'i18nService' | 'negotiatedMessageLocale'>,
69+
this: Pick<ValidationMessageHost, 'i18nService' | 'registry' | 'negotiatedMessageLocale'>,
6170
objectName: string,
6271
// Only `locale` is read — narrower than `ExecutionContext` so both the
6372
// resolved and the input-shaped envelope satisfy it.
6473
context?: { locale?: string },
65-
): { locale?: string; translate?: (key: string, locale: string, params?: Record<string, unknown>) => string; objectName: string } {
74+
): ValidationMessageContext & { objectName: string } {
6675
const t = this.i18nService?.t;
76+
const packagedRule = packagedRuleLookup(this.registry, objectName);
6777
return {
6878
objectName,
6979
locale: this.negotiatedMessageLocale(context?.locale),
7080
translate: t ? (key, locale, params) => t.call(this.i18nService, key, locale, params) : undefined,
81+
...(packagedRule !== undefined ? { packagedRule } : {}),
82+
};
83+
}
84+
85+
/**
86+
* How deep {@link packagedRuleLookup} follows `conditional` branches — the
87+
* bound `/meta`'s `translateObjectValidations` walks to, so both readers judge
88+
* the same branches.
89+
*/
90+
const MAX_VALIDATION_DEPTH = 10;
91+
92+
/**
93+
* [ADR-0029 D9.2a] The packaged (code-shipped) rule of a name on `objectName`,
94+
* for the rule evaluator's divergence test.
95+
*
96+
* The declaration is the packaged OWNER's (`getPackagedObjectOwner`, pre-fold),
97+
* the same body `/meta` hands `translateObject` as `packagedBase` through
98+
* `getPackagedObjectBase`, so both readers compare a served message against one
99+
* packaged rule. Rules are keyed by `name`, each `conditional` branch under its
100+
* own name; the first rule of a name wins, as on `/meta`.
101+
*
102+
* `undefined` — nothing inferred, the catalog applies — when no packaged owner
103+
* is registered for the object, or the registry cannot answer (a partial
104+
* double). The index is built on the first lookup, which a write that refuses
105+
* nothing never makes.
106+
*/
107+
function packagedRuleLookup(
108+
registry: ValidationMessageHost['registry'] | undefined,
109+
objectName: string,
110+
): ((ruleName: string) => unknown) | undefined {
111+
if (typeof registry?.getPackagedObjectOwner !== 'function') return undefined;
112+
let definition: unknown;
113+
try {
114+
definition = registry.getPackagedObjectOwner(objectName)?.definition;
115+
} catch {
116+
// A read over in-memory contributors must not turn a 400 into a 500.
117+
return undefined;
118+
}
119+
if (!definition || typeof definition !== 'object') return undefined;
120+
const validations = (definition as { validations?: unknown }).validations;
121+
let byName: Map<string, unknown> | undefined;
122+
return (ruleName) => {
123+
if (byName === undefined) {
124+
const index = new Map<string, unknown>();
125+
const visit = (raw: unknown, depth: number): void => {
126+
if (!raw || typeof raw !== 'object' || depth >= MAX_VALIDATION_DEPTH) return;
127+
const rule = raw as { type?: unknown; name?: unknown; then?: unknown; otherwise?: unknown };
128+
if (rule.type === 'conditional') {
129+
visit(rule.then, depth + 1);
130+
visit(rule.otherwise, depth + 1);
131+
return;
132+
}
133+
if (typeof rule.name === 'string' && rule.name.length > 0 && !index.has(rule.name)) index.set(rule.name, rule);
134+
};
135+
if (Array.isArray(validations)) for (const raw of validations) visit(raw, 0);
136+
byName = index;
137+
}
138+
return byName.get(ruleName);
71139
};
72140
}
73141

‎packages/objectql/src/engine.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9545,8 +9545,10 @@ export class ObjectQL implements IObjectQLEngine {
95459545
): { locale?: string; translate?: (key: string, locale: string, params?: Record<string, unknown>) => string; objectName: string } {
95469546
// [#25522 cut 1] The body moved to `engine-validation-messages.ts` (see `ValidationMessageHost`).
95479547
const readI18nService = () => this.i18nService;
9548+
const readRegistry = () => this._registry;
95489549
const host: ThisParameterType<typeof validationMessageContext> = {
95499550
get i18nService() { return readI18nService(); },
9551+
get registry() { return readRegistry(); },
95509552
negotiatedMessageLocale: (...a) => this.negotiatedMessageLocale(...a),
95519553
};
95529554
return validationMessageContext.call(host, objectName, context);

‎packages/objectql/src/validation/record-validator.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,21 @@ export interface ValidationMessageContext {
404404
translate?: ValidationMessageTranslator;
405405
/** Object name — needed to address the field's label in the bundle. */
406406
objectName?: string;
407+
/**
408+
* [ADR-0029 D9.2a] The PACKAGED (code-shipped) declaration of the rule of
409+
* this name on `objectName` — a `conditional` branch addressed by its own
410+
* name — read from the packaged owner's declaration, the base `/meta` hands
411+
* its translator as `packagedBase`. An authored `rule.message` that diverged
412+
* from it is a tenant's rewrite, and the catalog (the packaged rule's
413+
* translation) is not applied to it.
414+
*
415+
* Absent when no packaged owner is registered for the object (a
416+
* runtime-authored object, a registry-less host): nothing is inferred and
417+
* the catalog applies, as on `/meta` with no base. Present, `undefined`
418+
* means the packaged declaration carries no rule of that name, so the
419+
* served rule was authored after the fact.
420+
*/
421+
packagedRule?: (ruleName: string) => unknown;
407422
}
408423

409424
/**

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ import { recordAdvisoryHit } from '@objectstack/core';
243243
// reports it unconditionally, even under `systemFields: false`), and the
244244
// engine's whole by-id addressing reads that key (`idAddressesThisRow`,
245245
// `addressKey: 'id'`).
246-
import { SystemFieldName, objectValidationMessageKey } from '@objectstack/spec/system';
246+
import { SystemFieldName, objectValidationMessageKey, scalarOverridesPackagedBase } from '@objectstack/spec/system';
247247
import Ajv, { type ValidateFunction } from 'ajv';
248248
// #5029 — `format` is NOT built into ajv 8; it ships in this separate package.
249249
// See the `const ajv` note below for why the runtime registers it.
@@ -3759,13 +3759,28 @@ export function emitValidationAdvisories(
37593759
*
37603760
* `rule.name` is the address — including a nested `conditional` branch's own
37613761
* name, since the branch is the rule whose message the caller sees.
3762+
*
3763+
* ## The catalog loses to a tenant's rewrite — ADR-0029 D9.2a
3764+
*
3765+
* The catalog entry translates the PACKAGED rule. A message that diverged from
3766+
* the packaged rule of the same name (`messages.packagedRule`) is a tenant's
3767+
* rewrite and is returned as written, in every locale. The test is
3768+
* `scalarOverridesPackagedBase`, the one comparison `/meta`'s
3769+
* `translateObjectValidations` judges the same message by (⛔ never a second
3770+
* one here), so the served rule and the refusal of the same write keep
3771+
* showing one sentence. A rule the packaged declaration does not carry counts
3772+
* as diverged; no packaged rule lookup means nothing is inferred.
37623773
*/
37633774
function authoredRuleMessage(
37643775
rule: Pick<BaseRule, 'name' | 'message'>,
37653776
messages: ValidationMessageContext | undefined,
37663777
): string {
37673778
if (messages?.translate && messages.objectName && messages.locale
37683779
&& typeof rule.name === 'string' && rule.name.length > 0) {
3780+
if (messages.packagedRule
3781+
&& scalarOverridesPackagedBase(messages.packagedRule(rule.name) ?? {}, 'message', rule.message)) {
3782+
return rule.message;
3783+
}
37693784
const key = objectValidationMessageKey(messages.objectName, rule.name);
37703785
try {
37713786
const translated = messages.translate(key, messages.locale);

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,9 @@ describe('ADR-0029 D9.2a a tenant-rewritten rule message beats the packaged tran
299299
wrapper: AUTHORED.wrapper,
300300
vip_branch: REWRITE.vip_branch,
301301
standard_branch: ZH.standard_branch,
302+
// A rule the packaged object does not declare was authored after the fact.
303+
tenant_only_rule: 'Our own rule, in our own words.',
302304
});
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.');
305305
});
306306

307307
it('counts every named rule as authored when the packaged object declares none', () => {

‎packages/spec/src/system/i18n-resolver.ts‎

Lines changed: 60 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3852,10 +3852,21 @@ function builtinSystemFieldLabel(
38523852
*
38533853
* ⛔ The three conservative edges above are therefore load-bearing in two
38543854
* places. Widening any of them widens the fold's precedence rule too.
3855+
*
3856+
* ## `message` — a validation rule's, judged on both of its readers
3857+
*
3858+
* A rule's `message` is served on `/meta` ({@link translateObjectValidations})
3859+
* and returned in the refusal of a write by `@objectstack/objectql`'s rule
3860+
* evaluator, and both apply the catalog only while the served message still
3861+
* equals the packaged rule's of the same name (ADR-0029 D9.2a). The evaluator
3862+
* asks through this export, with the packaged RULE as `base`, so a tenant's
3863+
* rewrite is judged by one comparison on both readers and the two keep
3864+
* answering one sentence. The key is the only thing it adds: the three edges
3865+
* above hold for it unchanged.
38553866
*/
38563867
export function scalarOverridesPackagedBase(
38573868
base: unknown,
3858-
key: 'label' | 'pluralLabel' | 'description',
3869+
key: 'label' | 'pluralLabel' | 'description' | 'message',
38593870
value: unknown,
38603871
): boolean {
38613872
return valueOverridesPackagedBase(base, key, value);
@@ -3985,21 +3996,30 @@ const MAX_VALIDATION_DEPTH = 10;
39853996
* branches are translated and the wrapper's `message` is left as authored, the
39863997
* way the extractor leaves it unscaffolded.
39873998
*
3988-
* ## No packaged-base comparison
3989-
*
3990-
* Unlike the object's scalars, a rule message is a flat `catalog ?? document`,
3991-
* as a field `label` is. The evaluator translates a refusal without consulting
3992-
* any packaged base, and a divergence rule applied here alone would serve one
3993-
* sentence on `/meta` and another in the refusal of the same write, which is
3994-
* the split this overlay exists to close.
3999+
* ## The catalog loses to a tenant's rewrite — ADR-0029 D9.2a
4000+
*
4001+
* The catalog translates the PACKAGED rule, so a served message that diverged
4002+
* from the packaged rule of the same name — a tenant overlay that kept the
4003+
* rule and reworded it — is authored data and keeps its text, judged by
4004+
* {@link valueOverridesPackagedBase} (⛔ never a second comparison) against
4005+
* the rule in {@link TranslateDocumentOptions.packagedBase}'s `validations`,
4006+
* a `conditional` branch by its own name. A rule the base does not declare was
4007+
* authored after the fact, and its message counts as diverged; no base
4008+
* supplied means nothing is inferred and the catalog applies.
4009+
*
4010+
* The evaluator applies the same rule to its refusal, through the exported
4011+
* {@link scalarOverridesPackagedBase} and the packaged owner's declaration the
4012+
* engine hands it, so `/meta` and the refusal of the same write still show one
4013+
* sentence for one rule and locale.
39954014
*/
39964015
function translateObjectValidations(
39974016
validations: unknown,
39984017
bundle: TranslationBundle | undefined,
39994018
objectName: string,
4000-
opts: ResolveOptions | undefined,
4019+
opts: TranslateDocumentOptions | undefined,
40014020
): unknown {
40024021
if (!Array.isArray(validations) || !bundle) return validations;
4022+
const packaged = packagedRulesByName(opts?.packagedBase);
40034023
const translateRule = (raw: unknown, depth: number): unknown => {
40044024
const rule = asRecord(raw);
40054025
if (rule === undefined || depth >= MAX_VALIDATION_DEPTH) return raw;
@@ -4014,6 +4034,9 @@ function translateObjectValidations(
40144034
};
40154035
}
40164036
if (typeof rule.name !== 'string' || rule.name.length === 0) return raw;
4037+
if (packaged !== undefined && valueOverridesPackagedBase(packaged.get(rule.name) ?? {}, 'message', rule.message)) {
4038+
return raw;
4039+
}
40174040
const path = objectValidationMessageKey(objectName, rule.name).split('.');
40184041
for (const code of localeChain(opts)) {
40194042
const candidate = path.reduce<unknown>(
@@ -4035,6 +4058,32 @@ function translateObjectValidations(
40354058
return changed ? next : validations;
40364059
}
40374060

4061+
/**
4062+
* The packaged object's validation rules by `name`, each `conditional` branch
4063+
* under its own name to {@link MAX_VALIDATION_DEPTH}, for
4064+
* {@link translateObjectValidations}' divergence test. `undefined` when no
4065+
* base is known; an empty map when the base declares no rules, so every rule
4066+
* on the served document then counts as authored. The first rule of a name
4067+
* wins.
4068+
*/
4069+
function packagedRulesByName(packagedBase: unknown): Map<string, Record<string, unknown>> | undefined {
4070+
const base = asRecord(packagedBase);
4071+
if (base === undefined) return undefined;
4072+
const byName = new Map<string, Record<string, unknown>>();
4073+
const visit = (raw: unknown, depth: number): void => {
4074+
const rule = asRecord(raw);
4075+
if (rule === undefined || depth >= MAX_VALIDATION_DEPTH) return;
4076+
if (rule.type === 'conditional') {
4077+
visit(rule.then, depth + 1);
4078+
visit(rule.otherwise, depth + 1);
4079+
return;
4080+
}
4081+
if (typeof rule.name === 'string' && rule.name.length > 0 && !byName.has(rule.name)) byName.set(rule.name, rule);
4082+
};
4083+
if (Array.isArray(base.validations)) for (const raw of base.validations) visit(raw, 0);
4084+
return byName;
4085+
}
4086+
40384087
/**
40394088
* Apply the active locale to an object metadata document. Translates the
40404089
* object's `label` / `pluralLabel` / `description`, walks each field to
@@ -4091,6 +4140,8 @@ function translateObjectValidations(
40914140
* application of the same rule (ADR-0029 D9.2a, as {@link translateView}
40924141
* applies it), judged per view against the packaged object's own `listViews` —
40934142
* see {@link translateObjectListViews}.
4143+
* Each `validations[].message` follows it too, judged against the packaged
4144+
* rule of the same name — see {@link translateObjectValidations}.
40944145
*
40954146
* ## A field's translated help is served on `description` — ADR-0029 D9.2a
40964147
*

0 commit comments

Comments
 (0)