Skip to content

Commit 7e802e1

Browse files
committed
wip: i18n call-site gate refuses a namespace-only key outside its frame
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibxDqYaHT7GBjAY9FzB
1 parent b618224 commit 7e802e1

1 file changed

Lines changed: 126 additions & 15 deletions

File tree

‎ui/scripts/check-i18n-call-site-keys.mjs‎

Lines changed: 126 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1325,8 +1325,22 @@ function staticTextSegments(node, source) {
13251325
* is a directory of partial packs; the `studio` namespace is NOT one (it is a
13261326
* `{token}` string table of its own, read by `collectDesignerKeys` in
13271327
* `check-i18n-dead-keys.mjs`).
1328+
*
1329+
* Each directory is declared WITH ITS FRAME: the source directories (relative
1330+
* to `ui/`) whose files render under the gate that fetches the namespace. A key
1331+
* only the namespace defines is a raw key anywhere else, so class 9
1332+
* (`namespace-key-outside-frame`) refuses it at a call site outside these
1333+
* directories. The directory is the frame's outer bound; which files INSIDE it
1334+
* a page outside the frame imports is the census of that namespace's boundary
1335+
* test (`marketplaceNamespaceBoundary.test.ts` for this one). A namespace is
1336+
* added here or nowhere, so it cannot arrive without its frame.
13281337
*/
1329-
export const PACK_NAMESPACE_DIRS = Object.freeze(['packages/i18n/src/namespaces/marketplace/']);
1338+
export const PACK_NAMESPACE_FRAMES = Object.freeze({
1339+
'packages/i18n/src/namespaces/marketplace/': Object.freeze(['packages/app-shell/src/console/marketplace/']),
1340+
});
1341+
1342+
/** The pack-shaped namespace directories: the keys of {@link PACK_NAMESPACE_FRAMES}. */
1343+
export const PACK_NAMESPACE_DIRS = Object.freeze(Object.keys(PACK_NAMESPACE_FRAMES));
13301344

13311345
/** Every directory a pack key is DEFINED in: the packs, then the namespaces. */
13321346
export const PACK_DEFINITION_DIRS = Object.freeze(['packages/i18n/src/locales/', ...PACK_NAMESPACE_DIRS]);
@@ -1348,21 +1362,28 @@ export const PACK_DEFINITION_DIRS = Object.freeze(['packages/i18n/src/locales/',
13481362
* A leaf defined in two of the files — or a leaf in one that is a group in
13491363
* another — THROWS: two homes for one key cannot both be what renders.
13501364
*
1351-
* @returns {{ leaves: Set<string>, branches: Set<string>, values: Map<string, string> }}
1365+
* `namespaceOf` maps every leaf a namespace file defines to that namespace's
1366+
* directory; a leaf absent from it is resident in the eager pack.
1367+
*
1368+
* @param {readonly string[]} [namespaceDirs] the namespace directories to read (default {@link PACK_NAMESPACE_DIRS})
1369+
* @returns {{ leaves: Set<string>, branches: Set<string>, values: Map<string, string>, namespaceOf: Map<string, string> }}
13521370
*/
1353-
export function collectEnKeys(root) {
1371+
export function collectEnKeys(root, namespaceDirs = PACK_NAMESPACE_DIRS) {
13541372
const leaves = new Set();
13551373
const branches = new Set();
13561374
const values = new Map();
13571375
const homeOf = new Map();
1376+
const namespaceOf = new Map();
13581377
// The pack is required; a namespace's `en` file is read when it exists. A
13591378
// missing one cannot hide anything: its keys simply are not defined, so every
13601379
// call site that asks for one is reported as asking for a missing key.
13611380
const files = [
1362-
join(root, 'packages/i18n/src/locales/en.ts'),
1363-
...PACK_NAMESPACE_DIRS.map((dir) => join(root, dir, 'en.ts')).filter((file) => existsSync(file)),
1381+
{ file: join(root, 'packages/i18n/src/locales/en.ts'), namespace: null },
1382+
...namespaceDirs
1383+
.map((dir) => ({ file: join(root, dir, 'en.ts'), namespace: dir }))
1384+
.filter(({ file }) => existsSync(file)),
13641385
];
1365-
for (const file of files) {
1386+
for (const { file, namespace } of files) {
13661387
const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
13671388

13681389
const unwrap = (node) => {
@@ -1416,14 +1437,15 @@ export function collectEnKeys(root) {
14161437
}
14171438
leaves.add(path);
14181439
homeOf.set(path, file);
1440+
if (namespace !== null) namespaceOf.set(path, namespace);
14191441
const text = staticString(value, source);
14201442
if (text !== null) values.set(path, text);
14211443
}
14221444
}
14231445
};
14241446
walk(literal, '');
14251447
}
1426-
return { leaves, branches, values };
1448+
return { leaves, branches, values, namespaceOf };
14271449
}
14281450

14291451
// ── source walk ──────────────────────────────────────────────────────────────
@@ -1976,11 +1998,40 @@ function resolveFactoryTable(root, source, argument, parseModule) {
19761998
*/
19771999
export function analyze(
19782000
root,
1979-
/** @type {{ families?: DynamicKeyFamily[], handRolled?: { file: string, name: string }[] }} */
1980-
{ families = DYNAMIC_KEY_FAMILIES, handRolled = HAND_ROLLED_TABLES } = {},
2001+
/** @type {{ families?: DynamicKeyFamily[], handRolled?: { file: string, name: string }[], frames?: Record<string, readonly string[]> }} */
2002+
{ families = DYNAMIC_KEY_FAMILIES, handRolled = HAND_ROLLED_TABLES, frames = PACK_NAMESPACE_FRAMES } = {},
19812003
) {
1982-
const { leaves, branches, values } = collectEnKeys(root);
2004+
for (const [dir, frame] of Object.entries(frames)) {
2005+
if (!Array.isArray(frame) || frame.length === 0 || frame.some((prefix) => typeof prefix !== 'string' || !prefix.endsWith('/'))) {
2006+
throw new Error(
2007+
`the pack namespace \`${dir}\` declares no frame: list the source directories (each ending in \`/\`) ` +
2008+
'whose files render under the gate that fetches it, in PACK_NAMESPACE_FRAMES',
2009+
);
2010+
}
2011+
}
2012+
const { leaves, branches, values, namespaceOf } = collectEnKeys(root, Object.keys(frames));
19832013
const resolvesLeaf = (key) => leaves.has(key) || PLURAL_SUFFIXES.some((suffix) => leaves.has(key + suffix));
2014+
2015+
// Class 9 (objectstack#30645): which namespace a key lives in ONLY, or null
2016+
// when the eager pack answers it (or nothing does — class 1's business).
2017+
const residentLeaves = [...leaves].filter((key) => !namespaceOf.has(key));
2018+
const namespaceOnlyKey = (key) => {
2019+
const forms = [key, ...PLURAL_SUFFIXES.map((suffix) => key + suffix)].filter((form) => leaves.has(form));
2020+
if (forms.length === 0 || forms.some((form) => !namespaceOf.has(form))) return null;
2021+
return namespaceOf.get(forms[0]);
2022+
};
2023+
const namespaceOnlyHead = (head) => {
2024+
if (residentLeaves.some((key) => key.startsWith(head))) return null;
2025+
const first = [...namespaceOf.keys()].find((key) => key.startsWith(head));
2026+
return first === undefined ? null : namespaceOf.get(first);
2027+
};
2028+
/** Per namespace: the call-site keys read inside its frame — the live control on class 9. */
2029+
const framedReads = new Map(Object.keys(frames).map((dir) => [dir, 0]));
2030+
const judgeFrame = (dir, relPath, at, detail) => {
2031+
if (dir === null) return;
2032+
if (frames[dir].some((prefix) => relPath.startsWith(prefix))) framedReads.set(dir, framedReads.get(dir) + 1);
2033+
else findings.push({ reason: 'namespace-key-outside-frame', ...at, detail, expected: dir, frame: frames[dir] });
2034+
};
19842035
// Materialised once, not inside the predicate: spreading a 2.6k-entry Set per
19852036
// candidate head is the shape that made `all-locales-key-parity` quadratic
19862037
// (7.51s -> 25ms once hoisted; see AGENTS.md 测试纪律).
@@ -2406,6 +2457,9 @@ export function analyze(
24062457
referencedKeys.add(key);
24072458
for (const suffix of PLURAL_SUFFIXES) referencedKeys.add(key + suffix);
24082459
if (returnsObjects && branches.has(key)) referencedBranches.add(key);
2460+
2461+
if (resolvesLeaf(key)) judgeFrame(namespaceOnlyKey(key), relPath, at, key);
2462+
else if (returnsObjects && branches.has(key)) judgeFrame(namespaceOnlyHead(`${key}.`), relPath, at, `${key}.*`);
24092463
}
24102464

24112465
// objectui#3810 — the inline default is dead code the moment the key
@@ -2542,6 +2596,8 @@ export function analyze(
25422596
const head = staticHead(argument);
25432597
if (head && !headMatches(head)) {
25442598
findings.push({ reason: 'missing-prefix', ...at, detail: head });
2599+
} else if (head) {
2600+
judgeFrame(namespaceOnlyHead(head), relPath, at, `${head}*`);
25452601
}
25462602
// Reverse-sweep bookkeeping: a leaf sharing this prefix is a
25472603
// possible runtime target of the substitution, so it is live —
@@ -2652,7 +2708,16 @@ export function analyze(
26522708
findings.push({ reason: 'undeclared-dynamic-family', ...observed.sites[0], detail: head });
26532709
}
26542710

2655-
return { findings, counters, enKeyCount: leaves.size, referencedKeys, referencedBranches, dynamicHeads, dynamicFamilies };
2711+
return {
2712+
findings,
2713+
counters,
2714+
enKeyCount: leaves.size,
2715+
referencedKeys,
2716+
referencedBranches,
2717+
dynamicHeads,
2718+
dynamicFamilies,
2719+
framedReads,
2720+
};
26562721
}
26572722

26582723
// ── baseline ─────────────────────────────────────────────────────────────────
@@ -2828,6 +2893,15 @@ const HINTS = {
28282893
' downstream of `t()`, is spelled with SINGLE braces (`{x}`) and is out of this rule\'s range' +
28292894
' by construction. Same rule, same reasons, over the copy TABLES:' +
28302895
' `packages/i18n/src/__tests__/fallback-placeholder-spelling-3512.test.ts`.',
2896+
'namespace-key-outside-frame':
2897+
'The key EXISTS, but only in a lazy pack-shaped namespace (PACK_NAMESPACE_FRAMES), and this call' +
2898+
' site is outside the directories that namespace\'s frame wraps (objectstack#30645). Only the frame' +
2899+
' fetches the namespace, so here the key renders raw — or in English, when an earlier visit fetched' +
2900+
' only `en`. Every pack gate is green on it, because the namespace is part of the pack to them. Fix' +
2901+
' it by moving the key back into the resident pack (`packages/i18n/src/locales/<code>.ts`, all ten' +
2902+
' languages, out of the namespace\'s ten partial packs), or by reading it only inside the frame. ⛔' +
2903+
' Do NOT widen the frame to cover this file: a frame is the directories that render under the gate,' +
2904+
' and a file outside them gains no fetch from being listed.',
28312905
'dead-sibling-fallback':
28322906
'The key EXISTS in `en`, and this fallback is written as the call\'s SIBLING' +
28332907
' (`t(key) || \'English\'`) rather than as an argument — so it is dead on every path, not just' +
@@ -2850,7 +2924,7 @@ const invokedDirectly = isEntrypoint(import.meta.url);
28502924

28512925
if (invokedDirectly) {
28522926
const root = resolve(scriptDir, '..');
2853-
const { findings, counters, enKeyCount } = analyze(root);
2927+
const { findings, counters, enKeyCount, framedReads } = analyze(root);
28542928

28552929
// Guard against a refactor quietly emptying the comparison: with no keys and
28562930
// no call sites every assertion below is trivially satisfied. Same reason
@@ -2921,6 +2995,20 @@ if (invokedDirectly) {
29212995
process.exit(1);
29222996
}
29232997

2998+
// Class 9's floor (objectstack#30645): a namespace whose own frame reads none
2999+
// of its keys means the frame or the namespace reader is wrong, and "0 outside
3000+
// the frame" would then be read off a rule that sees no namespace key at all.
3001+
for (const [dir, reads] of framedReads) {
3002+
if (reads === 0) {
3003+
console.error(
3004+
`The namespace-frame scan collapsed: no call site inside the frame of \`${dir}\` reads a key only that` +
3005+
' namespace defines. Either PACK_NAMESPACE_FRAMES names the wrong directories or the namespace is no' +
3006+
' longer read, and class 9 would be passing on an empty set.',
3007+
);
3008+
process.exit(1);
3009+
}
3010+
}
3011+
29243012
const { unexpected, stale } = applyBaseline(findings, readBaseline(root));
29253013

29263014
console.log(
@@ -2970,6 +3058,11 @@ if (invokedDirectly) {
29703058
`${counters.headlessDynamicKeySites} dynamic call site(s) with no static head at all, ` +
29713059
`${counters.keyBuilderSites} head(s) read off a key-building helper rather than a call site.`,
29723060
);
3061+
console.log(
3062+
`Namespace frames: ${framedReads.size} pack-shaped namespace(s) — ` +
3063+
[...framedReads].map(([dir, reads]) => `${dir} read ${reads} time(s) inside its frame`).join(', ') +
3064+
'; a key only a namespace defines is refused anywhere outside that namespace\'s frame.',
3065+
);
29733066
console.log(
29743067
`Sibling fallbacks: ${counters.siblingFallbacks} call site(s) sit left of a ||/?? — ` +
29753068
`${counters.judgedSiblingFallbacks} judged, ${counters.computedSiblingFallbacks} with a non-literal ` +
@@ -2987,6 +3080,7 @@ if (invokedDirectly) {
29873080
const parity = unexpected.filter((finding) => finding.reason === 'interpolation-parity');
29883081
const siblings = unexpected.filter((finding) => finding.reason === 'dead-sibling-fallback');
29893082
const spelling = unexpected.filter((finding) => finding.reason === 'unresolvable-default-spelling');
3083+
const outsideFrame = unexpected.filter((finding) => finding.reason === 'namespace-key-outside-frame');
29903084
// objectui#4964's classes read on their own too: they are all about a template
29913085
// family whose HEAD resolves, which is precisely the case the two key classes
29923086
// above declare out of scope.
@@ -3008,7 +3102,10 @@ if (invokedDirectly) {
30083102
'unresolvable-default-spelling',
30093103
]);
30103104
const keyFindings = unexpected.filter(
3011-
(finding) => !VALUE_CLASSES.has(finding.reason) && !FAMILY_CLASSES.has(finding.reason),
3105+
(finding) =>
3106+
!VALUE_CLASSES.has(finding.reason) &&
3107+
!FAMILY_CLASSES.has(finding.reason) &&
3108+
finding.reason !== 'namespace-key-outside-frame',
30123109
);
30133110

30143111
if (unexpected.length === 0 && stale.length === 0) {
@@ -3018,8 +3115,9 @@ if (invokedDirectly) {
30183115
' createSafeTranslation defaults row repeats it too, every call site passes' +
30193116
' exactly the arguments that value has holes for, every inline defaultValue spells its' +
30203117
' placeholders the one way the provider-less fallback resolves, no call site carries a' +
3021-
' literal fallback beside itself, and every dynamic key family either checks its members' +
3022-
' against a declared vocabulary or says in writing why it has none.',
3118+
' literal fallback beside itself, every dynamic key family either checks its members' +
3119+
' against a declared vocabulary or says in writing why it has none, and no key only a lazy' +
3120+
' namespace defines is read outside that namespace\'s frame.',
30233121
);
30243122
process.exit(0);
30253123
}
@@ -3128,6 +3226,19 @@ if (invokedDirectly) {
31283226
}
31293227
}
31303228

3229+
if (outsideFrame.length > 0) {
3230+
console.error(
3231+
`\n${outsideFrame.length} call site${outsideFrame.length === 1 ? '' : 's'} outside a namespace's frame ` +
3232+
`read${outsideFrame.length === 1 ? 's' : ''} a key only that lazy namespace defines — nothing fetches ` +
3233+
'the namespace there, so the user reads the raw key (or English, if an earlier visit fetched only `en`):',
3234+
);
3235+
for (const finding of outsideFrame) {
3236+
console.error(` ${finding.file}:${finding.line}:${finding.column} [${finding.reason}] ${finding.detail}`);
3237+
console.error(` defined only in: ${finding.expected}en.ts`);
3238+
console.error(` its frame: ${finding.frame.join(', ')}`);
3239+
}
3240+
}
3241+
31313242
if (families.length > 0) {
31323243
console.error(
31333244
`\n${families.length} dynamic-family finding${families.length === 1 ? '' : 's'} — the head resolves, so the` +

0 commit comments

Comments
 (0)