@rexezuge/tooling 1.7.2 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/eslint-boundaries.d.ts +7 -3
- package/dist/eslint-boundaries.d.ts.map +1 -1
- package/dist/eslint-boundaries.js +1 -1
- package/dist/eslint-boundaries.js.map +3 -3
- package/dist/scripts/validate-locales.d.ts +27 -1
- package/dist/scripts/validate-locales.d.ts.map +1 -1
- package/dist/scripts/validate-locales.js +5 -5
- package/dist/scripts/validate-locales.js.map +3 -3
- package/package.json +2 -2
- package/src/eslint-boundaries.ts +51 -14
- package/src/eslint.test.ts +23 -0
- package/src/scripts/validate-locales.convergence.test.ts +82 -1
- package/src/scripts/validate-locales.ts +217 -42
|
@@ -74,12 +74,12 @@ export declare function layerBans(scope: string): readonly LayerBan[];
|
|
|
74
74
|
*/
|
|
75
75
|
type ConfigInput = Parameters<typeof tseslint.config>[number];
|
|
76
76
|
/**
|
|
77
|
-
* The `no-restricted-imports` entries
|
|
77
|
+
* The `no-restricted-imports` entries, one per directory.
|
|
78
78
|
*
|
|
79
79
|
* Written as `group` patterns rather than exact `paths`, so `@myapp/backend-data`
|
|
80
80
|
* and `@myapp/backend-data/dao` are both caught by one entry. `allowTypeImports`
|
|
81
|
-
* is
|
|
82
|
-
*
|
|
81
|
+
* is carried per group rather than per directory, because only the DAO boundary
|
|
82
|
+
* sets it.
|
|
83
83
|
*/
|
|
84
84
|
export declare function restrictedImports(bans: readonly LayerBan[]): ConfigInput[];
|
|
85
85
|
/**
|
|
@@ -93,6 +93,10 @@ export declare function restrictedImports(bans: readonly LayerBan[]): ConfigInpu
|
|
|
93
93
|
* hole was load-bearing there: the credential path reached a banned module
|
|
94
94
|
* through it. `no-restricted-syntax` sees `ImportExpression`, so the boundary is
|
|
95
95
|
* stated a second way.
|
|
96
|
+
*
|
|
97
|
+
* Grouped per directory for the same reason {@link restrictedImports} is: one
|
|
98
|
+
* entry per layer would leave only the last row standing, and `no-restricted-syntax`
|
|
99
|
+
* merges exactly like `no-restricted-imports` does.
|
|
96
100
|
*/
|
|
97
101
|
export declare function restrictedDynamicImports(bans: readonly LayerBan[]): ConfigInput[];
|
|
98
102
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eslint-boundaries.d.ts","sourceRoot":"","sources":["../src/eslint-boundaries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAcjD,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,QAAQ;IACvB;;MAEE;IACF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;MAEE;IACF,QAAQ,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC;;MAEE;IACF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB;;MAEE;IACF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,QAAQ,EAAE,CA2H5D;AAED;;;;GAIG;AACH,KAAK,WAAW,GAAG,UAAU,CAAC,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"eslint-boundaries.d.ts","sourceRoot":"","sources":["../src/eslint-boundaries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,QAAQ,MAAM,mBAAmB,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAcjD,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,QAAQ;IACvB;;MAEE;IACF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;MAEE;IACF,QAAQ,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC;;MAEE;IACF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB;;MAEE;IACF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,QAAQ,EAAE,CA2H5D;AAED;;;;GAIG;AACH,KAAK,WAAW,GAAG,UAAU,CAAC,OAAO,QAAQ,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC;AA+B9D;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,SAAS,QAAQ,EAAE,GAAG,WAAW,EAAE,CAkB1E;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,SAAS,QAAQ,EAAE,GAAG,WAAW,EAAE,CAejF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var t=(a,e)=>d(a,"name",{value:e,configurable:!0});const m=["packages/shared","packages/backend-errors","packages/backend-runtime","packages/backend-data","packages/provider-clients","packages/webdav","packages/dav-store","packages/git-protocol","packages/git-service","packages/backend-services","apps/api","apps/background","apps/web"];function b(a){const e=t(s=>`${a}/${s}`,"at");return[{dir:"packages/shared",ban:[e("*")],message:`${a} packages must not import from other ${a} packages \u2014 this is a zero-dependency base layer`},{dir:"packages/backend-errors",ban:[e("*")],message:`${a} packages must not import from other ${a} packages \u2014 this is a zero-dependency base layer`},{dir:"packages/backend-runtime",ban:[e("backend-data"),e("provider-clients"),e("webdav"),e("dav-store"),e("git-protocol"),e("git-service"),e("backend-services"),e("api"),e("background")],message:"backend-runtime must not import from a higher layer"},{dir:"packages/backend-data",ban:[e("backend-runtime"),e("provider-clients"),e("webdav"),e("dav-store"),e("git-protocol"),e("git-service"),e("backend-services"),e("api"),e("background")],message:"backend-data must not import from a higher layer"},{dir:"packages/provider-clients",ban:[e("backend-data"),e("backend-runtime"),e("backend-services"),e("api"),e("background")],message:"provider-clients must not import DAOs from backend-data"},{dir:"packages/webdav",ban:[e("backend-data"),e("backend-runtime"),e("dav-store"),e("backend-services"),e("api"),e("background")],message:"webdav must not import DAOs from backend-data"},{dir:"packages/git-protocol",ban:[e("backend-data"),e("backend-runtime"),e("git-service"),e("backend-services"),e("api"),e("background")],message:"git-protocol must not import DAOs from backend-data"},{dir:"packages/dav-store",ban:[e("backend-services"),e("api"),e("background")],message:"dav-store must not import from backend-services (higher layer)"},{dir:"packages/git-service",ban:[e("backend-services"),e("api"),e("background")],message:"git-service must not import from backend-services (higher layer)"},{dir:"packages/backend-services",ban:[e("api"),e("background")],message:"backend-services must not import from apps"},{dir:"apps/api",ban:[e("backend-data/dao"),e("backend-data")],allowTypeImports:!0,message:"apps/api must not import DAOs or backend-data values directly; use backend-services instead (type-only imports are allowed)"},{dir:"apps/api",ban:[e("provider-clients")],message:`apps/api must not import provider-clients directly; use ${a}/backend-services instead`},{dir:"apps/api",ban:[e("dav-store")],message:`apps/api must not import dav-store directly; use ${a}/webdav + DO RPC via ${a}/background instead`},{dir:"apps/api",ban:[e("git-service")],message:`apps/api must not import git-service directly; use ${a}/git-protocol + DO RPC via ${a}/background instead`},{dir:"apps/background",ban:[e("api")],message:"apps/background must not import from apps/api"},{dir:"apps/web",ban:[e("*")],message:`${e("apps/web")} ships zero backend dependencies \u2014 this module is the SPA's own copy`}]}t(b,"layerBans");function c(a){const e=new Map;for(const s of a){const r=e.get(s.dir);r?r.push(s):e.set(s.dir,[s])}return e}t(c,"groupedByDir");function g(a){return[...c(a)].map(([e,s])=>({files:[`${e}/**/*.{ts,js,mts,cts,mjs,cjs}`],rules:{"no-restricted-imports":["error",{patterns:s.flatMap(({ban:r,message:n,allowTypeImports:i})=>r.map(o=>({group:[o,`${o}/*`],message:n,...i===!0&&{allowTypeImports:!0}})))}]}}))}t(g,"restrictedImports");function k(a){return[...c(a)].map(([e,s])=>({files:[`${e}/**/*.{ts,js,mts,cts,mjs,cjs}`],rules:{"no-restricted-syntax":["error",...s.flatMap(({ban:r,message:n})=>r.map(i=>({selector:`ImportExpression[source.type='Literal'][source.value=/^${i.replaceAll("/",String.raw`\/`)}/]`,message:`A dynamic import() is not covered by no-restricted-imports, so this layer reaches \`${i}\` through the one syntax that gate does not see. Both say no: ${n}`})))]}}))}t(k,"restrictedDynamicImports");export{m as DEFAULT_PROJECT_DIRS,b as layerBans,k as restrictedDynamicImports,g as restrictedImports};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/eslint-boundaries.ts"],
|
|
4
|
-
"sourcesContent": ["import type tseslint from 'typescript-eslint';\n\n/**\n * The layer table behind the repo lint config's import boundaries.\n *\n * Provenance: the seven `no-restricted-imports` blocks in Durable-DAV's\n * `eslint.config.mjs`, with `@durable-dav/` replaced by the caller's scope.\n * Extracted from `eslint.ts` so the boundary rules — the part a repo actually\n * argues about — are their own module rather than the tail of a 640-line\n * config file.\n *\n * Converged across all nine family repos: `provider-clients` (AWS-AccessBridge,\n * CalDAV-Bridge, Mail-Meow, Mail-Otter), `webdav`/`dav-store` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic), `git-protocol`/`git-service` (Edge-Git).\n * `media-tags`/`subsonic` (Edge-Sonic) carry no boundary block in their source\n * repo — they are unconstrained utility leaves — so they have no layer here.\n *\n * The table is data rather than inline blocks so the dynamic-`import()` guard\n * is generated from the same list: a rule that derived its banned set from\n * another rule's configuration would be a second source of truth for the layer\n * table, and that table is what the docs describe.\n *\n * The table is a superset: a repo without a domain package simply never imports\n * it, so its ban never fires. A layer entry for a directory that does not exist\n * in the consumer matches no file and costs nothing.\n */\n\n/**\n * The directories the boundary rules cover, in the canonical layout.\n *\n * Kept here, beside the table it scopes: `defineRepoLintConfig` filters the\n * canonical layers by `projectDirs`, and a reader of the layer table should not\n * have to open the config assembly to learn which directories it covers.\n */\nexport const DEFAULT_PROJECT_DIRS: readonly string[] = [\n 'packages/shared',\n 'packages/backend-errors',\n 'packages/backend-runtime',\n 'packages/backend-data',\n 'packages/provider-clients',\n 'packages/webdav',\n 'packages/dav-store',\n 'packages/git-protocol',\n 'packages/git-service',\n 'packages/backend-services',\n 'apps/api',\n 'apps/background',\n 'apps/web',\n];\n\n/**\n * One layer's ban list, as the repo-relative package suffixes it may not import.\n *\n * Converged from all nine family repos. `backend-data` and `backend-services`\n * appear in all nine; `provider-clients` is AWS-AccessBridge's, CalDAV-Bridge's,\n * Mail-Meow's and Mail-Otter's; `webdav`/`dav-store` are Durable-DAV's,\n * Durable-DAV-Router's and Edge-Sonic's; `git-protocol`/`git-service` are\n * Edge-Git's. A layer only bans what exists in its repo, so the\n * union is safe: a repo without `provider-clients` simply never imports it.\n *\n * One `dir` may appear in several entries (see `apps/api` below): each entry\n * carries its own message and `allowTypeImports`, because the DAO ban allows\n * type-only imports and the direct-client bans do not.\n */\nexport interface LayerBan {\n /**\n Directory the rule is scoped to.\n */\n readonly dir: string;\n /**\n Package suffixes (relative to `scope`) that may not be imported from here.\n */\n readonly ban: readonly string[];\n /**\n Message shown when the rule fires.\n */\n readonly message: string;\n /**\n Type-only imports are allowed, for the DAO boundary in `apps/api`.\n */\n readonly allowTypeImports?: boolean;\n}\n\n/**\n * The layer table, parameterized by `scope`.\n */\nexport function layerBans(scope: string): readonly LayerBan[] {\n const at = (name: string): string => `${scope}/${name}`;\n return [\n {\n dir: 'packages/shared',\n ban: [at('*')],\n message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,\n },\n {\n dir: 'packages/backend-errors',\n ban: [at('*')],\n message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,\n },\n {\n dir: 'packages/backend-runtime',\n ban: [\n at('backend-data'),\n at('provider-clients'),\n at('webdav'),\n at('dav-store'),\n at('git-protocol'),\n at('git-service'),\n at('backend-services'),\n at('api'),\n at('background'),\n ],\n message: 'backend-runtime must not import from a higher layer',\n },\n {\n dir: 'packages/backend-data',\n ban: [\n at('backend-runtime'),\n at('provider-clients'),\n at('webdav'),\n at('dav-store'),\n at('git-protocol'),\n at('git-service'),\n at('backend-services'),\n at('api'),\n at('background'),\n ],\n message: 'backend-data must not import from a higher layer',\n },\n // Domain protocol layers (layer 2, beside backend-data): each bans the DAO\n // layer, the runtime, its store counterpart where it has one, the service\n // layer and the apps. Sources: provider-clients (AWS-AccessBridge,\n // Mail-Meow), webdav (Durable-DAV, Edge-Sonic), git-protocol (Edge-Git).\n {\n dir: 'packages/provider-clients',\n ban: [at('backend-data'), at('backend-runtime'), at('backend-services'), at('api'), at('background')],\n message: 'provider-clients must not import DAOs from backend-data',\n },\n {\n dir: 'packages/webdav',\n ban: [at('backend-data'), at('backend-runtime'), at('dav-store'), at('backend-services'), at('api'), at('background')],\n message: 'webdav must not import DAOs from backend-data',\n },\n {\n dir: 'packages/git-protocol',\n ban: [at('backend-data'), at('backend-runtime'), at('git-service'), at('backend-services'), at('api'), at('background')],\n message: 'git-protocol must not import DAOs from backend-data',\n },\n // Domain store layers (layer 2-3): only layers 0-2, never services or apps.\n // Sources: dav-store (Durable-DAV), git-service (Edge-Git).\n {\n dir: 'packages/dav-store',\n ban: [at('backend-services'), at('api'), at('background')],\n message: 'dav-store must not import from backend-services (higher layer)',\n },\n {\n dir: 'packages/git-service',\n ban: [at('backend-services'), at('api'), at('background')],\n message: 'git-service must not import from backend-services (higher layer)',\n },\n {\n dir: 'packages/backend-services',\n ban: [at('api'), at('background')],\n message: 'backend-services must not import from apps',\n },\n {\n dir: 'apps/api',\n ban: [at('backend-data/dao'), at('backend-data')],\n allowTypeImports: true,\n message:\n 'apps/api must not import DAOs or backend-data values directly; use backend-services instead (type-only imports are allowed)',\n },\n // Direct-client bans: one entry per client package so each message names\n // the correct alternative. A repo holds at most one of these packages, so\n // the other two never fire. Sources: provider-clients (AWS-AccessBridge,\n // Mail-Meow, Mail-Otter, CalDAV-Bridge), dav-store (Durable-DAV),\n // git-service (Edge-Git).\n {\n dir: 'apps/api',\n ban: [at('provider-clients')],\n message: `apps/api must not import provider-clients directly; use ${scope}/backend-services instead`,\n },\n {\n dir: 'apps/api',\n ban: [at('dav-store')],\n message: `apps/api must not import dav-store directly; use ${scope}/webdav + DO RPC via ${scope}/background instead`,\n },\n {\n dir: 'apps/api',\n ban: [at('git-service')],\n message: `apps/api must not import git-service directly; use ${scope}/git-protocol + DO RPC via ${scope}/background instead`,\n },\n {\n dir: 'apps/background',\n ban: [at('api')],\n message: 'apps/background must not import from apps/api',\n },\n // The browser half, and the only layer that bans the namespace wholesale\n // rather than a list of siblings: a backend package imported by the SPA\n // typechecks and then fails at bundle time, with the error pointing at the\n // bundler rather than at the boundary. Edge-Sonic is the source; the others had\n // no block for it at all, which is how their layer table's \"may import: the\n // browser\" was a convention instead of a gate.\n {\n dir: 'apps/web',\n ban: [at('*')],\n message: `${at('apps/web')} ships zero backend dependencies — this module is the SPA's own copy`,\n },\n ];\n}\n\n/**\n * One argument to `tseslint.config()`, named here so the boundary builders\n * return the assembled type rather than a lookalike the assembly then has to\n * be argued into accepting.\n */\ntype ConfigInput = Parameters<typeof tseslint.config>[number];\n\n/**\n * The `no-restricted-imports` entries for one layer.\n *\n * Written as `group` patterns rather than exact `paths`, so `@myapp/backend-data`\n * and `@myapp/backend-data/dao` are both caught by one entry. `allowTypeImports`\n * is passed through only where the source repos set it, because `apps/api`\n * legitimately types its filters and models against DAO shapes.\n */\nexport function restrictedImports(bans: readonly LayerBan[]): ConfigInput[] {\n return bans.map(({ dir, ban, message, allowTypeImports }) => ({\n files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],\n rules: {\n 'no-restricted-imports': [\n 'error',\n {\n patterns: ban.map((group) => ({\n group: [group, `${group}/*`],\n message,\n ...(allowTypeImports === true && { allowTypeImports: true }),\n })),\n },\n ],\n },\n }));\n}\n\n/**\n * The dynamic-`import()` guard, generated from the same table.\n *\n * `no-restricted-imports` reads `ImportDeclaration` nodes only; a dynamic\n * `import()` is an `ImportExpression`, and this ESLint version does not report it\n * under that rule at all. Edge-Sonic verified this rather than assumed it — a\n * static import of a restricted specifier from the same file is an `error`, and\n * the identical specifier reached through `await import(...)` is silent. That\n * hole was load-bearing there: the credential path reached a banned module\n * through it. `no-restricted-syntax` sees `ImportExpression`, so the boundary is\n * stated a second way.\n */\nexport function restrictedDynamicImports(bans: readonly LayerBan[]): ConfigInput[] {\n return bans.map(({ dir, ban, message }) => ({\n files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],\n rules: {\n 'no-restricted-syntax': [\n 'error',\n ...ban.map((specifier) => ({\n selector: `ImportExpression[source.type='Literal'][source.value=/^${specifier.replaceAll('/', String.raw`\\/`)}/]`,\n message: `A dynamic import() is not covered by no-restricted-imports, so this layer reaches \\`${specifier}\\` through the one syntax that gate does not see. Both say no: ${message}`,\n })),\n ],\n },\n }));\n}\n"],
|
|
5
|
-
"mappings": "+EAkCO,MAAMA,EAA0C,CACrD,kBACA,0BACA,2BACA,wBACA,4BACA,kBACA,qBACA,wBACA,uBACA,4BACA,WACA,kBACA,YAuCI,SAAUC,EAAUC,EAAa,CACrC,MAAMC,EAAKC,EAACC,GAAyB,GAAGH,CAAK,IAAIG,CAAI,GAA1C,MACX,MAAO,CACL,CACE,IAAK,kBACL,IAAK,CAACF,EAAG,GAAG,CAAC,EACb,QAAS,GAAGD,CAAK,wCAAwCA,CAAK,yDAEhE,CACE,IAAK,0BACL,IAAK,CAACC,EAAG,GAAG,CAAC,EACb,QAAS,GAAGD,CAAK,wCAAwCA,CAAK,yDAEhE,CACE,IAAK,2BACL,IAAK,CACHC,EAAG,cAAc,EACjBA,EAAG,kBAAkB,EACrBA,EAAG,QAAQ,EACXA,EAAG,WAAW,EACdA,EAAG,cAAc,EACjBA,EAAG,aAAa,EAChBA,EAAG,kBAAkB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,CAAK,6BAE3E,CACE,IAAK,WACL,IAAK,CAACC,EAAG,WAAW,CAAC,EACrB,QAAS,oDAAoDD,CAAK,wBAAwBA,CAAK,uBAEjG,CACE,IAAK,WACL,IAAK,CAACC,EAAG,aAAa,CAAC,EACvB,QAAS,sDAAsDD,CAAK,8BAA8BA,CAAK,uBAEzG,CACE,IAAK,kBACL,IAAK,CAACC,EAAG,KAAK,CAAC,EACf,QAAS,iDAQX,CACE,IAAK,WACL,IAAK,CAACA,EAAG,GAAG,CAAC,EACb,QAAS,GAAGA,EAAG,UAAU,CAAC,6EAGhC,CA3HgBC,EAAAH,EAAA,
|
|
6
|
-
"names": ["DEFAULT_PROJECT_DIRS", "layerBans", "scope", "at", "__name", "name", "
|
|
4
|
+
"sourcesContent": ["import type tseslint from 'typescript-eslint';\n\n/**\n * The layer table behind the repo lint config's import boundaries.\n *\n * Provenance: the seven `no-restricted-imports` blocks in Durable-DAV's\n * `eslint.config.mjs`, with `@durable-dav/` replaced by the caller's scope.\n * Extracted from `eslint.ts` so the boundary rules — the part a repo actually\n * argues about — are their own module rather than the tail of a 640-line\n * config file.\n *\n * Converged across all nine family repos: `provider-clients` (AWS-AccessBridge,\n * CalDAV-Bridge, Mail-Meow, Mail-Otter), `webdav`/`dav-store` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic), `git-protocol`/`git-service` (Edge-Git).\n * `media-tags`/`subsonic` (Edge-Sonic) carry no boundary block in their source\n * repo — they are unconstrained utility leaves — so they have no layer here.\n *\n * The table is data rather than inline blocks so the dynamic-`import()` guard\n * is generated from the same list: a rule that derived its banned set from\n * another rule's configuration would be a second source of truth for the layer\n * table, and that table is what the docs describe.\n *\n * The table is a superset: a repo without a domain package simply never imports\n * it, so its ban never fires. A layer entry for a directory that does not exist\n * in the consumer matches no file and costs nothing.\n */\n\n/**\n * The directories the boundary rules cover, in the canonical layout.\n *\n * Kept here, beside the table it scopes: `defineRepoLintConfig` filters the\n * canonical layers by `projectDirs`, and a reader of the layer table should not\n * have to open the config assembly to learn which directories it covers.\n */\nexport const DEFAULT_PROJECT_DIRS: readonly string[] = [\n 'packages/shared',\n 'packages/backend-errors',\n 'packages/backend-runtime',\n 'packages/backend-data',\n 'packages/provider-clients',\n 'packages/webdav',\n 'packages/dav-store',\n 'packages/git-protocol',\n 'packages/git-service',\n 'packages/backend-services',\n 'apps/api',\n 'apps/background',\n 'apps/web',\n];\n\n/**\n * One layer's ban list, as the repo-relative package suffixes it may not import.\n *\n * Converged from all nine family repos. `backend-data` and `backend-services`\n * appear in all nine; `provider-clients` is AWS-AccessBridge's, CalDAV-Bridge's,\n * Mail-Meow's and Mail-Otter's; `webdav`/`dav-store` are Durable-DAV's,\n * Durable-DAV-Router's and Edge-Sonic's; `git-protocol`/`git-service` are\n * Edge-Git's. A layer only bans what exists in its repo, so the\n * union is safe: a repo without `provider-clients` simply never imports it.\n *\n * One `dir` may appear in several entries (see `apps/api` below): each entry\n * carries its own message and `allowTypeImports`, because the DAO ban allows\n * type-only imports and the direct-client bans do not.\n */\nexport interface LayerBan {\n /**\n Directory the rule is scoped to.\n */\n readonly dir: string;\n /**\n Package suffixes (relative to `scope`) that may not be imported from here.\n */\n readonly ban: readonly string[];\n /**\n Message shown when the rule fires.\n */\n readonly message: string;\n /**\n Type-only imports are allowed, for the DAO boundary in `apps/api`.\n */\n readonly allowTypeImports?: boolean;\n}\n\n/**\n * The layer table, parameterized by `scope`.\n */\nexport function layerBans(scope: string): readonly LayerBan[] {\n const at = (name: string): string => `${scope}/${name}`;\n return [\n {\n dir: 'packages/shared',\n ban: [at('*')],\n message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,\n },\n {\n dir: 'packages/backend-errors',\n ban: [at('*')],\n message: `${scope} packages must not import from other ${scope} packages — this is a zero-dependency base layer`,\n },\n {\n dir: 'packages/backend-runtime',\n ban: [\n at('backend-data'),\n at('provider-clients'),\n at('webdav'),\n at('dav-store'),\n at('git-protocol'),\n at('git-service'),\n at('backend-services'),\n at('api'),\n at('background'),\n ],\n message: 'backend-runtime must not import from a higher layer',\n },\n {\n dir: 'packages/backend-data',\n ban: [\n at('backend-runtime'),\n at('provider-clients'),\n at('webdav'),\n at('dav-store'),\n at('git-protocol'),\n at('git-service'),\n at('backend-services'),\n at('api'),\n at('background'),\n ],\n message: 'backend-data must not import from a higher layer',\n },\n // Domain protocol layers (layer 2, beside backend-data): each bans the DAO\n // layer, the runtime, its store counterpart where it has one, the service\n // layer and the apps. Sources: provider-clients (AWS-AccessBridge,\n // Mail-Meow), webdav (Durable-DAV, Edge-Sonic), git-protocol (Edge-Git).\n {\n dir: 'packages/provider-clients',\n ban: [at('backend-data'), at('backend-runtime'), at('backend-services'), at('api'), at('background')],\n message: 'provider-clients must not import DAOs from backend-data',\n },\n {\n dir: 'packages/webdav',\n ban: [at('backend-data'), at('backend-runtime'), at('dav-store'), at('backend-services'), at('api'), at('background')],\n message: 'webdav must not import DAOs from backend-data',\n },\n {\n dir: 'packages/git-protocol',\n ban: [at('backend-data'), at('backend-runtime'), at('git-service'), at('backend-services'), at('api'), at('background')],\n message: 'git-protocol must not import DAOs from backend-data',\n },\n // Domain store layers (layer 2-3): only layers 0-2, never services or apps.\n // Sources: dav-store (Durable-DAV), git-service (Edge-Git).\n {\n dir: 'packages/dav-store',\n ban: [at('backend-services'), at('api'), at('background')],\n message: 'dav-store must not import from backend-services (higher layer)',\n },\n {\n dir: 'packages/git-service',\n ban: [at('backend-services'), at('api'), at('background')],\n message: 'git-service must not import from backend-services (higher layer)',\n },\n {\n dir: 'packages/backend-services',\n ban: [at('api'), at('background')],\n message: 'backend-services must not import from apps',\n },\n {\n dir: 'apps/api',\n ban: [at('backend-data/dao'), at('backend-data')],\n allowTypeImports: true,\n message:\n 'apps/api must not import DAOs or backend-data values directly; use backend-services instead (type-only imports are allowed)',\n },\n // Direct-client bans: one entry per client package so each message names\n // the correct alternative. A repo holds at most one of these packages, so\n // the other two never fire. Sources: provider-clients (AWS-AccessBridge,\n // Mail-Meow, Mail-Otter, CalDAV-Bridge), dav-store (Durable-DAV),\n // git-service (Edge-Git).\n {\n dir: 'apps/api',\n ban: [at('provider-clients')],\n message: `apps/api must not import provider-clients directly; use ${scope}/backend-services instead`,\n },\n {\n dir: 'apps/api',\n ban: [at('dav-store')],\n message: `apps/api must not import dav-store directly; use ${scope}/webdav + DO RPC via ${scope}/background instead`,\n },\n {\n dir: 'apps/api',\n ban: [at('git-service')],\n message: `apps/api must not import git-service directly; use ${scope}/git-protocol + DO RPC via ${scope}/background instead`,\n },\n {\n dir: 'apps/background',\n ban: [at('api')],\n message: 'apps/background must not import from apps/api',\n },\n // The browser half, and the only layer that bans the namespace wholesale\n // rather than a list of siblings: a backend package imported by the SPA\n // typechecks and then fails at bundle time, with the error pointing at the\n // bundler rather than at the boundary. Edge-Sonic is the source; the others had\n // no block for it at all, which is how their layer table's \"may import: the\n // browser\" was a convention instead of a gate.\n {\n dir: 'apps/web',\n ban: [at('*')],\n message: `${at('apps/web')} ships zero backend dependencies — this module is the SPA's own copy`,\n },\n ];\n}\n\n/**\n * One argument to `tseslint.config()`, named here so the boundary builders\n * return the assembled type rather than a lookalike the assembly then has to\n * be argued into accepting.\n */\ntype ConfigInput = Parameters<typeof tseslint.config>[number];\n\n/**\n * The bans for one directory, in table order.\n *\n * **Grouping is load-bearing, not tidiness.** Flat config merges every matching\n * config object and resolves each rule name by *last entry wins* — so two\n * entries with the same `files` glob do not accumulate, the second replaces the\n * first's rule outright. Emitting one entry per `LayerBan` therefore meant that\n * a directory appearing twice in the table (`apps/api` does, four times) kept\n * only its last row: the DAO ban and the `provider-clients` ban vanished, and\n * the layer table in the kit's own documentation described a gate that was not\n * running. It could not be caught by asserting a rule exists for a dir — the\n * surviving rule exists — only by asserting every ban in the table survives.\n *\n * Merging happens at the **pattern** level rather than the layer level, because\n * the two things a layer carries are not mergeable: each group keeps its own\n * `message`, and `allowTypeImports` belongs to a group (`apps/api` may type its\n * filters against DAO shapes but may not reach `provider-clients` even as a\n * type). One config object per directory, every pattern inside it.\n */\nfunction groupedByDir(bans: readonly LayerBan[]): Map<string, LayerBan[]> {\n const grouped = new Map<string, LayerBan[]>();\n for (const ban of bans) {\n const existing = grouped.get(ban.dir);\n if (existing) existing.push(ban);\n else grouped.set(ban.dir, [ban]);\n }\n return grouped;\n}\n\n/**\n * The `no-restricted-imports` entries, one per directory.\n *\n * Written as `group` patterns rather than exact `paths`, so `@myapp/backend-data`\n * and `@myapp/backend-data/dao` are both caught by one entry. `allowTypeImports`\n * is carried per group rather than per directory, because only the DAO boundary\n * sets it.\n */\nexport function restrictedImports(bans: readonly LayerBan[]): ConfigInput[] {\n return [...groupedByDir(bans)].map(([dir, layers]) => ({\n files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],\n rules: {\n 'no-restricted-imports': [\n 'error',\n {\n patterns: layers.flatMap(({ ban, message, allowTypeImports }) =>\n ban.map((group) => ({\n group: [group, `${group}/*`],\n message,\n ...(allowTypeImports === true && { allowTypeImports: true }),\n })),\n ),\n },\n ],\n },\n }));\n}\n\n/**\n * The dynamic-`import()` guard, generated from the same table.\n *\n * `no-restricted-imports` reads `ImportDeclaration` nodes only; a dynamic\n * `import()` is an `ImportExpression`, and this ESLint version does not report it\n * under that rule at all. Edge-Sonic verified this rather than assumed it — a\n * static import of a restricted specifier from the same file is an `error`, and\n * the identical specifier reached through `await import(...)` is silent. That\n * hole was load-bearing there: the credential path reached a banned module\n * through it. `no-restricted-syntax` sees `ImportExpression`, so the boundary is\n * stated a second way.\n *\n * Grouped per directory for the same reason {@link restrictedImports} is: one\n * entry per layer would leave only the last row standing, and `no-restricted-syntax`\n * merges exactly like `no-restricted-imports` does.\n */\nexport function restrictedDynamicImports(bans: readonly LayerBan[]): ConfigInput[] {\n return [...groupedByDir(bans)].map(([dir, layers]) => ({\n files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],\n rules: {\n 'no-restricted-syntax': [\n 'error',\n ...layers.flatMap(({ ban, message }) =>\n ban.map((specifier) => ({\n selector: `ImportExpression[source.type='Literal'][source.value=/^${specifier.replaceAll('/', String.raw`\\/`)}/]`,\n message: `A dynamic import() is not covered by no-restricted-imports, so this layer reaches \\`${specifier}\\` through the one syntax that gate does not see. Both say no: ${message}`,\n })),\n ),\n ],\n },\n }));\n}\n"],
|
|
5
|
+
"mappings": "+EAkCO,MAAMA,EAA0C,CACrD,kBACA,0BACA,2BACA,wBACA,4BACA,kBACA,qBACA,wBACA,uBACA,4BACA,WACA,kBACA,YAuCI,SAAUC,EAAUC,EAAa,CACrC,MAAMC,EAAKC,EAACC,GAAyB,GAAGH,CAAK,IAAIG,CAAI,GAA1C,MACX,MAAO,CACL,CACE,IAAK,kBACL,IAAK,CAACF,EAAG,GAAG,CAAC,EACb,QAAS,GAAGD,CAAK,wCAAwCA,CAAK,yDAEhE,CACE,IAAK,0BACL,IAAK,CAACC,EAAG,GAAG,CAAC,EACb,QAAS,GAAGD,CAAK,wCAAwCA,CAAK,yDAEhE,CACE,IAAK,2BACL,IAAK,CACHC,EAAG,cAAc,EACjBA,EAAG,kBAAkB,EACrBA,EAAG,QAAQ,EACXA,EAAG,WAAW,EACdA,EAAG,cAAc,EACjBA,EAAG,aAAa,EAChBA,EAAG,kBAAkB,EACrBA,EAAG,KAAK,EACRA,EAAG,YAAY,GAEjB,QAAS,uDAEX,CACE,IAAK,wBACL,IAAK,CACHA,EAAG,iBAAiB,EACpBA,EAAG,kBAAkB,EACrBA,EAAG,QAAQ,EACXA,EAAG,WAAW,EACdA,EAAG,cAAc,EACjBA,EAAG,aAAa,EAChBA,EAAG,kBAAkB,EACrBA,EAAG,KAAK,EACRA,EAAG,YAAY,GAEjB,QAAS,oDAMX,CACE,IAAK,4BACL,IAAK,CAACA,EAAG,cAAc,EAAGA,EAAG,iBAAiB,EAAGA,EAAG,kBAAkB,EAAGA,EAAG,KAAK,EAAGA,EAAG,YAAY,CAAC,EACpG,QAAS,2DAEX,CACE,IAAK,kBACL,IAAK,CAACA,EA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AAOF,EAAM,CACtB,MAAMG,EAAWF,EAAQ,IAAIC,EAAI,GAAG,EAChCC,EAAUA,EAAS,KAAKD,CAAG,EAC1BD,EAAQ,IAAIC,EAAI,IAAK,CAACA,CAAG,CAAC,CACjC,CACA,OAAOD,CACT,CARSJ,EAAAE,EAAA,gBAkBH,SAAUK,EAAkBJ,EAAyB,CACzD,MAAO,CAAC,GAAGD,EAAaC,CAAI,CAAC,EAAE,IAAI,CAAC,CAACK,EAAKC,CAAM,KAAO,CACrD,MAAO,CAAC,GAAGD,CAAG,+BAA+B,EAC7C,MAAO,CACL,wBAAyB,CACvB,QACA,CACE,SAAUC,EAAO,QAAQ,CAAC,CAAE,IAAAJ,EAAK,QAAAK,EAAS,iBAAAC,CAAgB,IACxDN,EAAI,IAAKO,IAAW,CAClB,MAAO,CAACA,EAAO,GAAGA,CAAK,IAAI,EAC3B,QAAAF,EACA,GAAIC,IAAqB,IAAQ,CAAE,iBAAkB,EAAI,GACzD,CAAC,MAKX,CACJ,CAlBgBX,EAAAO,EAAA,qBAoCV,SAAUM,EAAyBV,EAAyB,CAChE,MAAO,CAAC,GAAGD,EAAaC,CAAI,CAAC,EAAE,IAAI,CAAC,CAACK,EAAKC,CAAM,KAAO,CACrD,MAAO,CAAC,GAAGD,CAAG,+BAA+B,EAC7C,MAAO,CACL,uBAAwB,CACtB,QACA,GAAGC,EAAO,QAAQ,CAAC,CAAE,IAAAJ,EAAK,QAAAK,CAAO,IAC/BL,EAAI,IAAKS,IAAe,CACtB,SAAU,0DAA0DA,EAAU,WAAW,IAAK,OAAO,OAAO,CAAC,KAC7G,QAAS,uFAAuFA,CAAS,kEAAkEJ,CAAO,IAClL,CAAC,KAIT,CACJ,CAfgBV,EAAAa,EAAA",
|
|
6
|
+
"names": ["DEFAULT_PROJECT_DIRS", "layerBans", "scope", "at", "__name", "name", "groupedByDir", "bans", "grouped", "ban", "existing", "restrictedImports", "dir", "layers", "message", "allowTypeImports", "group", "restrictedDynamicImports", "specifier"]
|
|
7
7
|
}
|
|
@@ -8,6 +8,26 @@ One defect, kept as a locale plus a message so a caller can group them.
|
|
|
8
8
|
interface LocaleProblem {
|
|
9
9
|
locale: string;
|
|
10
10
|
problem: string;
|
|
11
|
+
/**
|
|
12
|
+
* Reported, but not a failure.
|
|
13
|
+
*
|
|
14
|
+
* The distinction is **"this build is wrong"** against **"this merge is still
|
|
15
|
+
* in flight"**, and a gate that cannot tell them apart gets switched off. A
|
|
16
|
+
* key the bundles carry that no call site reaches is the ordinary state of a
|
|
17
|
+
* bundle running ahead of its UI, and a translator adding a string for a screen
|
|
18
|
+
* that has not been wired is doing the right thing. It is also the only thing
|
|
19
|
+
* that catches a call site deleted or renamed without its key — which keeps a
|
|
20
|
+
* translator re-translating a string no user will ever see.
|
|
21
|
+
*
|
|
22
|
+
* So it is reported and it does not fail the run.
|
|
23
|
+
*
|
|
24
|
+
* The finding that is **not** advisory is the mirror: a `t()` key the bundle
|
|
25
|
+
* lacks. That one renders the inline default for every user in every language,
|
|
26
|
+
* it is actionable in the same commit, and there is no in-flight state in which
|
|
27
|
+
* it is the right answer — so it stays fatal, and the report below prints the
|
|
28
|
+
* two classes separately rather than counting them together.
|
|
29
|
+
*/
|
|
30
|
+
advisory?: boolean;
|
|
11
31
|
}
|
|
12
32
|
/**
|
|
13
33
|
The outcome of one run.
|
|
@@ -26,13 +46,19 @@ declare function parseObjectLiteral(source: string, file: string): unknown;
|
|
|
26
46
|
*/
|
|
27
47
|
declare function validateLocales(localesDir: string, baseLocale?: string, shape?: LocaleShape): LocaleReport;
|
|
28
48
|
/**
|
|
29
|
-
CLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?])`.
|
|
49
|
+
CLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?, '--tags=<file>'?])`.
|
|
30
50
|
|
|
31
51
|
`--call-sites=<dir>` opts into the application-side checks: every `t('key')` under
|
|
32
52
|
`<dir>` must resolve against the base bundle, and any inline default must equal the
|
|
33
53
|
bundled value. Without the flag the script stays bundle-to-bundle, because that is
|
|
34
54
|
the only part it can answer for a repo whose bundles are consumed by something
|
|
35
55
|
other than `t()` — a backend string table, for instance.
|
|
56
|
+
|
|
57
|
+
`--tags=<file>` cross-checks a declared `SUPPORTED_LANGUAGES` / `SUPPORTED_LOCALES`
|
|
58
|
+
array against the bundle directories, in both directions. It is separate from
|
|
59
|
+
`--call-sites` because a repo can declare its tags in a file the scan never walks,
|
|
60
|
+
and a directory of bundles with no declaration is exactly the state a
|
|
61
|
+
bundle-to-bundle check reports as perfectly healthy.
|
|
36
62
|
*/
|
|
37
63
|
declare function validateLocalesCli(argv?: readonly string[]): number;
|
|
38
64
|
export { parseObjectLiteral, validateLocales, validateLocalesCli };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate-locales.d.ts","sourceRoot":"","sources":["../../src/scripts/validate-locales.ts"],"names":[],"mappings":"AAyCA;;EAEE;AACF,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEtD;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"validate-locales.d.ts","sourceRoot":"","sources":["../../src/scripts/validate-locales.ts"],"names":[],"mappings":"AAyCA;;EAEE;AACF,KAAK,WAAW,GAAG,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEtD;;EAEE;AACF,UAAU,aAAa;IACrB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB;;;;;;;;;;;;;;;;;;OAkBG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;EAEE;AACF,UAAU,YAAY;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B;AAsID,iBAAS,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CA4EjE;AAqFD;;;;;GAKG;AACH,iBAAS,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,SAAO,EAAE,KAAK,GAAE,WAAoB,GAAG,YAAY,CA2EzG;AAmPD;;;;;;;;;;;;;;EAcE;AACF,iBAAS,kBAAkB,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CA8CnF;AAED,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,kBAAkB,EAAE,CAAC;AACnE,YAAY,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`&&(
|
|
3
|
-
`&&(
|
|
4
|
-
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}
|
|
5
|
-
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return
|
|
1
|
+
var P=Object.defineProperty;var f=(e,t)=>P(e,"name",{value:t,configurable:!0});import{existsSync as $,readdirSync as w,readFileSync as g}from"node:fs";import{pathToFileURL as W}from"node:url";import b from"node:path";function y(e,t="",o=new Map){if(e===null||typeof e!="object"||Array.isArray(e))return t&&o.set(t,e),o;const n=Object.entries(e);if(n.length===0)return t&&o.set(t,e),o;for(const[s,r]of n)y(r,t?`${t}.${s}`:s,o);return o}f(y,"flatten");function E(e){return typeof e!="string"?[]:[...new Set(e.match(/\{\{[^{}]+\}\}/g))].sort((t,o)=>t.localeCompare(o))}f(E,"placeholdersOf");function A(e){const t=g(e,"utf8");return e.endsWith(".ts")?O(t,e):JSON.parse(t)}f(A,"readBundle");function U(e){let t="",o=!1,n=!1;for(let s=0;s<e.length;s+=1){const r=e[s];if(o){r===`
|
|
2
|
+
`&&(o=!1);continue}const c=e[s+1];if(n){r==="*"&&c==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&c==="-"){o=!0;continue}if(r==="/"&&c==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&c!=="="&&c!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const l=e.indexOf("{",s);return l===-1?-1:l}}return-1}f(U,"objectLiteralStart");function O(e,t){const o=U(e);if(o===-1)throw new Error(`${t} has no object literal`);let n=0,s=-1,r="",c=!1,a=!1;for(let h=o;h<e.length;h+=1){const d=e[h];if(c){d===`
|
|
3
|
+
`&&(c=!1);continue}const m=e[h+1];if(a){d==="*"&&m==="/"&&(a=!1,h+=1);continue}if(r!==""){if(d==="\\"){h+=1;continue}d===r&&(r="");continue}if(d==="-"&&m==="-"){c=!0;continue}if(d==="/"&&m==="*"){a=!0;continue}if(d==="'"||d==='"'||d==="`"){r=d;continue}if(d==="{")n+=1;else if(d==="}"&&(n-=1,n===0)){s=h;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const u=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(h,d)=>JSON.stringify(_(d))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(u)}catch(h){throw new Error(`${t} object literal could not be parsed: ${h instanceof Error?h.message:String(h)}`)}}f(O,"parseObjectLiteral");function _(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
|
|
4
|
+
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}f(_,"unescapeLiteral");const j={file:"json",module:"ts"};function S(e){return e==="auto"?["dir","file","module"]:[e]}f(S,"layouts");function T(e,t){const o=[];S(t).includes("dir")&&o.push(...w(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name));for(const n of S(t)){if(n==="dir")continue;const s=j[n];o.push(...w(e).filter(r=>r.endsWith(`.${s}`)).map(r=>r.slice(0,-s.length-1)))}return o}f(T,"tagsOnDisk");function k(e,t,o){const n=[];S(o).includes("dir")&&n.push(b.join(e,t,"translation.json"));for(const s of S(o))s!=="dir"&&n.push(b.join(e,`${t}.${j[s]}`));return n.find(s=>$(s))}f(k,"bundleFor");function F(e,t,o){const n=k(e,t,o);if(n===void 0)throw new Error(`no bundle found for the base locale (expected ${t}/translation.json)`);return y(A(n))}f(F,"bundleAt");function C(e,t="en",o="auto"){const n=[];if(!$(e))return n.push({locale:t,problem:`${e} does not exist`}),{locales:[],keys:0,problems:n};const s=k(e,t,o);if(s===void 0)return n.push({locale:t,problem:`no bundle found for the base locale (expected ${t}/translation.json)`}),{locales:[],keys:0,problems:n};let r;try{r=y(A(s))}catch(l){return n.push({locale:t,problem:`${s}: ${l instanceof Error?l.message:String(l)}`}),{locales:[],keys:0,problems:n}}const c=new Set(r.keys());if(c.size===0)return n.push({locale:t,problem:`${s} has no keys \u2014 the base bundle is empty or unreadable`}),{locales:[t],keys:0,problems:n};const a=[...new Set([...T(e,o),t])].sort((l,p)=>l.localeCompare(p));for(const l of a){const p=k(e,l,o);if(p===void 0){n.push({locale:l,problem:"no bundle found"});continue}let i;try{i=y(A(p))}catch(u){n.push({locale:l,problem:`${p}: ${u instanceof Error?u.message:String(u)}`});continue}for(const u of c)i.has(u)||n.push({locale:l,problem:`missing key: ${u}`});for(const[u,h]of i){if(!c.has(u)){n.push({locale:l,problem:`extra key not in ${t}: ${u}`});continue}if(typeof h!="string"||h===""){n.push({locale:l,problem:`empty value: ${u} \u2014 indistinguishable from a missing key at runtime`});continue}const d=E(r.get(u));if(d.length===0)continue;const m=E(h);(d.length!==m.length||d.some((v,L)=>v!==m[L]))&&n.push({locale:l,problem:`placeholder mismatch at ${u}: ${l} has ${JSON.stringify(m)}, ${t} has ${JSON.stringify(d)}`})}}return{locales:a,keys:c.size,problems:n}}f(C,"validateLocales");function J(e,t,o){const n=[];for(const s of x(e)){const r=g(s,"utf8"),c=/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;for(const a of r.matchAll(c)){const l=a[2];if(l.includes("${")||l.includes("{{"))continue;const p=b.relative(process.cwd(),s)||s;if(!t.has(l)){n.push({locale:"call-site",problem:`${p}: t('${l}') is not in the bundle \u2014 it renders as the inline default and is untranslatable`});continue}if(!a[3])continue;const i=K(r,a.index+a[0].length);if(i===null)continue;const u=o.get(l);i!==u&&n.push({locale:"call-site",problem:`${p}: t('${l}', \u2026) default disagrees with the bundle \u2014 bundle=${JSON.stringify(u)} default=${JSON.stringify(i)}`})}}return n}f(J,"collectCallSites");function K(e,t){const o=e.slice(t).replace(/^\s+/,""),n=o[0];if(n!=="'"&&n!=='"')return null;const s=o.slice(1),c=(n==="'"?/^(?:[^'\\]|\\.)*'/:/^(?:[^"\\]|\\.)*"/).exec(s);return c?q(s.slice(0,c[0].length-1)):null}f(K,"readDefault");function q(e){return e.replaceAll(/\\(.)/gs,(t,o)=>{switch(o){case"n":return`
|
|
5
|
+
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}f(q,"decodeStringLiteral");function B(e){const t=new Set;for(const o of x(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1/g)){const s=n[2];!s.includes("${")&&!s.includes("{{")&&t.add(s)}return t}f(B,"usedKeys");function x(e){const t=[],o=f(n=>{for(const s of w(n,{withFileTypes:!0})){const r=b.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules"||s.name==="dist"||s.name==="coverage")continue;o(r);continue}e.extensions.some(c=>s.name.endsWith(c))&&t.push(r)}},"walk");return o(e.dir),t}f(x,"sourceFiles");function R(e,t,o){const n=G(t),s=e.filter(r=>!o.has(r)&&[...n].every(c=>!(r===c||r.startsWith(`${c}.`))));return s.length===0?[]:[{locale:"call-site",problem:`${s.length} base key(s) are not reached by any t() call site: ${s.slice(0,20).join(", ")}${s.length>20?", \u2026":""}`,advisory:!0}]}f(R,"collectUnusedKeys");function G(e){const t=new Set;for(const o of x(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*`([^`$]*)\$\{/g)){const s=n[1].replace(/\.$/,"");s&&t.add(s)}return t}f(G,"dynamicKeyPrefixes");function z(e){const t=g(e,"utf8"),o=/(?:export\s+)?const\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\s*=\s*\[([^\]]*)\]/.exec(t);if(!o)throw new Error(`${e} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);return[...(o[1]??"").matchAll(/['"]([^'"]+)['"]/g)].map(n=>n[1])}f(z,"declaredTags");function D(e,t,o){const n=z(t),s=[];for(const r of n)o.includes(r)||s.push({locale:"tags",problem:`${t} declares '${r}' but ${e}/${r} does not exist \u2014 selecting that language throws`});for(const r of o)n.includes(r)||s.push({locale:"tags",problem:`${e}/${r} exists but ${t} does not declare it \u2014 the selector cannot offer it`});return s}f(D,"checkDeclaredTags");function N(e=process.argv.slice(2)){const t=e.find(i=>!i.startsWith("--"))??"apps/web/src/locales",o=e.find(i=>i.startsWith("--shape="))?.slice(8)??"auto",n=e.find(i=>i.startsWith("--base="))?.slice(7)??"en",s=e.find(i=>i.startsWith("--call-sites="))?.slice(13),r=e.find(i=>i.startsWith("--tags="))?.slice(7),c=C(t,n,o),a=[...c.problems];if(r!==void 0&&$(r))try{a.push(...D(t,r,T(t,o)))}catch(i){a.push({locale:"tags",problem:`${r}: ${i instanceof Error?i.message:String(i)}`})}if(s!==void 0&&$(s))try{const i=F(t,n,o),u={dir:s,extensions:[".ts",".tsx"]},h=B(u);a.push(...J(u,new Set(i.keys()),i),...R([...i.keys()],u,h))}catch(i){a.push({locale:"call-site",problem:`${s}: ${i instanceof Error?i.message:String(i)}`})}const l=a.filter(i=>i.advisory!==!0),p=a.filter(i=>i.advisory===!0);if(l.length>0){console.error(`Locale validation failed for ${t} (${l.length} problem(s)):`);for(const i of l)console.error(` - ${i.locale}: ${i.problem}`);return 1}if(p.length>0){console.warn(`Locale validation passed for ${t} with ${p.length} advisory finding(s):`);for(const i of p)console.warn(` - ${i.locale}: ${i.problem}`)}return console.log(`Locale validation passed (${c.locales.length} locales, ${c.keys} keys each, shape ${o}).`),0}f(N,"validateLocalesCli");process.argv[1]!==void 0&&import.meta.url===W(process.argv[1]).href&&process.exit(N(process.argv.slice(2)));export{O as parseObjectLiteral,C as validateLocales,N as validateLocalesCli};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/validate-locales.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Validate that every locale bundle carries exactly the base locale's keys.\n *\n * Provenance: `scripts/validate_locales.{mjs,ts}` in Durable-DAV, Edge-Git and\n * Mail-Meow, and Edge-Sonic's `scripts/i18n/locale-checks.ts` +\n * `validate_locales.ts`, converged. All four copies agree on the contract:\n * flattened dotted key paths, two-way parity (missing AND extra), no empty values,\n * no stray placeholders.\n *\n * ### What the convergence added\n *\n * Edge-Sonic's is the only copy that checks what a value *is*. The rest compare\n * bundle to bundle, so with one shipped language the whole per-tag body is skipped\n * and the script reports `ALL OK` having checked nothing about the application — it\n * could not see that `libraries.scanPausedRequests` was used and absent, because\n * the string in the bundle did not exist to be wrong *about* anything. Hence\n * `--call-sites`: every `t('key')` under `apps/web/src` must resolve.\n *\n * Key **order** drift against the base is a warning, not a failure: locale files\n * are maintained by mirroring new keys into every file, and failing on order would\n * turn an otherwise-correct translation update into a CI failure about formatting.\n *\n * ### Three on-disk shapes, one checker\n *\n * The family ships bundles in three shapes, and the shape is an argument rather\n * than a fork of the script:\n *\n * - `auto` (default) — every layout below, tried in order, so a repo that has\n * half-migrated is reported rather than silently skipped;\n * - `dir` — `<locales-dir>/<tag>/translation.json`, the i18next layout used by\n * seven repos;\n * - `file` — `<locales-dir>/<tag>.json`, one flat file per tag;\n * - `module` — `<locales-dir>/<tag>.ts` exporting an object literal, which is the\n * shape `@rexezuge/i18n` uses for the backend string bundles. The literal is\n * extracted and normalised here, so the same gate covers the backend catalogs\n * the kit ships and the SPA bundles the repos do.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\n\n/**\nThe bundle layouts the checker understands.\n*/\ntype LocaleShape = 'auto' | 'dir' | 'file' | 'module';\n\n/**\nOne defect, kept as a locale plus a message so a caller can group them.\n*/\ninterface LocaleProblem {\n locale: string;\n problem: string;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface LocaleReport {\n locales: string[];\n keys: number;\n problems: LocaleProblem[];\n}\n\n/**\nEvery dotted key path in a bundle, depth first.\n*/\nfunction flatten(value: unknown, prefix = '', out: Map<string, unknown> = new Map()): Map<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n for (const [key, child] of entries) {\n flatten(child, prefix ? `${prefix}.${key}` : key, out);\n }\n return out;\n}\n\n/**\n * The interpolation tokens in a value, sorted.\n *\n * Sorted so two values carrying the same tokens in different orders compare equal —\n * substitution is by name, so order carries no meaning. `localeCompare` rather than\n * the default comparator so a reported mismatch does not change with the machine's\n * locale.\n */\nfunction placeholdersOf(value: unknown): string[] {\n if (typeof value !== 'string') return [];\n return [...new Set(value.match(/\\{\\{[^{}]+\\}\\}/g))].sort((left: string, right: string) => left.localeCompare(right));\n}\n\n/**\n * A source file to check `t()` call sites under, and how far down to look.\n */\ninterface CallSiteScope {\n /**\n Directory walked for source files.\n */\n dir: string;\n /**\n Extensions treated as source.\n */\n extensions: readonly string[];\n}\n\n/**\n * Read a bundle as a value, in whichever shape it is written.\n *\n * `module` is the shape `@rexezuge/i18n` ships: `const enStrings: BackendStrings =\n * { common: { unauthorized: '…' } };`. Extracting the literal rather than importing\n * the module is the point — a validator that imported the bundle would typecheck it\n * against the kit's own types, and therefore agree with whatever it was given.\n */\nfunction readBundle(file: string): unknown {\n const source = readFileSync(file, 'utf8');\n // Decided by the file's extension, not by the caller's `shape`: under `auto` a\n // `.ts` bundle is found, and reading it as JSON would report a parse error for a\n // file that is perfectly well-formed.\n return file.endsWith('.ts') ? parseObjectLiteral(source, file) : (JSON.parse(source) as unknown);\n}\n\n/**\n * The first balanced object literal in a TypeScript module, as a value.\n *\n * Brace-matched outside strings and comments, and started at the **first\n * assignment** rather than at the first brace — see `objectLiteralStart` for why the\n * difference is the whole rule. Single-quoted strings are normalised to\n * double-quoted JSON, bare keys are quoted, and trailing commas are tolerated: that\n * is all the shape this needs, and a translator file that needs more is not a\n * translator file.\n */\n/**\n * Where the object literal begins: the first brace **after the first assignment**.\n *\n * The assignment matters. `const enStrings: BackendStrings = { ... }` is preceded by\n * an import line whose own braces open earlier in the file, so a plain\n * `indexOf('{')` returns the import's pair and the \"literal\" extracted is\n * `{ BackendStrings }` — an empty object that parses cleanly and then reports the\n * base bundle as having no keys. Finding the assignment first skips every brace that\n * is not the value being bound to it.\n */\nfunction objectLiteralStart(source: string): number {\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n // The assignment, and not a comparison or an arrow: `=>` and `==` both contain an\n // `=`, and neither is where a bundle's object literal is attached.\n const previous = source[index - 1];\n if (char === '=' && next !== '=' && next !== '>' && previous !== '=' && previous !== '!' && previous !== '<' && previous !== '>') {\n const brace = source.indexOf('{', index);\n return brace === -1 ? -1 : brace;\n }\n }\n return -1;\n}\n\nfunction parseObjectLiteral(source: string, file: string): unknown {\n const start = objectLiteralStart(source);\n if (start === -1) {\n throw new Error(`${file} has no object literal`);\n }\n\n let depth = 0;\n let end = -1;\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = start; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n // An escape consumes the next character, so `\\'` does not close the string.\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n end = index;\n break;\n }\n }\n }\n if (end === -1) {\n throw new Error(`${file} has an unterminated object literal`);\n }\n\n const literal = source.slice(start, end + 1);\n // Three normalisations, each of which a JSON parser needs and a TS literal does not:\n // single-quoted strings become double-quoted (applied only to string literals, so a\n // value containing an apostrophe keeps it), bare keys get quoted, and trailing\n // commas are dropped. A translator file that needs more than that is not a\n // translator file.\n const doubleQuoted = literal.replaceAll(/'((?:[^'\\\\]|\\\\.)*)'/g, (_match, body: string) => JSON.stringify(unescapeLiteral(body)));\n const quotedKeys = doubleQuoted.replaceAll(/([{,]\\s*)([A-Z_$][\\w$]*)(\\s*:)/gi, '$1\"$2\"$3');\n const withoutTrailingCommas = quotedKeys.replaceAll(/,(\\s*[}\\]])/g, '$1');\n\n try {\n return JSON.parse(withoutTrailingCommas) as unknown;\n } catch (error: unknown) {\n throw new Error(`${file} object literal could not be parsed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\nThe escapes a translator file actually uses; anything else is passed through.\n*/\nfunction unescapeLiteral(body: string): string {\n return body\n .replaceAll(String.raw`\\'`, \"'\")\n .replaceAll(String.raw`\\\"`, '\"')\n .replaceAll(String.raw`\\n`, '\\n')\n .replaceAll(String.raw`\\t`, '\\t')\n .replaceAll(String.raw`\\\\`, '\\\\');\n}\n\n/**\nThe extensions a flat layout uses, keyed by shape.\n*/\nconst FLAT_EXTENSION: Record<'file' | 'module', string> = { file: 'json', module: 'ts' };\n\n/**\nThe layouts `shape` covers. `auto` covers all three, in the order they are tried.\n*/\nfunction layouts(shape: LocaleShape): Array<'dir' | 'file' | 'module'> {\n return shape === 'auto' ? ['dir', 'file', 'module'] : [shape];\n}\n\n/**\nThe tags on disk, in whichever layouts `shape` covers.\n*/\nfunction tagsOnDisk(localesDir: string, shape: LocaleShape): string[] {\n const tags: string[] = [];\n if (layouts(shape).includes('dir')) {\n tags.push(\n ...readdirSync(localesDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name),\n );\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n const extension = FLAT_EXTENSION[layout];\n tags.push(\n ...readdirSync(localesDir)\n .filter((name) => name.endsWith(`.${extension}`))\n .map((name) => name.slice(0, -extension.length - 1)),\n );\n }\n return tags;\n}\n\n/**\n * The file a tag's bundle lives in, or `undefined` when it is not there.\n *\n * Every candidate is tried rather than only the one `shape` names, because a repo\n * with a half-migrated tree is a repo whose missing half should be reported. A\n * checker that only looked where it was told would read a bundle that exists as\n * absent, and a missing bundle is the defect this script exists to find.\n */\nfunction bundleFor(localesDir: string, locale: string, shape: LocaleShape): string | undefined {\n const candidates: string[] = [];\n if (layouts(shape).includes('dir')) {\n candidates.push(path.join(localesDir, locale, 'translation.json'));\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n candidates.push(path.join(localesDir, `${locale}.${FLAT_EXTENSION[layout]}`));\n }\n return candidates.find((candidate) => existsSync(candidate));\n}\n\n/**\n * The base bundle, flattened, for a scope that checks the application against it.\n *\n * @throws when the bundle cannot be found or parsed — the caller reports that as a\n * problem rather than reporting \"all clear\" against an empty key set, which is\n * the one outcome a locale gate must never produce silently.\n */\nfunction bundleAt(localesDir: string, baseLocale: string, shape: LocaleShape): Map<string, unknown> {\n const file = bundleFor(localesDir, baseLocale, shape);\n if (file === undefined) {\n throw new Error(`no bundle found for the base locale (expected ${baseLocale}/translation.json)`);\n }\n return flatten(readBundle(file));\n}\n\n/**\n * Validate a directory of locale bundles against `baseLocale`'s key set.\n *\n * Two-way parity: a key the base has and a bundle lacks renders the fallback, and\n * a key a bundle has that the base lacks is dead weight nothing can translate from.\n */\nfunction validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleShape = 'auto'): LocaleReport {\n const problems: LocaleProblem[] = [];\n if (!existsSync(localesDir)) {\n problems.push({ locale: baseLocale, problem: `${localesDir} does not exist` });\n return { locales: [], keys: 0, problems };\n }\n\n const baseFile = bundleFor(localesDir, baseLocale, shape);\n if (baseFile === undefined) {\n problems.push({ locale: baseLocale, problem: `no bundle found for the base locale (expected ${baseLocale}/translation.json)` });\n return { locales: [], keys: 0, problems };\n }\n\n let baseBundle: Map<string, unknown>;\n try {\n baseBundle = flatten(readBundle(baseFile));\n } catch (error: unknown) {\n problems.push({ locale: baseLocale, problem: `${baseFile}: ${error instanceof Error ? error.message : String(error)}` });\n return { locales: [], keys: 0, problems };\n }\n const baseKeys = new Set(baseBundle.keys());\n\n if (baseKeys.size === 0) {\n // An empty base is the one defect that reaches the most users: it is the fallback\n // for every missing key, so an empty value here is indistinguishable from a\n // missing bundle at runtime.\n problems.push({ locale: baseLocale, problem: `${baseFile} has no keys — the base bundle is empty or unreadable` });\n return { locales: [baseLocale], keys: 0, problems };\n }\n\n const locales = [...new Set([...tagsOnDisk(localesDir, shape), baseLocale])].sort((a, b) => a.localeCompare(b));\n for (const locale of locales) {\n const file = bundleFor(localesDir, locale, shape);\n if (file === undefined) {\n problems.push({ locale, problem: 'no bundle found' });\n continue;\n }\n let bundle: Map<string, unknown>;\n try {\n bundle = flatten(readBundle(file));\n } catch (error: unknown) {\n problems.push({ locale, problem: `${file}: ${error instanceof Error ? error.message : String(error)}` });\n continue;\n }\n for (const key of baseKeys) {\n if (!bundle.has(key)) problems.push({ locale, problem: `missing key: ${key}` });\n }\n for (const [key, value] of bundle) {\n if (!baseKeys.has(key)) {\n problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });\n continue;\n }\n // An empty value is reported for the base too. i18next renders `''` for a key\n // whose value is empty and for a key that is absent, so the two are the same\n // blank screen — which is why a \"translated\" locale can look complete in a\n // diff and be missing on the page.\n if (typeof value !== 'string' || value === '') {\n problems.push({ locale, problem: `empty value: ${key} — indistinguishable from a missing key at runtime` });\n continue;\n }\n // Placeholder parity. Substitution is by name, so a translation that drops\n // `{{count}}` renders the sentence with a hole in it and no error anywhere.\n const expected = placeholdersOf(baseBundle.get(key));\n if (expected.length === 0) continue;\n const actual = placeholdersOf(value);\n if (expected.length !== actual.length || expected.some((token, index) => token !== actual[index])) {\n problems.push({\n locale,\n problem: `placeholder mismatch at ${key}: ${locale} has ${JSON.stringify(actual)}, ${baseLocale} has ${JSON.stringify(expected)}`,\n });\n }\n }\n }\n\n return { locales, keys: baseKeys.size, problems };\n}\n\n/**\n * Every `t('key')` call site under a scope, with its inline default if it has one.\n *\n * This is the only part of the check that reaches the application rather than the\n * bundles: the rest compare bundle to bundle, so with one shipped language the whole\n * per-tag body is skipped and the script reports `ALL OK` having checked nothing\n * about the product — it cannot see that a key was used and absent, because the\n * string in the bundle did not exist to be wrong *about* anything.\n *\n * Dynamic keys cannot be resolved statically and are skipped rather than guessed:\n * a computed key that happens to start with a literal is a finding nobody can act\n * on, and one finding nobody can act on trains people to ignore the report.\n */\nfunction collectCallSites(scope: CallSiteScope, baseKeys: Set<string>, baseBundle: Map<string, unknown>): LocaleProblem[] {\n const problems: LocaleProblem[] = [];\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'coverage') continue;\n walk(full);\n continue;\n }\n if (scope.extensions.every((extension) => !entry.name.endsWith(extension))) continue;\n const source = readFileSync(full, 'utf8');\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n const pattern = /\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1\\s*(,)?/g;\n for (const match of source.matchAll(pattern)) {\n const key = match[2];\n if (key.includes('${') || key.includes('{{')) continue;\n const where = path.relative(process.cwd(), full) || full;\n if (!baseKeys.has(key)) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,\n });\n continue;\n }\n // A default that disagrees with the shipped bundle **fails**: one of the two\n // is a bug, and the default is the one that renders verbatim the day the key\n // goes missing — which is the fallback path the whole check is about.\n if (!match[3]) continue;\n const inline = readDefault(source, match.index + match[0].length);\n if (inline === null) continue;\n const bundled = baseBundle.get(key);\n if (inline !== bundled) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,\n });\n }\n }\n }\n };\n walk(scope.dir);\n return problems;\n}\n\n/**\n * The first string literal at `from`, or `null` when the next token is not one.\n *\n * The terminator is the literal's **own** quote character and never the other one.\n * A default that contains an apostrophe is the ordinary case here — these bundles\n * say things like `D1's daily write allowance` — so a scan that accepts either\n * quote stops at the apostrophe and reports `D1` as the whole default, turning a\n * correct file into a \"default disagrees\" failure on every line that quotes an\n * English possessive.\n */\nfunction readDefault(source: string, from: number): string | null {\n const rest = source.slice(from).replace(/^\\s+/, '');\n const quote = rest[0];\n if (quote !== \"'\" && quote !== '\"') return null;\n const body = rest.slice(1);\n const closer = quote === \"'\" ? /^(?:[^'\\\\]|\\\\.)*'/ : /^(?:[^\"\\\\]|\\\\.)*\"/;\n const match = closer.exec(body);\n if (!match) return null;\n return decodeStringLiteral(body.slice(0, match[0].length - 1));\n}\n\n/**\n * Decode a JS string literal as written in source, escapes and all.\n *\n * Only the escapes these bundles use are handled. An unrecognised one is passed\n * through as the backslash plus the character rather than throwing: a validator\n * that crashes on an unfamiliar escape reports nothing at all, which is worse than\n * reporting a value it had to guess at.\n */\nfunction decodeStringLiteral(raw: string): string {\n return raw.replaceAll(/\\\\(.)/gs, (whole, char: string) => {\n switch (char) {\n case 'n': {\n return '\\n';\n }\n case 't': {\n return '\\t';\n }\n case 'r': {\n return '\\r';\n }\n case '\\\\':\n case \"'\":\n case '\"':\n case '`': {\n return char;\n }\n default: {\n return whole;\n }\n }\n });\n}\n\n/**\nCLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?])`.\n\n`--call-sites=<dir>` opts into the application-side checks: every `t('key')` under\n`<dir>` must resolve against the base bundle, and any inline default must equal the\nbundled value. Without the flag the script stays bundle-to-bundle, because that is\nthe only part it can answer for a repo whose bundles are consumed by something\nother than `t()` — a backend string table, for instance.\n*/\nfunction validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'apps/web/src/locales';\n const shape = (argv.find((arg) => arg.startsWith('--shape='))?.slice('--shape='.length) ?? 'auto') as LocaleShape;\n const base = argv.find((arg) => arg.startsWith('--base='))?.slice('--base='.length) ?? 'en';\n const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);\n\n const report = validateLocales(dir, base, shape);\n const problems = [...report.problems];\n\n if (callSiteDir !== undefined && existsSync(callSiteDir)) {\n try {\n const baseBundle = bundleAt(dir, base, shape);\n problems.push(...collectCallSites({ dir: callSiteDir, extensions: ['.ts', '.tsx'] }, new Set(baseBundle.keys()), baseBundle));\n } catch (error: unknown) {\n problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n if (problems.length > 0) {\n console.error(`Locale validation failed for ${dir} (${problems.length} problem(s)):`);\n for (const problem of problems) console.error(` - ${problem.locale}: ${problem.problem}`);\n return 1;\n }\n console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);\n return 0;\n}\n\nexport { parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleProblem, LocaleReport, LocaleShape };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
-
"mappings": "+EAqCA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,OAAS,iBAAAC,MAAqB,WAC9B,OAAOC,MAAU,YA2BjB,SAASC,EAAQC,EAAgBC,EAAS,GAAIC,EAA4B,IAAI,IAAK,CACjF,GAAIF,IAAU,MAAQ,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EACpE,OAAIC,GAAQC,EAAI,IAAID,EAAQD,CAAK,EAC1BE,EAET,MAAMC,EAAU,OAAO,QAAQH,CAAgC,EAC/D,GAAIG,EAAQ,SAAW,EACrB,OAAIF,GAAQC,EAAI,IAAID,EAAQD,CAAK,EAC1BE,EAET,SAAW,CAACE,EAAKC,CAAK,IAAKF,EACzBJ,EAAQM,EAAOJ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EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EACzF,MAAO,EACT,CACA,eAAQ,IAAI,6BAA6BD,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB9C,CAAK,IAAI,EAC7G,CACT,CAzBS3B,EAAAoE,EAAA,sBAqCL,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQ7E,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAK6E,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
-
"names": ["existsSync", "readdirSync", "readFileSync", "pathToFileURL", "path", "flatten", "value", "prefix", "out", "entries", "key", "child", "__name", "placeholdersOf", "left", "right", "readBundle", "file", "source", "parseObjectLiteral", "objectLiteralStart", "quote", "inLineComment", "inBlockComment", "index", "char", "next", "previous", "brace", "start", "depth", "end", "withoutTrailingCommas", "_match", "body", "unescapeLiteral", "error", "FLAT_EXTENSION", "layouts", "shape", "tagsOnDisk", "localesDir", "tags", "entry", "layout", "extension", "name", "bundleFor", "locale", "candidates", "candidate", "bundleAt", "baseLocale", "validateLocales", "problems", "baseFile", "baseBundle", "baseKeys", "locales", "b", "bundle", "expected", "actual", "token", "collectCallSites", "scope", "
|
|
4
|
+
"sourcesContent": ["/**\n * Validate that every locale bundle carries exactly the base locale's keys.\n *\n * Provenance: `scripts/validate_locales.{mjs,ts}` in Durable-DAV, Edge-Git and\n * Mail-Meow, and Edge-Sonic's `scripts/i18n/locale-checks.ts` +\n * `validate_locales.ts`, converged. All four copies agree on the contract:\n * flattened dotted key paths, two-way parity (missing AND extra), no empty values,\n * no stray placeholders.\n *\n * ### What the convergence added\n *\n * Edge-Sonic's is the only copy that checks what a value *is*. The rest compare\n * bundle to bundle, so with one shipped language the whole per-tag body is skipped\n * and the script reports `ALL OK` having checked nothing about the application — it\n * could not see that `libraries.scanPausedRequests` was used and absent, because\n * the string in the bundle did not exist to be wrong *about* anything. Hence\n * `--call-sites`: every `t('key')` under `apps/web/src` must resolve.\n *\n * Key **order** drift against the base is a warning, not a failure: locale files\n * are maintained by mirroring new keys into every file, and failing on order would\n * turn an otherwise-correct translation update into a CI failure about formatting.\n *\n * ### Three on-disk shapes, one checker\n *\n * The family ships bundles in three shapes, and the shape is an argument rather\n * than a fork of the script:\n *\n * - `auto` (default) — every layout below, tried in order, so a repo that has\n * half-migrated is reported rather than silently skipped;\n * - `dir` — `<locales-dir>/<tag>/translation.json`, the i18next layout used by\n * seven repos;\n * - `file` — `<locales-dir>/<tag>.json`, one flat file per tag;\n * - `module` — `<locales-dir>/<tag>.ts` exporting an object literal, which is the\n * shape `@rexezuge/i18n` uses for the backend string bundles. The literal is\n * extracted and normalised here, so the same gate covers the backend catalogs\n * the kit ships and the SPA bundles the repos do.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\n\n/**\nThe bundle layouts the checker understands.\n*/\ntype LocaleShape = 'auto' | 'dir' | 'file' | 'module';\n\n/**\nOne defect, kept as a locale plus a message so a caller can group them.\n*/\ninterface LocaleProblem {\n locale: string;\n problem: string;\n /**\n * Reported, but not a failure.\n *\n * The distinction is **\"this build is wrong\"** against **\"this merge is still\n * in flight\"**, and a gate that cannot tell them apart gets switched off. A\n * key the bundles carry that no call site reaches is the ordinary state of a\n * bundle running ahead of its UI, and a translator adding a string for a screen\n * that has not been wired is doing the right thing. It is also the only thing\n * that catches a call site deleted or renamed without its key — which keeps a\n * translator re-translating a string no user will ever see.\n *\n * So it is reported and it does not fail the run.\n *\n * The finding that is **not** advisory is the mirror: a `t()` key the bundle\n * lacks. That one renders the inline default for every user in every language,\n * it is actionable in the same commit, and there is no in-flight state in which\n * it is the right answer — so it stays fatal, and the report below prints the\n * two classes separately rather than counting them together.\n */\n advisory?: boolean;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface LocaleReport {\n locales: string[];\n keys: number;\n problems: LocaleProblem[];\n}\n\n/**\nEvery dotted key path in a bundle, depth first.\n*/\nfunction flatten(value: unknown, prefix = '', out: Map<string, unknown> = new Map()): Map<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) {\n if (prefix) out.set(prefix, value);\n return out;\n }\n for (const [key, child] of entries) {\n flatten(child, prefix ? `${prefix}.${key}` : key, out);\n }\n return out;\n}\n\n/**\n * The interpolation tokens in a value, sorted.\n *\n * Sorted so two values carrying the same tokens in different orders compare equal —\n * substitution is by name, so order carries no meaning. `localeCompare` rather than\n * the default comparator so a reported mismatch does not change with the machine's\n * locale.\n */\nfunction placeholdersOf(value: unknown): string[] {\n if (typeof value !== 'string') return [];\n return [...new Set(value.match(/\\{\\{[^{}]+\\}\\}/g))].sort((left: string, right: string) => left.localeCompare(right));\n}\n\n/**\n * A source file to check `t()` call sites under, and how far down to look.\n */\ninterface CallSiteScope {\n /**\n Directory walked for source files.\n */\n dir: string;\n /**\n Extensions treated as source.\n */\n extensions: readonly string[];\n}\n\n/**\n * Read a bundle as a value, in whichever shape it is written.\n *\n * `module` is the shape `@rexezuge/i18n` ships: `const enStrings: BackendStrings =\n * { common: { unauthorized: '…' } };`. Extracting the literal rather than importing\n * the module is the point — a validator that imported the bundle would typecheck it\n * against the kit's own types, and therefore agree with whatever it was given.\n */\nfunction readBundle(file: string): unknown {\n const source = readFileSync(file, 'utf8');\n // Decided by the file's extension, not by the caller's `shape`: under `auto` a\n // `.ts` bundle is found, and reading it as JSON would report a parse error for a\n // file that is perfectly well-formed.\n return file.endsWith('.ts') ? parseObjectLiteral(source, file) : (JSON.parse(source) as unknown);\n}\n\n/**\n * The first balanced object literal in a TypeScript module, as a value.\n *\n * Brace-matched outside strings and comments, and started at the **first\n * assignment** rather than at the first brace — see `objectLiteralStart` for why the\n * difference is the whole rule. Single-quoted strings are normalised to\n * double-quoted JSON, bare keys are quoted, and trailing commas are tolerated: that\n * is all the shape this needs, and a translator file that needs more is not a\n * translator file.\n */\n/**\n * Where the object literal begins: the first brace **after the first assignment**.\n *\n * The assignment matters. `const enStrings: BackendStrings = { ... }` is preceded by\n * an import line whose own braces open earlier in the file, so a plain\n * `indexOf('{')` returns the import's pair and the \"literal\" extracted is\n * `{ BackendStrings }` — an empty object that parses cleanly and then reports the\n * base bundle as having no keys. Finding the assignment first skips every brace that\n * is not the value being bound to it.\n */\nfunction objectLiteralStart(source: string): number {\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = 0; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n // The assignment, and not a comparison or an arrow: `=>` and `==` both contain an\n // `=`, and neither is where a bundle's object literal is attached.\n const previous = source[index - 1];\n if (char === '=' && next !== '=' && next !== '>' && previous !== '=' && previous !== '!' && previous !== '<' && previous !== '>') {\n const brace = source.indexOf('{', index);\n return brace === -1 ? -1 : brace;\n }\n }\n return -1;\n}\n\nfunction parseObjectLiteral(source: string, file: string): unknown {\n const start = objectLiteralStart(source);\n if (start === -1) {\n throw new Error(`${file} has no object literal`);\n }\n\n let depth = 0;\n let end = -1;\n let quote = '';\n let inLineComment = false;\n let inBlockComment = false;\n for (let index = start; index < source.length; index += 1) {\n const char = source[index];\n\n if (inLineComment) {\n if (char === '\\n') inLineComment = false;\n continue;\n }\n const next = source[index + 1];\n if (inBlockComment) {\n if (char === '*' && next === '/') {\n inBlockComment = false;\n index += 1;\n }\n continue;\n }\n if (quote !== '') {\n // An escape consumes the next character, so `\\'` does not close the string.\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === quote) quote = '';\n continue;\n }\n if (char === '-' && next === '-') {\n inLineComment = true;\n continue;\n }\n if (char === '/' && next === '*') {\n inBlockComment = true;\n continue;\n }\n if (char === \"'\" || char === '\"' || char === '`') {\n quote = char;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n end = index;\n break;\n }\n }\n }\n if (end === -1) {\n throw new Error(`${file} has an unterminated object literal`);\n }\n\n const literal = source.slice(start, end + 1);\n // Three normalisations, each of which a JSON parser needs and a TS literal does not:\n // single-quoted strings become double-quoted (applied only to string literals, so a\n // value containing an apostrophe keeps it), bare keys get quoted, and trailing\n // commas are dropped. A translator file that needs more than that is not a\n // translator file.\n const doubleQuoted = literal.replaceAll(/'((?:[^'\\\\]|\\\\.)*)'/g, (_match, body: string) => JSON.stringify(unescapeLiteral(body)));\n const quotedKeys = doubleQuoted.replaceAll(/([{,]\\s*)([A-Z_$][\\w$]*)(\\s*:)/gi, '$1\"$2\"$3');\n const withoutTrailingCommas = quotedKeys.replaceAll(/,(\\s*[}\\]])/g, '$1');\n\n try {\n return JSON.parse(withoutTrailingCommas) as unknown;\n } catch (error: unknown) {\n throw new Error(`${file} object literal could not be parsed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\nThe escapes a translator file actually uses; anything else is passed through.\n*/\nfunction unescapeLiteral(body: string): string {\n return body\n .replaceAll(String.raw`\\'`, \"'\")\n .replaceAll(String.raw`\\\"`, '\"')\n .replaceAll(String.raw`\\n`, '\\n')\n .replaceAll(String.raw`\\t`, '\\t')\n .replaceAll(String.raw`\\\\`, '\\\\');\n}\n\n/**\nThe extensions a flat layout uses, keyed by shape.\n*/\nconst FLAT_EXTENSION: Record<'file' | 'module', string> = { file: 'json', module: 'ts' };\n\n/**\nThe layouts `shape` covers. `auto` covers all three, in the order they are tried.\n*/\nfunction layouts(shape: LocaleShape): Array<'dir' | 'file' | 'module'> {\n return shape === 'auto' ? ['dir', 'file', 'module'] : [shape];\n}\n\n/**\nThe tags on disk, in whichever layouts `shape` covers.\n*/\nfunction tagsOnDisk(localesDir: string, shape: LocaleShape): string[] {\n const tags: string[] = [];\n if (layouts(shape).includes('dir')) {\n tags.push(\n ...readdirSync(localesDir, { withFileTypes: true })\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name),\n );\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n const extension = FLAT_EXTENSION[layout];\n tags.push(\n ...readdirSync(localesDir)\n .filter((name) => name.endsWith(`.${extension}`))\n .map((name) => name.slice(0, -extension.length - 1)),\n );\n }\n return tags;\n}\n\n/**\n * The file a tag's bundle lives in, or `undefined` when it is not there.\n *\n * Every candidate is tried rather than only the one `shape` names, because a repo\n * with a half-migrated tree is a repo whose missing half should be reported. A\n * checker that only looked where it was told would read a bundle that exists as\n * absent, and a missing bundle is the defect this script exists to find.\n */\nfunction bundleFor(localesDir: string, locale: string, shape: LocaleShape): string | undefined {\n const candidates: string[] = [];\n if (layouts(shape).includes('dir')) {\n candidates.push(path.join(localesDir, locale, 'translation.json'));\n }\n for (const layout of layouts(shape)) {\n if (layout === 'dir') continue;\n candidates.push(path.join(localesDir, `${locale}.${FLAT_EXTENSION[layout]}`));\n }\n return candidates.find((candidate) => existsSync(candidate));\n}\n\n/**\n * The base bundle, flattened, for a scope that checks the application against it.\n *\n * @throws when the bundle cannot be found or parsed — the caller reports that as a\n * problem rather than reporting \"all clear\" against an empty key set, which is\n * the one outcome a locale gate must never produce silently.\n */\nfunction bundleAt(localesDir: string, baseLocale: string, shape: LocaleShape): Map<string, unknown> {\n const file = bundleFor(localesDir, baseLocale, shape);\n if (file === undefined) {\n throw new Error(`no bundle found for the base locale (expected ${baseLocale}/translation.json)`);\n }\n return flatten(readBundle(file));\n}\n\n/**\n * Validate a directory of locale bundles against `baseLocale`'s key set.\n *\n * Two-way parity: a key the base has and a bundle lacks renders the fallback, and\n * a key a bundle has that the base lacks is dead weight nothing can translate from.\n */\nfunction validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleShape = 'auto'): LocaleReport {\n const problems: LocaleProblem[] = [];\n if (!existsSync(localesDir)) {\n problems.push({ locale: baseLocale, problem: `${localesDir} does not exist` });\n return { locales: [], keys: 0, problems };\n }\n\n const baseFile = bundleFor(localesDir, baseLocale, shape);\n if (baseFile === undefined) {\n problems.push({ locale: baseLocale, problem: `no bundle found for the base locale (expected ${baseLocale}/translation.json)` });\n return { locales: [], keys: 0, problems };\n }\n\n let baseBundle: Map<string, unknown>;\n try {\n baseBundle = flatten(readBundle(baseFile));\n } catch (error: unknown) {\n problems.push({ locale: baseLocale, problem: `${baseFile}: ${error instanceof Error ? error.message : String(error)}` });\n return { locales: [], keys: 0, problems };\n }\n const baseKeys = new Set(baseBundle.keys());\n\n if (baseKeys.size === 0) {\n // An empty base is the one defect that reaches the most users: it is the fallback\n // for every missing key, so an empty value here is indistinguishable from a\n // missing bundle at runtime.\n problems.push({ locale: baseLocale, problem: `${baseFile} has no keys — the base bundle is empty or unreadable` });\n return { locales: [baseLocale], keys: 0, problems };\n }\n\n const locales = [...new Set([...tagsOnDisk(localesDir, shape), baseLocale])].sort((a, b) => a.localeCompare(b));\n for (const locale of locales) {\n const file = bundleFor(localesDir, locale, shape);\n if (file === undefined) {\n problems.push({ locale, problem: 'no bundle found' });\n continue;\n }\n let bundle: Map<string, unknown>;\n try {\n bundle = flatten(readBundle(file));\n } catch (error: unknown) {\n problems.push({ locale, problem: `${file}: ${error instanceof Error ? error.message : String(error)}` });\n continue;\n }\n for (const key of baseKeys) {\n if (!bundle.has(key)) problems.push({ locale, problem: `missing key: ${key}` });\n }\n for (const [key, value] of bundle) {\n if (!baseKeys.has(key)) {\n problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });\n continue;\n }\n // An empty value is reported for the base too. i18next renders `''` for a key\n // whose value is empty and for a key that is absent, so the two are the same\n // blank screen — which is why a \"translated\" locale can look complete in a\n // diff and be missing on the page.\n if (typeof value !== 'string' || value === '') {\n problems.push({ locale, problem: `empty value: ${key} — indistinguishable from a missing key at runtime` });\n continue;\n }\n // Placeholder parity. Substitution is by name, so a translation that drops\n // `{{count}}` renders the sentence with a hole in it and no error anywhere.\n const expected = placeholdersOf(baseBundle.get(key));\n if (expected.length === 0) continue;\n const actual = placeholdersOf(value);\n if (expected.length !== actual.length || expected.some((token, index) => token !== actual[index])) {\n problems.push({\n locale,\n problem: `placeholder mismatch at ${key}: ${locale} has ${JSON.stringify(actual)}, ${baseLocale} has ${JSON.stringify(expected)}`,\n });\n }\n }\n }\n\n return { locales, keys: baseKeys.size, problems };\n}\n\n/**\n * Every `t('key')` call site under a scope, with its inline default if it has one.\n *\n * This is the only part of the check that reaches the application rather than the\n * bundles: the rest compare bundle to bundle, so with one shipped language the whole\n * per-tag body is skipped and the script reports `ALL OK` having checked nothing\n * about the product — it cannot see that a key was used and absent, because the\n * string in the bundle did not exist to be wrong *about* anything.\n *\n * Dynamic keys cannot be resolved statically and are skipped rather than guessed:\n * a computed key that happens to start with a literal is a finding nobody can act\n * on, and one finding nobody can act on trains people to ignore the report.\n */\nfunction collectCallSites(scope: CallSiteScope, baseKeys: Set<string>, baseBundle: Map<string, unknown>): LocaleProblem[] {\n const problems: LocaleProblem[] = [];\n for (const full of sourceFiles(scope)) {\n const source = readFileSync(full, 'utf8');\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n const pattern = /\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1\\s*(,)?/g;\n for (const match of source.matchAll(pattern)) {\n const key = match[2];\n if (key.includes('${') || key.includes('{{')) continue;\n const where = path.relative(process.cwd(), full) || full;\n if (!baseKeys.has(key)) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,\n });\n continue;\n }\n // A default that disagrees with the shipped bundle **fails**: one of the two\n // is a bug, and the default is the one that renders verbatim the day the key\n // goes missing — which is the fallback path the whole check is about.\n if (!match[3]) continue;\n const inline = readDefault(source, match.index + match[0].length);\n if (inline === null) continue;\n const bundled = baseBundle.get(key);\n if (inline !== bundled) {\n problems.push({\n locale: 'call-site',\n problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,\n });\n }\n }\n }\n return problems;\n}\n\n/**\n * The first string literal at `from`, or `null` when the next token is not one.\n *\n * The terminator is the literal's **own** quote character and never the other one.\n * A default that contains an apostrophe is the ordinary case here — these bundles\n * say things like `D1's daily write allowance` — so a scan that accepts either\n * quote stops at the apostrophe and reports `D1` as the whole default, turning a\n * correct file into a \"default disagrees\" failure on every line that quotes an\n * English possessive.\n */\nfunction readDefault(source: string, from: number): string | null {\n const rest = source.slice(from).replace(/^\\s+/, '');\n const quote = rest[0];\n if (quote !== \"'\" && quote !== '\"') return null;\n const body = rest.slice(1);\n const closer = quote === \"'\" ? /^(?:[^'\\\\]|\\\\.)*'/ : /^(?:[^\"\\\\]|\\\\.)*\"/;\n const match = closer.exec(body);\n if (!match) return null;\n return decodeStringLiteral(body.slice(0, match[0].length - 1));\n}\n\n/**\n * Decode a JS string literal as written in source, escapes and all.\n *\n * Only the escapes these bundles use are handled. An unrecognised one is passed\n * through as the backslash plus the character rather than throwing: a validator\n * that crashes on an unfamiliar escape reports nothing at all, which is worse than\n * reporting a value it had to guess at.\n */\nfunction decodeStringLiteral(raw: string): string {\n return raw.replaceAll(/\\\\(.)/gs, (whole, char: string) => {\n switch (char) {\n case 'n': {\n return '\\n';\n }\n case 't': {\n return '\\t';\n }\n case 'r': {\n return '\\r';\n }\n case '\\\\':\n case \"'\":\n case '\"':\n case '`': {\n return char;\n }\n default: {\n return whole;\n }\n }\n });\n}\n\n/**\n * Every key a `t()` call site names literally, under one scope.\n *\n * Extracted from {@link collectCallSites} so the unused-key sweep and the\n * unresolved-key check read the **same** set. Two scanners that each carry their\n * own idea of what a call site looks like disagree on exactly the interesting\n * case — a shape one understands and the other does not — and then report a key\n * as both unused and used.\n */\nfunction usedKeys(scope: CallSiteScope): Set<string> {\n const used = new Set<string>();\n for (const file of sourceFiles(scope)) {\n // `t('…')` / `t(\"…\")` with a string literal first argument. The key is the\n // single source of truth for what is rendered, so anything else is out of scope.\n for (const match of readFileSync(file, 'utf8').matchAll(/\\bt\\(\\s*(['\"])((?:[^'\"\\\\]|\\\\.)*)\\1/g)) {\n const key = match[2];\n if (!key.includes('${') && !key.includes('{{')) used.add(key);\n }\n }\n return used;\n}\n\n/**\n * Every source file a scope covers, walking the skip list once.\n */\nfunction sourceFiles(scope: CallSiteScope): string[] {\n const files: string[] = [];\n const walk = (dir: string): void => {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'coverage') continue;\n walk(full);\n continue;\n }\n if (scope.extensions.some((extension) => entry.name.endsWith(extension))) files.push(full);\n }\n };\n walk(scope.dir);\n return files;\n}\n\n/**\n * Base-bundle keys that no `t()` call site reaches.\n *\n * Advisory by construction, and for the reason {@link LocaleProblem.advisory}\n * gives: a bundle routinely runs ahead of its UI, and a translator adding a\n * string for a screen that has not been wired is doing the right thing. What it\n * also catches is the case that matters — a renamed or deleted call site whose\n * key was never removed, which keeps a translator re-translating a string no\n * user will ever see.\n *\n * Dynamic keys are **not** reported as unused. `` t(`section.${name}`) `` cannot\n * be resolved statically, so every key under that prefix would look dead; the\n * honest answer is \"unknown\", and an `unknown` reported as `unused` is the kind\n * of finding that makes a gate useless.\n */\nfunction collectUnusedKeys(baseKeys: readonly string[], scope: CallSiteScope, used: Set<string>): LocaleProblem[] {\n const prefixes = dynamicKeyPrefixes(scope);\n const unused = baseKeys.filter(\n (key) => !used.has(key) && [...prefixes].every((prefix) => !(key === prefix || key.startsWith(`${prefix}.`))),\n );\n if (unused.length === 0) return [];\n return [\n {\n locale: 'call-site',\n problem: `${unused.length} base key(s) are not reached by any t() call site: ${unused.slice(0, 20).join(', ')}${unused.length > 20 ? ', …' : ''}`,\n advisory: true,\n },\n ];\n}\n\n/**\n * The longest literal prefix of every dynamically-built key.\n *\n * A prefix rather than a whole key, because only the static head of\n * `` t(`nav.${item}`) `` is knowable, and the keys it may resolve to are exactly\n * the ones a static scan must not claim are dead.\n */\nfunction dynamicKeyPrefixes(scope: CallSiteScope): Set<string> {\n const prefixes = new Set<string>();\n for (const file of sourceFiles(scope)) {\n for (const match of readFileSync(file, 'utf8').matchAll(/\\bt\\(\\s*`([^`$]*)\\$\\{/g)) {\n const head = match[1].replace(/\\.$/, '');\n if (head) prefixes.add(head);\n }\n }\n return prefixes;\n}\n\n/**\n * The string tags a locale directory declares, parsed from a source file.\n *\n * A declared list and a directory of bundles are two independent facts about the\n * same thing, and the only one that can be wrong *silently* is the declared list:\n * a tag with no directory makes a runtime `import.meta.glob` lookup throw the\n * moment that language is chosen, which is a support ticket and not a build\n * failure. A directory with no declaration is a translation nobody can select.\n *\n * Parsed as text rather than imported, because the declaring file is a TypeScript\n * module in the app being linted and importing it would run it.\n */\nfunction declaredTags(file: string): string[] {\n const source = readFileSync(file, 'utf8');\n const match = /(?:export\\s+)?const\\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\\s*=\\s*\\[([^\\]]*)\\]/.exec(source);\n if (!match) throw new Error(`${file} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);\n return [...(match[1] ?? '').matchAll(/['\"]([^'\"]+)['\"]/g)].map((tag) => tag[1]);\n}\n\n/**\n * Cross-check a declared tag list against the bundle directories, both ways.\n *\n * Both directions are findings because both are wrong states: declared-but-absent\n * is a runtime throw on selection, present-but-undeclared is a bundle no\n * selector offers.\n */\nfunction checkDeclaredTags(localesDir: string, declaredFile: string, onDisk: readonly string[]): LocaleProblem[] {\n const declared = declaredTags(declaredFile);\n const problems: LocaleProblem[] = [];\n for (const tag of declared) {\n if (!onDisk.includes(tag)) {\n problems.push({\n locale: 'tags',\n problem: `${declaredFile} declares '${tag}' but ${localesDir}/${tag} does not exist — selecting that language throws`,\n });\n }\n }\n for (const tag of onDisk) {\n if (!declared.includes(tag)) {\n problems.push({\n locale: 'tags',\n problem: `${localesDir}/${tag} exists but ${declaredFile} does not declare it — the selector cannot offer it`,\n });\n }\n }\n return problems;\n}\n\n/**\nCLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?, '--tags=<file>'?])`.\n\n`--call-sites=<dir>` opts into the application-side checks: every `t('key')` under\n`<dir>` must resolve against the base bundle, and any inline default must equal the\nbundled value. Without the flag the script stays bundle-to-bundle, because that is\nthe only part it can answer for a repo whose bundles are consumed by something\nother than `t()` — a backend string table, for instance.\n\n`--tags=<file>` cross-checks a declared `SUPPORTED_LANGUAGES` / `SUPPORTED_LOCALES`\narray against the bundle directories, in both directions. It is separate from\n`--call-sites` because a repo can declare its tags in a file the scan never walks,\nand a directory of bundles with no declaration is exactly the state a\nbundle-to-bundle check reports as perfectly healthy.\n*/\nfunction validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'apps/web/src/locales';\n const shape = (argv.find((arg) => arg.startsWith('--shape='))?.slice('--shape='.length) ?? 'auto') as LocaleShape;\n const base = argv.find((arg) => arg.startsWith('--base='))?.slice('--base='.length) ?? 'en';\n const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);\n const tagsFile = argv.find((arg) => arg.startsWith('--tags='))?.slice('--tags='.length);\n\n const report = validateLocales(dir, base, shape);\n const problems = [...report.problems];\n\n if (tagsFile !== undefined && existsSync(tagsFile)) {\n try {\n problems.push(...checkDeclaredTags(dir, tagsFile, tagsOnDisk(dir, shape)));\n } catch (error: unknown) {\n problems.push({ locale: 'tags', problem: `${tagsFile}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n if (callSiteDir !== undefined && existsSync(callSiteDir)) {\n try {\n const baseBundle = bundleAt(dir, base, shape);\n const scope = { dir: callSiteDir, extensions: ['.ts', '.tsx'] };\n const used = usedKeys(scope);\n problems.push(\n ...collectCallSites(scope, new Set(baseBundle.keys()), baseBundle),\n ...collectUnusedKeys([...baseBundle.keys()], scope, used),\n );\n } catch (error: unknown) {\n problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });\n }\n }\n\n const failures = problems.filter((problem) => problem.advisory !== true);\n const advisories = problems.filter((problem) => problem.advisory === true);\n\n if (failures.length > 0) {\n console.error(`Locale validation failed for ${dir} (${failures.length} problem(s)):`);\n for (const problem of failures) console.error(` - ${problem.locale}: ${problem.problem}`);\n return 1;\n }\n if (advisories.length > 0) {\n console.warn(`Locale validation passed for ${dir} with ${advisories.length} advisory finding(s):`);\n for (const problem of advisories) console.warn(` - ${problem.locale}: ${problem.problem}`);\n }\n console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);\n return 0;\n}\n\nexport { parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleProblem, LocaleReport, LocaleShape };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAqCA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,OAAS,iBAAAC,MAAqB,WAC9B,OAAOC,MAAU,YA+CjB,SAASC,EAAQC,EAAgBC,EAA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AAE,EAAGA,CAAU,EACjE,GAAG6B,EAAkB,CAAC,GAAG7B,EAAW,KAAI,CAAE,EAAGU,EAAOe,CAAI,CAAC,CAE7D,OAAS7C,EAAgB,CACvBkB,EAAS,KAAK,CAAE,OAAQ,YAAa,QAAS,GAAG8C,CAAW,KAAKhE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAAE,CAC7H,CAGF,MAAMmE,EAAWjD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EACjEC,EAAanD,EAAS,OAAQkD,GAAYA,EAAQ,WAAa,EAAI,EAEzE,GAAID,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,gCAAgCnB,CAAG,KAAKmB,EAAS,MAAM,eAAe,EACpF,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EACzF,MAAO,EACT,CACA,GAAIC,EAAW,OAAS,EAAG,CACzB,QAAQ,KAAK,gCAAgCrB,CAAG,SAASqB,EAAW,MAAM,uBAAuB,EACjG,UAAWD,KAAWC,EAAY,QAAQ,KAAK,OAAOD,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,CAC5F,CACA,eAAQ,IAAI,6BAA6BF,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB/D,CAAK,IAAI,EAC7G,CACT,CA9CS3B,EAAAoF,EAAA,sBA0DL,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQ7F,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAK6F,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
+
"names": ["existsSync", "readdirSync", "readFileSync", "pathToFileURL", "path", "flatten", "value", "prefix", "out", "entries", "key", "child", "__name", "placeholdersOf", "left", "right", "readBundle", "file", "source", "parseObjectLiteral", "objectLiteralStart", "quote", "inLineComment", "inBlockComment", "index", "char", "next", "previous", "brace", "start", "depth", "end", "withoutTrailingCommas", "_match", "body", "unescapeLiteral", "error", "FLAT_EXTENSION", "layouts", "shape", "tagsOnDisk", "localesDir", "tags", "entry", "layout", "extension", "name", "bundleFor", "locale", "candidates", "candidate", "bundleAt", "baseLocale", "validateLocales", "problems", "baseFile", "baseBundle", "baseKeys", "locales", "a", "b", "bundle", "expected", "actual", "token", "collectCallSites", "scope", "full", "sourceFiles", "pattern", "match", "where", "inline", "readDefault", "bundled", "from", "rest", "decodeStringLiteral", "raw", "whole", "usedKeys", "used", "files", "walk", "dir", "collectUnusedKeys", "prefixes", "dynamicKeyPrefixes", "unused", "head", "declaredTags", "tag", "checkDeclaredTags", "declaredFile", "onDisk", "declared", "validateLocalesCli", "argv", "arg", "base", "callSiteDir", "tagsFile", "report", "failures", "problem", "advisories"]
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rexezuge/tooling",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"src"
|
|
39
39
|
],
|
|
40
40
|
"dependencies": {
|
|
41
|
-
"@rexezuge/d1": "1.
|
|
41
|
+
"@rexezuge/d1": "1.8.0"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"eslint": "^10.0.0",
|
package/src/eslint-boundaries.ts
CHANGED
|
@@ -217,25 +217,56 @@ export function layerBans(scope: string): readonly LayerBan[] {
|
|
|
217
217
|
type ConfigInput = Parameters<typeof tseslint.config>[number];
|
|
218
218
|
|
|
219
219
|
/**
|
|
220
|
-
* The
|
|
220
|
+
* The bans for one directory, in table order.
|
|
221
|
+
*
|
|
222
|
+
* **Grouping is load-bearing, not tidiness.** Flat config merges every matching
|
|
223
|
+
* config object and resolves each rule name by *last entry wins* — so two
|
|
224
|
+
* entries with the same `files` glob do not accumulate, the second replaces the
|
|
225
|
+
* first's rule outright. Emitting one entry per `LayerBan` therefore meant that
|
|
226
|
+
* a directory appearing twice in the table (`apps/api` does, four times) kept
|
|
227
|
+
* only its last row: the DAO ban and the `provider-clients` ban vanished, and
|
|
228
|
+
* the layer table in the kit's own documentation described a gate that was not
|
|
229
|
+
* running. It could not be caught by asserting a rule exists for a dir — the
|
|
230
|
+
* surviving rule exists — only by asserting every ban in the table survives.
|
|
231
|
+
*
|
|
232
|
+
* Merging happens at the **pattern** level rather than the layer level, because
|
|
233
|
+
* the two things a layer carries are not mergeable: each group keeps its own
|
|
234
|
+
* `message`, and `allowTypeImports` belongs to a group (`apps/api` may type its
|
|
235
|
+
* filters against DAO shapes but may not reach `provider-clients` even as a
|
|
236
|
+
* type). One config object per directory, every pattern inside it.
|
|
237
|
+
*/
|
|
238
|
+
function groupedByDir(bans: readonly LayerBan[]): Map<string, LayerBan[]> {
|
|
239
|
+
const grouped = new Map<string, LayerBan[]>();
|
|
240
|
+
for (const ban of bans) {
|
|
241
|
+
const existing = grouped.get(ban.dir);
|
|
242
|
+
if (existing) existing.push(ban);
|
|
243
|
+
else grouped.set(ban.dir, [ban]);
|
|
244
|
+
}
|
|
245
|
+
return grouped;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* The `no-restricted-imports` entries, one per directory.
|
|
221
250
|
*
|
|
222
251
|
* Written as `group` patterns rather than exact `paths`, so `@myapp/backend-data`
|
|
223
252
|
* and `@myapp/backend-data/dao` are both caught by one entry. `allowTypeImports`
|
|
224
|
-
* is
|
|
225
|
-
*
|
|
253
|
+
* is carried per group rather than per directory, because only the DAO boundary
|
|
254
|
+
* sets it.
|
|
226
255
|
*/
|
|
227
256
|
export function restrictedImports(bans: readonly LayerBan[]): ConfigInput[] {
|
|
228
|
-
return bans.map((
|
|
257
|
+
return [...groupedByDir(bans)].map(([dir, layers]) => ({
|
|
229
258
|
files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],
|
|
230
259
|
rules: {
|
|
231
260
|
'no-restricted-imports': [
|
|
232
261
|
'error',
|
|
233
262
|
{
|
|
234
|
-
patterns:
|
|
235
|
-
group
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
263
|
+
patterns: layers.flatMap(({ ban, message, allowTypeImports }) =>
|
|
264
|
+
ban.map((group) => ({
|
|
265
|
+
group: [group, `${group}/*`],
|
|
266
|
+
message,
|
|
267
|
+
...(allowTypeImports === true && { allowTypeImports: true }),
|
|
268
|
+
})),
|
|
269
|
+
),
|
|
239
270
|
},
|
|
240
271
|
],
|
|
241
272
|
},
|
|
@@ -253,17 +284,23 @@ export function restrictedImports(bans: readonly LayerBan[]): ConfigInput[] {
|
|
|
253
284
|
* hole was load-bearing there: the credential path reached a banned module
|
|
254
285
|
* through it. `no-restricted-syntax` sees `ImportExpression`, so the boundary is
|
|
255
286
|
* stated a second way.
|
|
287
|
+
*
|
|
288
|
+
* Grouped per directory for the same reason {@link restrictedImports} is: one
|
|
289
|
+
* entry per layer would leave only the last row standing, and `no-restricted-syntax`
|
|
290
|
+
* merges exactly like `no-restricted-imports` does.
|
|
256
291
|
*/
|
|
257
292
|
export function restrictedDynamicImports(bans: readonly LayerBan[]): ConfigInput[] {
|
|
258
|
-
return bans.map((
|
|
293
|
+
return [...groupedByDir(bans)].map(([dir, layers]) => ({
|
|
259
294
|
files: [`${dir}/**/*.{ts,js,mts,cts,mjs,cjs}`],
|
|
260
295
|
rules: {
|
|
261
296
|
'no-restricted-syntax': [
|
|
262
297
|
'error',
|
|
263
|
-
...
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
298
|
+
...layers.flatMap(({ ban, message }) =>
|
|
299
|
+
ban.map((specifier) => ({
|
|
300
|
+
selector: `ImportExpression[source.type='Literal'][source.value=/^${specifier.replaceAll('/', String.raw`\/`)}/]`,
|
|
301
|
+
message: `A dynamic import() is not covered by no-restricted-imports, so this layer reaches \`${specifier}\` through the one syntax that gate does not see. Both say no: ${message}`,
|
|
302
|
+
})),
|
|
303
|
+
),
|
|
267
304
|
],
|
|
268
305
|
},
|
|
269
306
|
}));
|
package/src/eslint.test.ts
CHANGED
|
@@ -143,6 +143,29 @@ describe('defineRepoLintConfig', () => {
|
|
|
143
143
|
expect(rules).toContain('ships zero backend dependencies');
|
|
144
144
|
});
|
|
145
145
|
|
|
146
|
+
it('keeps every ban for a directory that appears more than once in the table', () => {
|
|
147
|
+
// `apps/api` carries four rows in the canonical table: the DAO boundary plus
|
|
148
|
+
// one per direct-client package. Flat config resolves a repeated rule by
|
|
149
|
+
// last-entry-wins, so emitting one entry per row kept only the last and
|
|
150
|
+
// silently dropped the DAO ban and `provider-clients` — the gate described
|
|
151
|
+
// in the kit's own table was not running. Asserted on the *merged* result
|
|
152
|
+
// for a file in that directory, because a single row always linted
|
|
153
|
+
// correctly on its own; only the accumulation was wrong.
|
|
154
|
+
const rules = rulesOf(config, 'apps/api/src/endpoints/users/index.ts');
|
|
155
|
+
const imports = JSON.stringify(rules['no-restricted-imports']);
|
|
156
|
+
expect(imports).toContain('@fixture/backend-data/dao');
|
|
157
|
+
expect(imports).toContain('@fixture/provider-clients');
|
|
158
|
+
// The DAO row allows type-only imports; the client row must not inherit that
|
|
159
|
+
// from its neighbour in the same merged object.
|
|
160
|
+
const patterns = (rules['no-restricted-imports'] as [string, { patterns: Record<string, unknown>[] }])[1].patterns;
|
|
161
|
+
expect(patterns.find((p) => (p['group'] as string[])[0] === '@fixture/backend-data/dao')?.['allowTypeImports']).toBe(true);
|
|
162
|
+
expect(patterns.find((p) => (p['group'] as string[])[0] === '@fixture/provider-clients')?.['allowTypeImports']).toBeUndefined();
|
|
163
|
+
|
|
164
|
+
const syntax = JSON.stringify(rules['no-restricted-syntax']);
|
|
165
|
+
expect(syntax).toContain('@fixture/backend-data/dao');
|
|
166
|
+
expect(syntax).toContain('@fixture/provider-clients');
|
|
167
|
+
});
|
|
168
|
+
|
|
146
169
|
it('mirrors every boundary in a dynamic-import guard', () => {
|
|
147
170
|
const syntax = rulesOf(config, 'packages/backend-runtime/src/x.ts')['no-restricted-syntax'];
|
|
148
171
|
expect(Array.isArray(syntax)).toBe(true);
|
|
@@ -104,18 +104,99 @@ describe('validateLocales', () => {
|
|
|
104
104
|
* reporter's formatting rather than on the finding.
|
|
105
105
|
*/
|
|
106
106
|
function capture(fn: () => number): { code: number; out: string } {
|
|
107
|
-
const original = { error: console.error, log: console.log };
|
|
107
|
+
const original = { error: console.error, log: console.log, warn: console.warn };
|
|
108
108
|
let out = '';
|
|
109
109
|
console.error = (...args: unknown[]): void => void (out += `${args.join(' ')}\n`);
|
|
110
110
|
console.log = (...args: unknown[]): void => void (out += `${args.join(' ')}\n`);
|
|
111
|
+
console.warn = (...args: unknown[]): void => void (out += `${args.join(' ')}\n`);
|
|
111
112
|
try {
|
|
112
113
|
return { code: fn(), out };
|
|
113
114
|
} finally {
|
|
114
115
|
console.error = original.error;
|
|
115
116
|
console.log = original.log;
|
|
117
|
+
console.warn = original.warn;
|
|
116
118
|
}
|
|
117
119
|
}
|
|
118
120
|
|
|
121
|
+
describe('validateLocalesCli --tags', () => {
|
|
122
|
+
function declared(root: string, tags: string[]): string {
|
|
123
|
+
const file = path.join(root, 'i18n.ts');
|
|
124
|
+
writeFileSync(file, `export const SUPPORTED_LANGUAGES = [${tags.map((tag) => `'${tag}'`).join(', ')}] as const;\n`);
|
|
125
|
+
return file;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
it('passes when the declared list and the bundle directories agree', () => {
|
|
129
|
+
const root = repo();
|
|
130
|
+
bundle(root, 'en', { common: { save: 'Save' } });
|
|
131
|
+
bundle(root, 'de', { common: { save: 'Speichern' } });
|
|
132
|
+
const file = declared(root, ['en', 'de']);
|
|
133
|
+
const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--tags=${file}`]));
|
|
134
|
+
expect(out).not.toContain('do not agree');
|
|
135
|
+
expect(code).toBe(0);
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it('fails on a declared tag with no bundle, which throws the moment that language is chosen', () => {
|
|
139
|
+
// The check that cannot be caught by parity: twelve bundles in perfect
|
|
140
|
+
// agreement, and a selector offering a thirteenth.
|
|
141
|
+
const root = repo();
|
|
142
|
+
bundle(root, 'en', { common: { save: 'Save' } });
|
|
143
|
+
const file = declared(root, ['en', 'ja']);
|
|
144
|
+
const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--tags=${file}`]));
|
|
145
|
+
expect(out).toContain("declares 'ja' but");
|
|
146
|
+
expect(code).toBe(1);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('fails on a bundle no selector offers', () => {
|
|
150
|
+
const root = repo();
|
|
151
|
+
bundle(root, 'en', { common: { save: 'Save' } });
|
|
152
|
+
bundle(root, 'ko', { common: { save: '저장' } });
|
|
153
|
+
const file = declared(root, ['en']);
|
|
154
|
+
const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--tags=${file}`]));
|
|
155
|
+
expect(out).toContain('cannot offer it');
|
|
156
|
+
expect(code).toBe(1);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
describe('validateLocalesCli --call-sites advisory findings', () => {
|
|
161
|
+
it('reports a base key no call site reaches without failing the run', () => {
|
|
162
|
+
// A bundle routinely runs ahead of its UI, so this is a merge in progress
|
|
163
|
+
// rather than a broken build — but it is also the only thing that catches a
|
|
164
|
+
// call site deleted without its key, so it must be printed and must not gate.
|
|
165
|
+
const root = repo();
|
|
166
|
+
bundle(root, 'en', { common: { save: 'Save', cancel: 'Cancel' } });
|
|
167
|
+
const src = path.join(root, 'src');
|
|
168
|
+
mkdirSync(src, { recursive: true });
|
|
169
|
+
writeFileSync(path.join(src, 'View.tsx'), "const label = t('common.save');\n");
|
|
170
|
+
const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
|
|
171
|
+
expect(out).toContain('not reached by any t() call site');
|
|
172
|
+
expect(out).toContain('common.cancel');
|
|
173
|
+
expect(code).toBe(0);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('does not call a key under a dynamic prefix unused, because it cannot be resolved statically', () => {
|
|
177
|
+
const root = repo();
|
|
178
|
+
bundle(root, 'en', { nav: { accounts: 'Accounts', teams: 'Teams' } });
|
|
179
|
+
const src = path.join(root, 'src');
|
|
180
|
+
mkdirSync(src, { recursive: true });
|
|
181
|
+
writeFileSync(path.join(src, 'Nav.tsx'), 'const label = t(`nav.${item}`);\n');
|
|
182
|
+
const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
|
|
183
|
+
expect(out).not.toContain('not reached by any t() call site');
|
|
184
|
+
expect(code).toBe(0);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
it('still fails a call site whose key the bundle lacks', () => {
|
|
188
|
+
// The mirror of the advisory case, and deliberately not softened: it renders
|
|
189
|
+
// the inline default for every user in every language.
|
|
190
|
+
const root = repo();
|
|
191
|
+
bundle(root, 'en', { common: { save: 'Save' } });
|
|
192
|
+
const src = path.join(root, 'src');
|
|
193
|
+
mkdirSync(src, { recursive: true });
|
|
194
|
+
writeFileSync(path.join(src, 'View.tsx'), "const label = t('common.saved');\n");
|
|
195
|
+
const { code } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
|
|
196
|
+
expect(code).toBe(1);
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
|
|
119
200
|
describe('validateLocalesCli --call-sites', () => {
|
|
120
201
|
it('passes a call site whose inline default equals the bundle', () => {
|
|
121
202
|
const root = repo();
|
|
@@ -50,6 +50,26 @@ One defect, kept as a locale plus a message so a caller can group them.
|
|
|
50
50
|
interface LocaleProblem {
|
|
51
51
|
locale: string;
|
|
52
52
|
problem: string;
|
|
53
|
+
/**
|
|
54
|
+
* Reported, but not a failure.
|
|
55
|
+
*
|
|
56
|
+
* The distinction is **"this build is wrong"** against **"this merge is still
|
|
57
|
+
* in flight"**, and a gate that cannot tell them apart gets switched off. A
|
|
58
|
+
* key the bundles carry that no call site reaches is the ordinary state of a
|
|
59
|
+
* bundle running ahead of its UI, and a translator adding a string for a screen
|
|
60
|
+
* that has not been wired is doing the right thing. It is also the only thing
|
|
61
|
+
* that catches a call site deleted or renamed without its key — which keeps a
|
|
62
|
+
* translator re-translating a string no user will ever see.
|
|
63
|
+
*
|
|
64
|
+
* So it is reported and it does not fail the run.
|
|
65
|
+
*
|
|
66
|
+
* The finding that is **not** advisory is the mirror: a `t()` key the bundle
|
|
67
|
+
* lacks. That one renders the inline default for every user in every language,
|
|
68
|
+
* it is actionable in the same commit, and there is no in-flight state in which
|
|
69
|
+
* it is the right answer — so it stays fatal, and the report below prints the
|
|
70
|
+
* two classes separately rather than counting them together.
|
|
71
|
+
*/
|
|
72
|
+
advisory?: boolean;
|
|
53
73
|
}
|
|
54
74
|
|
|
55
75
|
/**
|
|
@@ -452,47 +472,37 @@ function validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleSha
|
|
|
452
472
|
*/
|
|
453
473
|
function collectCallSites(scope: CallSiteScope, baseKeys: Set<string>, baseBundle: Map<string, unknown>): LocaleProblem[] {
|
|
454
474
|
const problems: LocaleProblem[] = [];
|
|
455
|
-
const
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
475
|
+
for (const full of sourceFiles(scope)) {
|
|
476
|
+
const source = readFileSync(full, 'utf8');
|
|
477
|
+
// `t('…')` / `t("…")` with a string literal first argument. The key is the
|
|
478
|
+
// single source of truth for what is rendered, so anything else is out of scope.
|
|
479
|
+
const pattern = /\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;
|
|
480
|
+
for (const match of source.matchAll(pattern)) {
|
|
481
|
+
const key = match[2];
|
|
482
|
+
if (key.includes('${') || key.includes('{{')) continue;
|
|
483
|
+
const where = path.relative(process.cwd(), full) || full;
|
|
484
|
+
if (!baseKeys.has(key)) {
|
|
485
|
+
problems.push({
|
|
486
|
+
locale: 'call-site',
|
|
487
|
+
problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,
|
|
488
|
+
});
|
|
461
489
|
continue;
|
|
462
490
|
}
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
//
|
|
466
|
-
|
|
467
|
-
const
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,
|
|
476
|
-
});
|
|
477
|
-
continue;
|
|
478
|
-
}
|
|
479
|
-
// A default that disagrees with the shipped bundle **fails**: one of the two
|
|
480
|
-
// is a bug, and the default is the one that renders verbatim the day the key
|
|
481
|
-
// goes missing — which is the fallback path the whole check is about.
|
|
482
|
-
if (!match[3]) continue;
|
|
483
|
-
const inline = readDefault(source, match.index + match[0].length);
|
|
484
|
-
if (inline === null) continue;
|
|
485
|
-
const bundled = baseBundle.get(key);
|
|
486
|
-
if (inline !== bundled) {
|
|
487
|
-
problems.push({
|
|
488
|
-
locale: 'call-site',
|
|
489
|
-
problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,
|
|
490
|
-
});
|
|
491
|
-
}
|
|
491
|
+
// A default that disagrees with the shipped bundle **fails**: one of the two
|
|
492
|
+
// is a bug, and the default is the one that renders verbatim the day the key
|
|
493
|
+
// goes missing — which is the fallback path the whole check is about.
|
|
494
|
+
if (!match[3]) continue;
|
|
495
|
+
const inline = readDefault(source, match.index + match[0].length);
|
|
496
|
+
if (inline === null) continue;
|
|
497
|
+
const bundled = baseBundle.get(key);
|
|
498
|
+
if (inline !== bundled) {
|
|
499
|
+
problems.push({
|
|
500
|
+
locale: 'call-site',
|
|
501
|
+
problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,
|
|
502
|
+
});
|
|
492
503
|
}
|
|
493
504
|
}
|
|
494
|
-
}
|
|
495
|
-
walk(scope.dir);
|
|
505
|
+
}
|
|
496
506
|
return problems;
|
|
497
507
|
}
|
|
498
508
|
|
|
@@ -551,37 +561,202 @@ function decodeStringLiteral(raw: string): string {
|
|
|
551
561
|
}
|
|
552
562
|
|
|
553
563
|
/**
|
|
554
|
-
|
|
564
|
+
* Every key a `t()` call site names literally, under one scope.
|
|
565
|
+
*
|
|
566
|
+
* Extracted from {@link collectCallSites} so the unused-key sweep and the
|
|
567
|
+
* unresolved-key check read the **same** set. Two scanners that each carry their
|
|
568
|
+
* own idea of what a call site looks like disagree on exactly the interesting
|
|
569
|
+
* case — a shape one understands and the other does not — and then report a key
|
|
570
|
+
* as both unused and used.
|
|
571
|
+
*/
|
|
572
|
+
function usedKeys(scope: CallSiteScope): Set<string> {
|
|
573
|
+
const used = new Set<string>();
|
|
574
|
+
for (const file of sourceFiles(scope)) {
|
|
575
|
+
// `t('…')` / `t("…")` with a string literal first argument. The key is the
|
|
576
|
+
// single source of truth for what is rendered, so anything else is out of scope.
|
|
577
|
+
for (const match of readFileSync(file, 'utf8').matchAll(/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1/g)) {
|
|
578
|
+
const key = match[2];
|
|
579
|
+
if (!key.includes('${') && !key.includes('{{')) used.add(key);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return used;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Every source file a scope covers, walking the skip list once.
|
|
587
|
+
*/
|
|
588
|
+
function sourceFiles(scope: CallSiteScope): string[] {
|
|
589
|
+
const files: string[] = [];
|
|
590
|
+
const walk = (dir: string): void => {
|
|
591
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
592
|
+
const full = path.join(dir, entry.name);
|
|
593
|
+
if (entry.isDirectory()) {
|
|
594
|
+
if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'coverage') continue;
|
|
595
|
+
walk(full);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
if (scope.extensions.some((extension) => entry.name.endsWith(extension))) files.push(full);
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
walk(scope.dir);
|
|
602
|
+
return files;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Base-bundle keys that no `t()` call site reaches.
|
|
607
|
+
*
|
|
608
|
+
* Advisory by construction, and for the reason {@link LocaleProblem.advisory}
|
|
609
|
+
* gives: a bundle routinely runs ahead of its UI, and a translator adding a
|
|
610
|
+
* string for a screen that has not been wired is doing the right thing. What it
|
|
611
|
+
* also catches is the case that matters — a renamed or deleted call site whose
|
|
612
|
+
* key was never removed, which keeps a translator re-translating a string no
|
|
613
|
+
* user will ever see.
|
|
614
|
+
*
|
|
615
|
+
* Dynamic keys are **not** reported as unused. `` t(`section.${name}`) `` cannot
|
|
616
|
+
* be resolved statically, so every key under that prefix would look dead; the
|
|
617
|
+
* honest answer is "unknown", and an `unknown` reported as `unused` is the kind
|
|
618
|
+
* of finding that makes a gate useless.
|
|
619
|
+
*/
|
|
620
|
+
function collectUnusedKeys(baseKeys: readonly string[], scope: CallSiteScope, used: Set<string>): LocaleProblem[] {
|
|
621
|
+
const prefixes = dynamicKeyPrefixes(scope);
|
|
622
|
+
const unused = baseKeys.filter(
|
|
623
|
+
(key) => !used.has(key) && [...prefixes].every((prefix) => !(key === prefix || key.startsWith(`${prefix}.`))),
|
|
624
|
+
);
|
|
625
|
+
if (unused.length === 0) return [];
|
|
626
|
+
return [
|
|
627
|
+
{
|
|
628
|
+
locale: 'call-site',
|
|
629
|
+
problem: `${unused.length} base key(s) are not reached by any t() call site: ${unused.slice(0, 20).join(', ')}${unused.length > 20 ? ', …' : ''}`,
|
|
630
|
+
advisory: true,
|
|
631
|
+
},
|
|
632
|
+
];
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* The longest literal prefix of every dynamically-built key.
|
|
637
|
+
*
|
|
638
|
+
* A prefix rather than a whole key, because only the static head of
|
|
639
|
+
* `` t(`nav.${item}`) `` is knowable, and the keys it may resolve to are exactly
|
|
640
|
+
* the ones a static scan must not claim are dead.
|
|
641
|
+
*/
|
|
642
|
+
function dynamicKeyPrefixes(scope: CallSiteScope): Set<string> {
|
|
643
|
+
const prefixes = new Set<string>();
|
|
644
|
+
for (const file of sourceFiles(scope)) {
|
|
645
|
+
for (const match of readFileSync(file, 'utf8').matchAll(/\bt\(\s*`([^`$]*)\$\{/g)) {
|
|
646
|
+
const head = match[1].replace(/\.$/, '');
|
|
647
|
+
if (head) prefixes.add(head);
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
return prefixes;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* The string tags a locale directory declares, parsed from a source file.
|
|
655
|
+
*
|
|
656
|
+
* A declared list and a directory of bundles are two independent facts about the
|
|
657
|
+
* same thing, and the only one that can be wrong *silently* is the declared list:
|
|
658
|
+
* a tag with no directory makes a runtime `import.meta.glob` lookup throw the
|
|
659
|
+
* moment that language is chosen, which is a support ticket and not a build
|
|
660
|
+
* failure. A directory with no declaration is a translation nobody can select.
|
|
661
|
+
*
|
|
662
|
+
* Parsed as text rather than imported, because the declaring file is a TypeScript
|
|
663
|
+
* module in the app being linted and importing it would run it.
|
|
664
|
+
*/
|
|
665
|
+
function declaredTags(file: string): string[] {
|
|
666
|
+
const source = readFileSync(file, 'utf8');
|
|
667
|
+
const match = /(?:export\s+)?const\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\s*=\s*\[([^\]]*)\]/.exec(source);
|
|
668
|
+
if (!match) throw new Error(`${file} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);
|
|
669
|
+
return [...(match[1] ?? '').matchAll(/['"]([^'"]+)['"]/g)].map((tag) => tag[1]);
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* Cross-check a declared tag list against the bundle directories, both ways.
|
|
674
|
+
*
|
|
675
|
+
* Both directions are findings because both are wrong states: declared-but-absent
|
|
676
|
+
* is a runtime throw on selection, present-but-undeclared is a bundle no
|
|
677
|
+
* selector offers.
|
|
678
|
+
*/
|
|
679
|
+
function checkDeclaredTags(localesDir: string, declaredFile: string, onDisk: readonly string[]): LocaleProblem[] {
|
|
680
|
+
const declared = declaredTags(declaredFile);
|
|
681
|
+
const problems: LocaleProblem[] = [];
|
|
682
|
+
for (const tag of declared) {
|
|
683
|
+
if (!onDisk.includes(tag)) {
|
|
684
|
+
problems.push({
|
|
685
|
+
locale: 'tags',
|
|
686
|
+
problem: `${declaredFile} declares '${tag}' but ${localesDir}/${tag} does not exist — selecting that language throws`,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
for (const tag of onDisk) {
|
|
691
|
+
if (!declared.includes(tag)) {
|
|
692
|
+
problems.push({
|
|
693
|
+
locale: 'tags',
|
|
694
|
+
problem: `${localesDir}/${tag} exists but ${declaredFile} does not declare it — the selector cannot offer it`,
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return problems;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
CLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?, '--tags=<file>'?])`.
|
|
555
703
|
|
|
556
704
|
`--call-sites=<dir>` opts into the application-side checks: every `t('key')` under
|
|
557
705
|
`<dir>` must resolve against the base bundle, and any inline default must equal the
|
|
558
706
|
bundled value. Without the flag the script stays bundle-to-bundle, because that is
|
|
559
707
|
the only part it can answer for a repo whose bundles are consumed by something
|
|
560
708
|
other than `t()` — a backend string table, for instance.
|
|
709
|
+
|
|
710
|
+
`--tags=<file>` cross-checks a declared `SUPPORTED_LANGUAGES` / `SUPPORTED_LOCALES`
|
|
711
|
+
array against the bundle directories, in both directions. It is separate from
|
|
712
|
+
`--call-sites` because a repo can declare its tags in a file the scan never walks,
|
|
713
|
+
and a directory of bundles with no declaration is exactly the state a
|
|
714
|
+
bundle-to-bundle check reports as perfectly healthy.
|
|
561
715
|
*/
|
|
562
716
|
function validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): number {
|
|
563
717
|
const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'apps/web/src/locales';
|
|
564
718
|
const shape = (argv.find((arg) => arg.startsWith('--shape='))?.slice('--shape='.length) ?? 'auto') as LocaleShape;
|
|
565
719
|
const base = argv.find((arg) => arg.startsWith('--base='))?.slice('--base='.length) ?? 'en';
|
|
566
720
|
const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);
|
|
721
|
+
const tagsFile = argv.find((arg) => arg.startsWith('--tags='))?.slice('--tags='.length);
|
|
567
722
|
|
|
568
723
|
const report = validateLocales(dir, base, shape);
|
|
569
724
|
const problems = [...report.problems];
|
|
570
725
|
|
|
726
|
+
if (tagsFile !== undefined && existsSync(tagsFile)) {
|
|
727
|
+
try {
|
|
728
|
+
problems.push(...checkDeclaredTags(dir, tagsFile, tagsOnDisk(dir, shape)));
|
|
729
|
+
} catch (error: unknown) {
|
|
730
|
+
problems.push({ locale: 'tags', problem: `${tagsFile}: ${error instanceof Error ? error.message : String(error)}` });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
571
734
|
if (callSiteDir !== undefined && existsSync(callSiteDir)) {
|
|
572
735
|
try {
|
|
573
736
|
const baseBundle = bundleAt(dir, base, shape);
|
|
574
|
-
|
|
737
|
+
const scope = { dir: callSiteDir, extensions: ['.ts', '.tsx'] };
|
|
738
|
+
const used = usedKeys(scope);
|
|
739
|
+
problems.push(
|
|
740
|
+
...collectCallSites(scope, new Set(baseBundle.keys()), baseBundle),
|
|
741
|
+
...collectUnusedKeys([...baseBundle.keys()], scope, used),
|
|
742
|
+
);
|
|
575
743
|
} catch (error: unknown) {
|
|
576
744
|
problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });
|
|
577
745
|
}
|
|
578
746
|
}
|
|
579
747
|
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
748
|
+
const failures = problems.filter((problem) => problem.advisory !== true);
|
|
749
|
+
const advisories = problems.filter((problem) => problem.advisory === true);
|
|
750
|
+
|
|
751
|
+
if (failures.length > 0) {
|
|
752
|
+
console.error(`Locale validation failed for ${dir} (${failures.length} problem(s)):`);
|
|
753
|
+
for (const problem of failures) console.error(` - ${problem.locale}: ${problem.problem}`);
|
|
583
754
|
return 1;
|
|
584
755
|
}
|
|
756
|
+
if (advisories.length > 0) {
|
|
757
|
+
console.warn(`Locale validation passed for ${dir} with ${advisories.length} advisory finding(s):`);
|
|
758
|
+
for (const problem of advisories) console.warn(` - ${problem.locale}: ${problem.problem}`);
|
|
759
|
+
}
|
|
585
760
|
console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);
|
|
586
761
|
return 0;
|
|
587
762
|
}
|