@rexezuge/tooling 1.13.0 → 1.14.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/README.md +25 -4
- package/dist/eslint-options.d.ts +54 -0
- package/dist/eslint-options.d.ts.map +1 -0
- package/dist/eslint-options.js +0 -0
- package/dist/eslint-options.js.map +7 -0
- package/dist/eslint.d.ts +2 -53
- package/dist/eslint.d.ts.map +1 -1
- package/dist/eslint.js.map +2 -2
- package/dist/pages-proxy.d.ts +2 -0
- package/dist/pages-proxy.d.ts.map +1 -0
- package/dist/pages-proxy.js +1 -0
- package/dist/pages-proxy.js.map +7 -0
- package/dist/plugin-option.d.ts +15 -0
- package/dist/plugin-option.d.ts.map +1 -0
- package/dist/plugin-option.js +1 -0
- package/dist/plugin-option.js.map +7 -0
- package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
- package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
- package/dist/scripts/ensure-spa-shell-stub.js +1 -2
- package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
- package/dist/scripts/init-secrets.d.ts +1 -2
- package/dist/scripts/init-secrets.d.ts.map +1 -1
- package/dist/scripts/init-secrets.js +2 -3
- package/dist/scripts/init-secrets.js.map +3 -3
- package/dist/scripts/migrations-lock.d.ts +6 -2
- package/dist/scripts/migrations-lock.d.ts.map +1 -1
- package/dist/scripts/migrations-lock.js +1 -2
- package/dist/scripts/migrations-lock.js.map +3 -3
- package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
- package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
- package/dist/scripts/prepare-wrangler-config.js +1 -2
- package/dist/scripts/prepare-wrangler-config.js.map +3 -3
- package/dist/scripts/validate-locales.d.ts +20 -2
- 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/dist/scripts/verify-spa-shell.d.ts +7 -2
- package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
- package/dist/scripts/verify-spa-shell.js +1 -2
- package/dist/scripts/verify-spa-shell.js.map +3 -3
- package/dist/vite.d.ts +2 -1
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +3 -3
- package/dist/vite.js.map +3 -3
- package/dist/vitest-integration.d.ts +3 -2
- package/dist/vitest-integration.d.ts.map +1 -1
- package/dist/vitest-integration.js +1 -1
- package/dist/vitest-integration.js.map +3 -3
- package/dist/vitest-repo.d.ts +3 -2
- package/dist/vitest-repo.d.ts.map +1 -1
- package/dist/vitest-repo.js +1 -1
- package/dist/vitest-repo.js.map +3 -3
- package/dist/vitest-web.d.ts +3 -2
- package/dist/vitest-web.d.ts.map +1 -1
- package/dist/vitest-web.js +1 -1
- package/dist/vitest-web.js.map +3 -3
- package/dist/vitest.d.ts +3 -2
- package/dist/vitest.d.ts.map +1 -1
- package/dist/vitest.js +1 -1
- package/dist/vitest.js.map +3 -3
- package/package.json +3 -3
- package/src/eslint-options.ts +54 -0
- package/src/eslint.ts +2 -53
- package/src/pages-proxy.test.ts +8 -0
- package/src/pages-proxy.ts +13 -0
- package/src/plugin-option.test.ts +13 -0
- package/src/plugin-option.ts +18 -0
- package/src/scripts/ensure-spa-shell-stub.ts +18 -10
- package/src/scripts/entrypoints.test.ts +55 -0
- package/src/scripts/init-secrets.ts +8 -6
- package/src/scripts/migrations-lock.ts +22 -17
- package/src/scripts/prepare-wrangler-config.ts +26 -14
- package/src/scripts/validate-locales.ts +39 -17
- package/src/scripts/verify-spa-shell.ts +21 -20
- package/src/vite.ts +5 -3
- package/src/vitest-integration.ts +5 -3
- package/src/vitest-repo.ts +5 -3
- package/src/vitest-web.ts +5 -3
- package/src/vitest.ts +5 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/prepare-wrangler-config.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "created"]
|
|
4
|
+
"sourcesContent": ["/**\n * Materialize `wrangler.jsonc` and provision what it refers to.\n *\n * Provenance: Durable-DAV's `scripts/prepare-wrangler-config.ts` and Edge-Sonic's\n * `scripts/deploy/prepare-wrangler-config.ts`, converged. The five ordered calls\n * live in `wrangler-config/`: read or copy the config, refuse one older than the\n * template requires, apply the caller's patches, then create whatever resources it\n * names and write their real ids over the placeholders. This file is only the\n * order; it has nothing else to do.\n *\n * Run by the deploy job before `wrangler deploy`, and by the backup workflow\n * before `wrangler d1 export` — so the database a backup covers is resolved from\n * the same config the deploy targets, with no second `D1_DATABASE_ID` secret to\n * keep in sync.\n *\n * The one thing it does beyond calling is publish what\n * `provisionWranglerResources` created, which the backup workflow reads to refuse\n * exporting a database that did not exist until this run.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/prepare-wrangler-config.ts\n * ```\n *\n * Environment:\n *\n * - `WRANGLER_JSONC` — the whole config, as a repository variable. When set it is\n * written verbatim instead of copying the template.\n * - `WRANGLER_PATCH_JSON` — top-level keys merged into the config.\n * - `WRANGLER_VARS_PATCH_JSON` — `vars` entries merged into the config.\n */\nimport { setOutput } from './lib/github-actions.ts';\nimport { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';\nimport { provisionWranglerResources } from './wrangler-config/resources.ts';\nimport { isEntrypoint } from './lib/entrypoint.ts';\n\n/**\n * Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths\n * resolve when `wrangler-config/types.ts` is first imported, so a caller changing\n * directory must do so before importing this module). Returns the created resources.\n */\nexport function main(): string[] {\n prepareConfigFile();\n ensureMinimumConfigVersion();\n applyTopLevelPatch();\n applyVarsPatch();\n const created = provisionWranglerResources();\n\n // Published as a step output rather than only printed. The backup workflow needs\n // to know whether the D1 database *existed* or was created moments ago: a fresh one\n // holds no user data, and uploading that empty dump every night is a false sense\n // of safety. The alternative — re-reading the placeholder id out of\n // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches\n // the placeholder away before the reader ever runs.\n setOutput('created', created.join(','));\n console.log('Wrangler configuration is ready.');\n return created;\n}\n\nif (isEntrypoint(import.meta.url)) {\n main();\n}\n"],
|
|
5
|
+
"mappings": "+EAgCA,OAAS,aAAAA,MAAiB,0BAC1B,OAAS,sBAAAC,EAAoB,kBAAAC,EAAgB,8BAAAC,EAA4B,qBAAAC,MAAyB,+BAClG,OAAS,8BAAAC,MAAkC,iCAC3C,OAAS,gBAAAC,MAAoB,sBAOvB,SAAUC,GAAI,CAClBH,EAAiB,EACjBD,EAA0B,EAC1BF,EAAkB,EAClBC,EAAc,EACd,MAAMM,EAAUH,EAA0B,EAQ1C,OAAAL,EAAU,UAAWQ,EAAQ,KAAK,GAAG,CAAC,EACtC,QAAQ,IAAI,kCAAkC,EACvCA,CACT,CAhBgBC,EAAAF,EAAA,QAkBZD,EAAa,YAAY,GAAG,GAC9BC,EAAI",
|
|
6
|
+
"names": ["setOutput", "applyTopLevelPatch", "applyVarsPatch", "ensureMinimumConfigVersion", "prepareConfigFile", "provisionWranglerResources", "isEntrypoint", "main", "created", "__name"]
|
|
7
7
|
}
|
|
@@ -61,6 +61,24 @@ and a directory of bundles with no declaration is exactly the state a
|
|
|
61
61
|
bundle-to-bundle check reports as perfectly healthy.
|
|
62
62
|
*/
|
|
63
63
|
declare function validateLocalesCli(argv?: readonly string[]): number;
|
|
64
|
-
|
|
65
|
-
|
|
64
|
+
/**
|
|
65
|
+
What `collectLocaleProblems` checks: the bundles, and optionally the declared tags and the `t()` call sites.
|
|
66
|
+
*/
|
|
67
|
+
interface LocaleCheckOptions {
|
|
68
|
+
dir: string;
|
|
69
|
+
base?: string;
|
|
70
|
+
shape?: LocaleShape;
|
|
71
|
+
callSiteDir?: string;
|
|
72
|
+
tagsFile?: string;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Every finding for one locales directory, as data. The CLI prints it and `rexezuge locales validate --json` serializes it;
|
|
76
|
+
* advisories carry `advisory: true`, everything else is a failure.
|
|
77
|
+
*/
|
|
78
|
+
declare function collectLocaleProblems(options: LocaleCheckOptions): {
|
|
79
|
+
report: LocaleReport;
|
|
80
|
+
problems: LocaleProblem[];
|
|
81
|
+
};
|
|
82
|
+
export { collectLocaleProblems, parseObjectLiteral, validateLocales, validateLocalesCli };
|
|
83
|
+
export type { LocaleCheckOptions, LocaleProblem, LocaleReport, LocaleShape };
|
|
66
84
|
//# sourceMappingURL=validate-locales.d.ts.map
|
|
@@ -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;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,
|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CAAC;AAC1F,YAAY,EAAE,kBAAkB,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var v=Object.defineProperty;var
|
|
2
|
-
`&&(o=!1);continue}const
|
|
3
|
-
`&&(
|
|
4
|
-
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}
|
|
5
|
-
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}
|
|
1
|
+
var v=Object.defineProperty;var u=(e,t)=>v(e,"name",{value:t,configurable:!0});import{isEntrypoint as _}from"./lib/entrypoint.js";import{existsSync as $,readdirSync as w,readFileSync as g}from"node:fs";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}u(y,"flatten");function x(e){return typeof e!="string"?[]:[...new Set(e.match(/\{\{[^{}]+\}\}/g))].sort((t,o)=>t.localeCompare(o))}u(x,"placeholdersOf");function A(e){const t=g(e,"utf8");return e.endsWith(".ts")?O(t,e):JSON.parse(t)}u(A,"readBundle");function F(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 l=e[s+1];if(n){r==="*"&&l==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&l==="-"){o=!0;continue}if(r==="/"&&l==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&l!=="="&&l!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const i=e.indexOf("{",s);return i===-1?-1:i}}return-1}u(F,"objectLiteralStart");function O(e,t){const o=F(e);if(o===-1)throw new Error(`${t} has no object literal`);let n=0,s=-1,r="",l=!1,a=!1;for(let p=o;p<e.length;p+=1){const f=e[p];if(l){f===`
|
|
3
|
+
`&&(l=!1);continue}const m=e[p+1];if(a){f==="*"&&m==="/"&&(a=!1,p+=1);continue}if(r!==""){if(f==="\\"){p+=1;continue}f===r&&(r="");continue}if(f==="-"&&m==="-"){l=!0;continue}if(f==="/"&&m==="*"){a=!0;continue}if(f==="'"||f==='"'||f==="`"){r=f;continue}if(f==="{")n+=1;else if(f==="}"&&(n-=1,n===0)){s=p;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const h=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(p,f)=>JSON.stringify(J(f))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(h)}catch(p){throw new Error(`${t} object literal could not be parsed: ${p instanceof Error?p.message:String(p)}`)}}u(O,"parseObjectLiteral");function J(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
|
|
4
|
+
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}u(J,"unescapeLiteral");const j={file:"json",module:"ts"};function S(e){return e==="auto"?["dir","file","module"]:[e]}u(S,"layouts");function C(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}u(C,"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))}u(k,"bundleFor");function U(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))}u(U,"bundleAt");function N(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(i){return n.push({locale:t,problem:`${s}: ${i instanceof Error?i.message:String(i)}`}),{locales:[],keys:0,problems:n}}const l=new Set(r.keys());if(l.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([...C(e,o),t])].sort((i,d)=>i.localeCompare(d));for(const i of a){const d=k(e,i,o);if(d===void 0){n.push({locale:i,problem:"no bundle found"});continue}let c;try{c=y(A(d))}catch(h){n.push({locale:i,problem:`${d}: ${h instanceof Error?h.message:String(h)}`});continue}for(const h of l)c.has(h)||n.push({locale:i,problem:`missing key: ${h}`});for(const[h,p]of c){if(!l.has(h)){n.push({locale:i,problem:`extra key not in ${t}: ${h}`});continue}if(typeof p!="string"||p===""){n.push({locale:i,problem:`empty value: ${h} \u2014 indistinguishable from a missing key at runtime`});continue}const f=x(r.get(h));if(f.length===0)continue;const m=x(p);(f.length!==m.length||f.some((L,W)=>L!==m[W]))&&n.push({locale:i,problem:`placeholder mismatch at ${h}: ${i} has ${JSON.stringify(m)}, ${t} has ${JSON.stringify(f)}`})}}return{locales:a,keys:l.size,problems:n}}u(N,"validateLocales");function K(e,t,o){const n=[];for(const s of E(e)){const r=g(s,"utf8"),l=/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;for(const a of r.matchAll(l)){const i=a[2];if(i.includes("${")||i.includes("{{"))continue;const d=b.relative(process.cwd(),s)||s;if(!t.has(i)){n.push({locale:"call-site",problem:`${d}: t('${i}') is not in the bundle \u2014 it renders as the inline default and is untranslatable`});continue}if(!a[3])continue;const c=q(r,a.index+a[0].length);if(c===null)continue;const h=o.get(i);c!==h&&n.push({locale:"call-site",problem:`${d}: t('${i}', \u2026) default disagrees with the bundle \u2014 bundle=${JSON.stringify(h)} default=${JSON.stringify(c)}`})}}return n}u(K,"collectCallSites");function q(e,t){const o=e.slice(t).replace(/^\s+/,""),n=o[0];if(n!=="'"&&n!=='"')return null;const s=o.slice(1),l=(n==="'"?/^(?:[^'\\]|\\.)*'/:/^(?:[^"\\]|\\.)*"/).exec(s);return l?B(s.slice(0,l[0].length-1)):null}u(q,"readDefault");function B(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}})}u(B,"decodeStringLiteral");function G(e){const t=new Set;for(const o of E(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}u(G,"usedKeys");function E(e){const t=[],o=u(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(l=>s.name.endsWith(l))&&t.push(r)}},"walk");return o(e.dir),t}u(E,"sourceFiles");function R(e,t,o){const n=D(t),s=e.filter(r=>!o.has(r)&&[...n].every(l=>!(r===l||r.startsWith(`${l}.`))));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}]}u(R,"collectUnusedKeys");function D(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*`([^`$]*)\$\{/g)){const s=n[1].replace(/\.$/,"");s&&t.add(s)}return t}u(D,"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])}u(z,"declaredTags");function Q(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}u(Q,"checkDeclaredTags");function T(e=process.argv.slice(2)){const t=e.find(c=>!c.startsWith("--"))??"apps/web/src/locales",o=e.find(c=>c.startsWith("--shape="))?.slice(8)??"auto",n=e.find(c=>c.startsWith("--base="))?.slice(7)??"en",s=e.find(c=>c.startsWith("--call-sites="))?.slice(13),r=e.find(c=>c.startsWith("--tags="))?.slice(7),{report:l,problems:a}=P({dir:t,base:n,shape:o,callSiteDir:s,tagsFile:r}),i=a.filter(c=>c.advisory!==!0),d=a.filter(c=>c.advisory===!0);if(i.length>0){console.error(`Locale validation failed for ${t} (${i.length} problem(s)):`);for(const c of i)console.error(` - ${c.locale}: ${c.problem}`);return 1}if(d.length>0){console.warn(`Locale validation passed for ${t} with ${d.length} advisory finding(s):`);for(const c of d)console.warn(` - ${c.locale}: ${c.problem}`)}return console.log(`Locale validation passed (${l.locales.length} locales, ${l.keys} keys each, shape ${o}).`),0}u(T,"validateLocalesCli");function P(e){const{dir:t,callSiteDir:o,tagsFile:n}=e,s=e.base??"en",r=e.shape??"auto",l=N(t,s,r),a=[...l.problems];if(n!==void 0&&$(n))try{a.push(...Q(t,n,C(t,r)))}catch(i){a.push({locale:"tags",problem:`${n}: ${i instanceof Error?i.message:String(i)}`})}if(o!==void 0&&$(o))try{const i=U(t,s,r),d={dir:o,extensions:[".ts",".tsx"]},c=G(d);a.push(...K(d,new Set(i.keys()),i),...R([...i.keys()],d,c))}catch(i){a.push({locale:"call-site",problem:`${o}: ${i instanceof Error?i.message:String(i)}`})}return{report:l,problems:a}}u(P,"collectLocaleProblems");_(import.meta.url)&&process.exit(T(process.argv.slice(2)));export{P as collectLocaleProblems,O as parseObjectLiteral,N as validateLocales,T as validateLocalesCli};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/validate-locales.ts"],
|
|
4
|
-
"sourcesContent": ["import { isEntrypoint } from './lib/entrypoint.ts';\n/**\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 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 (isEntrypoint(import.meta.url)) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
-
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,sBAsC7B,OAAS,cAAAC,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,OAAOC,MAAU,YA+CjB,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,EAAS,GAAGA,CAAM,IAAIG,CAAG,GAAKA,EAAKF,CAAG,EAEvD,OAAOA,CACT,CAdSI,EAAAP,EAAA,WAwBT,SAASQ,EAAeP,EAAc,CACpC,OAAI,OAAOA,GAAU,SAAiB,CAAA,EAC/B,CAAC,GAAG,IAAI,IAAIA,EAAM,MAAM,iBAAiB,CAAC,CAAC,EAAE,KAAK,CAACQ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,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,sBA0DLhG,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKgG,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
-
"names": ["isEntrypoint", "existsSync", "readdirSync", "readFileSync", "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"]
|
|
4
|
+
"sourcesContent": ["import { isEntrypoint } from './lib/entrypoint.ts';\n/**\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 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, problems } = collectLocaleProblems({ dir, base, shape, callSiteDir, tagsFile });\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\n/**\nWhat `collectLocaleProblems` checks: the bundles, and optionally the declared tags and the `t()` call sites.\n*/\ninterface LocaleCheckOptions {\n dir: string;\n base?: string;\n shape?: LocaleShape;\n callSiteDir?: string;\n tagsFile?: string;\n}\n\n/**\n * Every finding for one locales directory, as data. The CLI prints it and `rexezuge locales validate --json` serializes it;\n * advisories carry `advisory: true`, everything else is a failure.\n */\nfunction collectLocaleProblems(options: LocaleCheckOptions): { report: LocaleReport; problems: LocaleProblem[] } {\n const { dir, callSiteDir, tagsFile } = options;\n const base = options.base ?? 'en';\n const shape = options.shape ?? 'auto';\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 return { report, problems };\n}\n\nexport { collectLocaleProblems, parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleCheckOptions, 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 (isEntrypoint(import.meta.url)) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,sBAsC7B,OAAS,cAAAC,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,OAAOC,MAAU,YA+CjB,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,EAAS,GAAGA,CAAM,IAAIG,CAAG,GAAKA,EAAKF,CAAG,EAEvD,OAAOA,CACT,CAdSI,EAAAP,EAAA,WAwBT,SAASQ,EAAeP,EAAc,CACpC,OAAI,OAAOA,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AAK7C,CAAK,CAAC,CAAC,CAC3E,OAASH,EAAgB,CACvBkB,EAAS,KAAK,CAAE,OAAQ,OAAQ,QAAS,GAAG+C,CAAQ,KAAKjE,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EAAE,CAAE,CACrH,CAGF,GAAIgE,IAAgB,QAAanG,EAAWmG,CAAW,EACrD,GAAI,CACF,MAAM5C,EAAaL,EAASiC,EAAKe,EAAM5D,CAAK,EACtC2B,EAAQ,CAAE,IAAKkC,EAAa,WAAY,CAAC,MAAO,MAAM,CAAC,EACvDnB,EAAOD,EAASd,CAAK,EAC3BZ,EAAS,KACP,GAAGW,EAAiBC,EAAO,IAAI,IAAIV,EAAW,KAAI,CAAE,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,CAEF,MAAO,CAAE,OAAAkE,EAAQ,SAAAhD,CAAQ,CAC3B,CA7BS1C,EAAA2F,EAAA,yBAyCLvG,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKgG,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
+
"names": ["isEntrypoint", "existsSync", "readdirSync", "readFileSync", "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", "collectLocaleProblems", "failures", "problem", "advisories", "options"]
|
|
7
7
|
}
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Verify the shell. `args[0]` is the repo root, derived from this file when absent
|
|
3
|
+
* rather than from `process.cwd()`: the gate reads the same tree whatever directory
|
|
4
|
+
* it is invoked from, which is the difference between a gate and a gate that passes
|
|
5
|
+
* because nobody ran it from the right place. Returns the exit code.
|
|
6
|
+
*/
|
|
7
|
+
export declare function main(args?: readonly string[]): number;
|
|
3
8
|
//# sourceMappingURL=verify-spa-shell.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verify-spa-shell.d.ts","sourceRoot":"","sources":["../../src/scripts/verify-spa-shell.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"verify-spa-shell.d.ts","sourceRoot":"","sources":["../../src/scripts/verify-spa-shell.ts"],"names":[],"mappings":"AAmCA;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CAa5E"}
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import e from"node:path";import{fileURLToPath as l}from"node:url";import{verifySpaShell as t}from"./spa-shell.js";const p=e.resolve(e.dirname(l(import.meta.url)),".."),o=process.argv[2]===void 0?p:e.resolve(process.argv[2]),{problems:r}=t({root:o});if(r.length>0){console.error("SPA shell check failed:");for(const s of r)console.error(` - ${s}`);process.exit(1)}console.log(`SPA shell check passed (${e.join(o,"apps/api/src/generated/spa-shell.ts")} matches ${e.join(o,"apps/web/dist")}).`);
|
|
1
|
+
var p=Object.defineProperty;var i=(e,r)=>p(e,"name",{value:r,configurable:!0});import o from"node:path";import{fileURLToPath as n}from"node:url";import{isEntrypoint as c}from"./lib/entrypoint.js";import{verifySpaShell as m}from"./spa-shell.js";function a(e=process.argv.slice(2)){const r=o.resolve(o.dirname(n(import.meta.url)),".."),t=e[0]===void 0?r:o.resolve(e[0]),{problems:s}=m({root:t});if(s.length>0){console.error("SPA shell check failed:");for(const l of s)console.error(` - ${l}`);return 1}return console.log(`SPA shell check passed (${o.join(t,"apps/api/src/generated/spa-shell.ts")} matches ${o.join(t,"apps/web/dist")}).`),0}i(a,"main"),c(import.meta.url)&&process.exit(a());export{a as main};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/verify-spa-shell.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": ["path", "fileURLToPath", "verifySpaShell", "
|
|
4
|
+
"sourcesContent": ["/**\n * Fail when the SPA shell the API worker serves is missing or self-inconsistent.\n *\n * Provenance: Durable-DAV's and Durable-DAV-Router's `scripts/verify-spa-shell.mjs`\n * and Edge-Sonic's typed `scripts/build/verify-spa-shell.ts`. The rules — which of\n * the ways a shell can be wrong to look for — live in `spa-shell.ts`, so they are\n * unit tested without a build on disk; this file is the entrypoint that turns the\n * verdict into an exit code.\n *\n * What it catches:\n *\n * - the `postinstall` stub, or no build at all, still in place;\n * - `spa-shell.ts` referencing `/assets/...` bundles that were not emitted (a\n * partially cleaned or half-copied `dist/`, which serves a shell whose JS 404s\n * and therefore renders no operator UI at all);\n * - `spa-shell.ts` and `apps/web/dist/index.html` disagreeing, i.e. only one of\n * the two halves of the build was refreshed.\n *\n * **The build is a precondition of this check, not a convenience.** Both paths are\n * gitignored and `postinstall` writes a deliberately empty stub, so verifying\n * without building cannot pass — and it fails with precisely the message above,\n * which is the check working rather than the check being wrong.\n *\n * Usage, from the repo root:\n *\n * ```bash\n * pnpm exec tsx scripts/verify-spa-shell.ts # defaults to ./ as root\n * pnpm exec tsx scripts/verify-spa-shell.ts --root /path/to/repo\n * ```\n */\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { verifySpaShell } from './spa-shell.ts';\n\n/**\n * Verify the shell. `args[0]` is the repo root, derived from this file when absent\n * rather than from `process.cwd()`: the gate reads the same tree whatever directory\n * it is invoked from, which is the difference between a gate and a gate that passes\n * because nobody ran it from the right place. Returns the exit code.\n */\nexport function main(args: readonly string[] = process.argv.slice(2)): number {\n const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');\n const root = args[0] === undefined ? repositoryRoot : path.resolve(args[0]);\n const { problems } = verifySpaShell({ root });\n if (problems.length > 0) {\n console.error('SPA shell check failed:');\n for (const problem of problems) console.error(` - ${problem}`);\n return 1;\n }\n console.log(\n `SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`,\n );\n return 0;\n}\n\nif (isEntrypoint(import.meta.url)) {\n process.exit(main());\n}\n"],
|
|
5
|
+
"mappings": "+EA8BA,OAAOA,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,kBAAAC,MAAsB,iBAQzB,SAAUC,EAAKC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CAClE,MAAMC,EAAiBN,EAAK,QAAQA,EAAK,QAAQC,EAAc,YAAY,GAAG,CAAC,EAAG,IAAI,EAChFM,EAAOF,EAAK,CAAC,IAAM,OAAYC,EAAiBN,EAAK,QAAQK,EAAK,CAAC,CAAC,EACpE,CAAE,SAAAG,CAAQ,EAAKL,EAAe,CAAE,KAAAI,CAAI,CAAE,EAC5C,GAAIC,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,yBAAyB,EACvC,UAAWC,KAAWD,EAAU,QAAQ,MAAM,OAAOC,CAAO,EAAE,EAC9D,MAAO,EACT,CACA,eAAQ,IACN,2BAA2BT,EAAK,KAAKO,EAAM,qCAAqC,CAAC,YAAYP,EAAK,KAAKO,EAAM,eAAe,CAAC,IAAI,EAE5H,CACT,CAbgBG,EAAAN,EAAA,QAeZF,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAKE,EAAI,CAAE",
|
|
6
|
+
"names": ["path", "fileURLToPath", "isEntrypoint", "verifySpaShell", "main", "args", "repositoryRoot", "root", "problems", "problem", "__name"]
|
|
7
7
|
}
|
package/dist/vite.d.ts
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
* README.
|
|
30
30
|
*/
|
|
31
31
|
import { type Plugin, type ViteUserConfig } from 'vitest/config';
|
|
32
|
+
import type { PluginOption } from './plugin-option.ts';
|
|
32
33
|
/**
|
|
33
34
|
* One dev-server proxy entry, as Vite's `server.proxy` accepts it.
|
|
34
35
|
*/
|
|
@@ -99,7 +100,7 @@ export interface WebViteConfigOptions {
|
|
|
99
100
|
* needs. Applied before the spa-shell plugin so the shell is written after the
|
|
100
101
|
* bundle exists.
|
|
101
102
|
*/
|
|
102
|
-
readonly plugins?: readonly
|
|
103
|
+
readonly plugins?: readonly PluginOption[];
|
|
103
104
|
/**
|
|
104
105
|
* Dev-server proxy entries. Keyed by path prefix.
|
|
105
106
|
*/
|
package/dist/vite.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,EAAgB,KAAK,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/E;;GA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ty;var t=(n,e)=>l(n,"name",{value:e,configurable:!0});import{existsSync as f,mkdirSync as p,readFileSync as c,writeFileSync as h}from"node:fs";import m from"node:path";import{fileURLToPath as i,pathToFileURL as x}from"node:url";import{defineConfig as a}from"vitest/config";import{asVitePlugins as y}from"./plugin-option.js";function s(n){return n instanceof URL?n:n.startsWith("file:")?new URL(n):x(n)}t(s,"toUrl");function U(n){const e=s(n);return e.href.endsWith("/")?e:new URL(`${e.href}/`)}t(U,"toDirUrl");function L(n){return{name:"spa-shell-embed",closeBundle(){const e=U(n.root??process.cwd()),r=i(new URL(n.path,e)),o=n.distIndex===void 0?i(new URL("dist/index.html",e)):i(typeof n.distIndex=="string"&&!/^[a-z][a-z\d+\-.]*:/i.test(n.distIndex)?new URL(n.distIndex,e):s(n.distIndex));if(!f(o)){console.warn("spa-shell-embed: dist/index.html not found, skipping");return}const d=c(o,"utf8"),u=`// Auto-generated by Vite build plugin - DO NOT EDIT.
|
|
2
|
+
export const SPA_HTML: string = ${JSON.stringify(d)};
|
|
3
|
+
`;p(m.dirname(r),{recursive:!0}),h(r,u)}}}t(L,"spaShellEmbedPlugin");function I(n={}){const e=[...n.plugins??[]];return n.spaShell!==void 0&&e.push(L(n.spaShell)),a({...e.length>0&&{plugins:y(e)},...n.proxy!==void 0&&{server:{proxy:{...n.proxy}}},build:{outDir:n.outDir??"dist",emptyOutDir:!0}})}t(I,"defineWebViteConfig");export{I as defineWebViteConfig,L as spaShellEmbedPlugin};
|
package/dist/vite.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/vite.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The SPA's Vite config.\n *\n * Provenance: converged from the `apps/web/vite.config.ts` of the eight repos\n * that build a Vite SPA. They are one file with three variables: the plugin list\n * (`@vitejs/plugin-react` + `@tailwindcss/vite`), the dev-server proxy target,\n * and the `spa-shell-embed` plugin that copies `dist/index.html` into\n * `apps/api/src/generated/spa-shell.ts`.\n *\n * Canonical decisions:\n *\n * 1. **The plugins are passed in, not imported.** The kit stays zero-dependency:\n * `react`, `@vitejs/plugin-react` and `@tailwindcss/vite` belong to the app\n * that uses them, and importing them here would make the tooling package\n * undownloadable for a consumer without a React SPA.\n * 2. **The `spa-shell-embed` hook stays per-repo, and is passed in.** It is the\n * one genuinely repo-specific piece: each repo names its own worker and its\n * own generated-module path. What the kit provides is the *contract* — see\n * `spaShellEmbedPlugin`, which is the converged body of all eight copies.\n * 3. **`server.proxy` is data, not code.** The paths differ per repo\n * (`/user` + `/rest` in Edge-Sonic, `/api` in CalDAV-Bridge, `/tracker` in\n * ChordDHT-Tracker) but the shape never does, so it is an option with a\n * default.\n * 4. **`build.emptyOutDir: true`** is the default, because a stale asset in\n * `dist/` is served as a live bundle — the same half-refreshed build\n * `scripts/verify-spa-shell.ts` rejects.\n *\n * The consumer's `apps/web/vite.config.ts` becomes a handful of lines — see the\n * README.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';\n\n/**\n * One dev-server proxy entry, as Vite's `server.proxy` accepts it.\n */\nexport interface ProxyEntry {\n readonly target: string;\n readonly changeOrigin?: boolean;\n readonly bypass?: (request: { headers: Record<string, string | string[] | undefined> }) => string | undefined;\n /**\n * Proxy WebSocket upgrades on this path.\n *\n * Vite's `server.proxy` needs `ws: true` for an entry that carries a\n * WebSocket, and the entry has no other way to say so: without it the\n * handshake is proxied as an ordinary request and the socket never opens.\n * A consumer with a live-update or realtime endpoint therefore could not\n * express its dev proxy through this table at all.\n */\n readonly ws?: boolean;\n}\n\n/**\n * Where the SPA's built `index.html` is copied to, and under what module name.\n */\nexport interface SpaShellTarget {\n /**\n * Path of the generated module, relative to the repository root.\n *\n * `apps/api/src/generated/spa-shell.ts` in every repo that embeds a shell; the\n * parameter exists because the path is the one thing that genuinely differs.\n */\n readonly path: string;\n /**\n * The repository root the path is resolved against, as a file URL or a path.\n *\n * Defaults to the directory the build runs in (`process.cwd()`), which is the\n * repo root when the build is `pnpm --filter @scope/web build`. Passed in by the\n * Vite config, not derived from `import.meta.url`: this plugin object is created\n * inside the kit's own module, so a URL relative to it points into\n * `node_modules/@rexezuge/tooling` and writes the shell somewhere no compiler\n * will ever look.\n */\n readonly root?: string | URL;\n /**\n * The built `index.html`, as a path or file URL.\n *\n * Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs\n * after the bundle is written, so this is the file the build just produced.\n *\n * A **relative** path resolves against {@link SpaShellTarget.root}, exactly as\n * {@link SpaShellTarget.path} does. It used to resolve against the process's\n * working directory, which under `pnpm --filter … build` is the *package*\n * directory rather than the repository root — so a consumer naming the file\n * relative to the root it had just been given wrote nowhere, and the plugin\n * reported \"dist/index.html not found, skipping\". That message is also what a\n * genuinely fresh checkout prints on its first build, so the two are\n * indistinguishable in the log, and the worker keeps serving the *previous*\n * shell: the SPA ships yesterday's JavaScript with nothing in the build log\n * to explain it.\n */\n readonly distIndex?: string | URL;\n}\n\n/**\n * What `defineWebViteConfig` accepts.\n */\nexport interface WebViteConfigOptions {\n /**\n * The SPA's plugins — `react()`, `tailwindcss()`, and anything else the app\n * needs. Applied before the spa-shell plugin so the shell is written after the\n * bundle exists.\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Dev-server proxy entries. Keyed by path prefix.\n */\n readonly proxy?: Readonly<Record<string, ProxyEntry>>;\n /**\n * Where the built shell is embedded. Omit to skip the embedding entirely.\n */\n readonly spaShell?: SpaShellTarget;\n /**\n * The build output directory.\n */\n readonly outDir?: string;\n /**\n * The directory this config is resolved from, as a file URL. Defaults to the\n * caller's location.\n */\n readonly root?: string;\n}\n\n/**\n * The `spa-shell-embed` plugin, converged from all eight copies.\n *\n * It exists because the API worker serves `SPA_HTML` from a module in its own\n * source tree, and both that module and `dist/` are gitignored — so a fresh\n * clone gets an empty stub from `postinstall` and every `GET /` returns a blank\n * page until someone runs a build. This plugin is what makes the build write the\n * real artefact, and `scripts/verify-spa-shell.ts` is what refuses to deploy\n * without it.\n *\n * Written as a factory rather than inlined so the exit conditions are in one\n * place: the `closeBundle` hook runs on every build, including the ones where\n * `dist/index.html` was never produced, and a plugin that throws there fails\n * builds that legitimately emit nothing.\n */\n/**\n * Normalise a path-or-URL option to a URL, so `new URL(...)` can be used on it.\n *\n * Small, and here because two options accept either form: a path is what a consumer\n * naturally writes in a config, and a URL is what `import.meta.url` hands them.\n * Accepting both is one line and saves a `fileURLToPath` at every call site.\n */\n/**\n * Normalise `string | URL` to a `URL`.\n *\n * A string that is **already a file URL** must be parsed, not converted:\n * `pathToFileURL('file:///srv/app')` treats its argument as a filesystem path\n * and produces `file:///<cwd>/file:/srv/app`, so every path built on top of it\n * silently resolves into a directory named after the scheme.\n *\n * The failure this prevented is not loud. `spaShellEmbedPlugin` then reports\n * \"dist/index.html not found, skipping\" — which is also what a genuinely fresh\n * checkout prints on its first build — and the consumer's worker keeps serving\n * the *previous* shell, so the SPA ships yesterday's JavaScript with no error\n * anywhere in the build log. Both `root` and `distIndex` are documented as\n * \"a file URL or a path\", and `new URL('.', import.meta.url).href` — the shape\n * every config file reaches for first — is a file-URL string, so this is the\n * path most callers take.\n */\nfunction toUrl(value: string | URL): URL {\n if (value instanceof URL) return value;\n return value.startsWith('file:') ? new URL(value) : pathToFileURL(value);\n}\n\n/**\n * The same, as a **directory** URL — with the trailing separator `new URL(rel, base)`\n * needs.\n *\n * `new URL('apps/api/x.ts', 'file:///repo')` resolves to `/apps/api/x.ts`, silently\n * dropping the base. The base has to end in a separator, and a path from\n * `process.cwd()` never does, so this is where the plugin would otherwise write the\n * shell into the filesystem root.\n */\nfunction toDirUrl(value: string | URL): URL {\n const url = toUrl(value);\n return url.href.endsWith('/') ? url : new URL(`${url.href}/`);\n}\n\nexport function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBundle: () => void } {\n return {\n name: 'spa-shell-embed',\n closeBundle() {\n // Resolved from the directory the build runs in, never from this module's own\n // URL: the plugin object is created here but executes in the consumer's Vite\n // process, and `new URL(path, import.meta.url)` would resolve against\n // `node_modules/@rexezuge/tooling`. `process.cwd()` is the repo root for\n // `pnpm --filter @scope/web build`, which is how every consumer runs it.\n const root = toDirUrl(target.root ?? process.cwd());\n const outputPath = fileURLToPath(new URL(target.path, root));\n // A relative `distIndex` resolves against the root, like `path` does —\n // not against the process's working directory, which under\n // `pnpm --filter … build` is the package directory.\n const indexPath =\n target.distIndex === undefined\n ? fileURLToPath(new URL('dist/index.html', root))\n : fileURLToPath(\n typeof target.distIndex === 'string' && !/^[a-z][a-z\\d+\\-.]*:/i.test(target.distIndex)\n ? new URL(target.distIndex, root)\n : toUrl(target.distIndex),\n );\n\n if (!existsSync(indexPath)) {\n // eslint-disable-next-line no-restricted-globals -- build-time Vite plugin, not worker code: there is no logger to inject\n console.warn('spa-shell-embed: dist/index.html not found, skipping');\n return;\n }\n\n const html = readFileSync(indexPath, 'utf8');\n const output = `// Auto-generated by Vite build plugin - DO NOT EDIT.\\nexport const SPA_HTML: string = ${JSON.stringify(html)};\\n`;\n\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n },\n };\n}\n\n/**\n * Build the SPA's Vite config.\n *\n * ```ts\n * // apps/web/vite.config.ts\n * import react from '@vitejs/plugin-react';\n * import { defineWebViteConfig, spaShellEmbedPlugin } from '@rexezuge/tooling/vite';\n *\n * export default defineWebViteConfig({\n * plugins: [react()],\n * proxy: { '/user': { target: 'http://localhost:8787', changeOrigin: true } },\n * spaShell: { path: '../../apps/api/src/generated/spa-shell.ts' },\n * });\n * ```\n */\nexport function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {\n const plugins: Plugin[] = [...(options.plugins ?? [])];\n if (options.spaShell !== undefined) {\n plugins.push(spaShellEmbedPlugin(options.spaShell));\n }\n\n return defineConfig({\n ...(plugins.length > 0 && { plugins }),\n ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),\n build: {\n outDir: options.outDir ?? 'dist',\n emptyOutDir: true,\n },\n });\n}\n"],
|
|
5
|
-
"mappings": "+EA+BA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAOC,MAAU,YACjB,OAAS,iBAAAC,EAAe,iBAAAC,MAAqB,WAC7C,OAAS,gBAAAC,MAAsD,
|
|
6
|
-
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "path", "fileURLToPath", "pathToFileURL", "defineConfig", "toUrl", "value", "__name", "toDirUrl", "url", "spaShellEmbedPlugin", "target", "root", "outputPath", "indexPath", "html", "output", "defineWebViteConfig", "options", "plugins"]
|
|
4
|
+
"sourcesContent": ["/**\n * The SPA's Vite config.\n *\n * Provenance: converged from the `apps/web/vite.config.ts` of the eight repos\n * that build a Vite SPA. They are one file with three variables: the plugin list\n * (`@vitejs/plugin-react` + `@tailwindcss/vite`), the dev-server proxy target,\n * and the `spa-shell-embed` plugin that copies `dist/index.html` into\n * `apps/api/src/generated/spa-shell.ts`.\n *\n * Canonical decisions:\n *\n * 1. **The plugins are passed in, not imported.** The kit stays zero-dependency:\n * `react`, `@vitejs/plugin-react` and `@tailwindcss/vite` belong to the app\n * that uses them, and importing them here would make the tooling package\n * undownloadable for a consumer without a React SPA.\n * 2. **The `spa-shell-embed` hook stays per-repo, and is passed in.** It is the\n * one genuinely repo-specific piece: each repo names its own worker and its\n * own generated-module path. What the kit provides is the *contract* — see\n * `spaShellEmbedPlugin`, which is the converged body of all eight copies.\n * 3. **`server.proxy` is data, not code.** The paths differ per repo\n * (`/user` + `/rest` in Edge-Sonic, `/api` in CalDAV-Bridge, `/tracker` in\n * ChordDHT-Tracker) but the shape never does, so it is an option with a\n * default.\n * 4. **`build.emptyOutDir: true`** is the default, because a stale asset in\n * `dist/` is served as a live bundle — the same half-refreshed build\n * `scripts/verify-spa-shell.ts` rejects.\n *\n * The consumer's `apps/web/vite.config.ts` becomes a handful of lines — see the\n * README.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';\nimport { asVitePlugins } from './plugin-option.ts';\nimport type { PluginOption } from './plugin-option.ts';\n\n/**\n * One dev-server proxy entry, as Vite's `server.proxy` accepts it.\n */\nexport interface ProxyEntry {\n readonly target: string;\n readonly changeOrigin?: boolean;\n readonly bypass?: (request: { headers: Record<string, string | string[] | undefined> }) => string | undefined;\n /**\n * Proxy WebSocket upgrades on this path.\n *\n * Vite's `server.proxy` needs `ws: true` for an entry that carries a\n * WebSocket, and the entry has no other way to say so: without it the\n * handshake is proxied as an ordinary request and the socket never opens.\n * A consumer with a live-update or realtime endpoint therefore could not\n * express its dev proxy through this table at all.\n */\n readonly ws?: boolean;\n}\n\n/**\n * Where the SPA's built `index.html` is copied to, and under what module name.\n */\nexport interface SpaShellTarget {\n /**\n * Path of the generated module, relative to the repository root.\n *\n * `apps/api/src/generated/spa-shell.ts` in every repo that embeds a shell; the\n * parameter exists because the path is the one thing that genuinely differs.\n */\n readonly path: string;\n /**\n * The repository root the path is resolved against, as a file URL or a path.\n *\n * Defaults to the directory the build runs in (`process.cwd()`), which is the\n * repo root when the build is `pnpm --filter @scope/web build`. Passed in by the\n * Vite config, not derived from `import.meta.url`: this plugin object is created\n * inside the kit's own module, so a URL relative to it points into\n * `node_modules/@rexezuge/tooling` and writes the shell somewhere no compiler\n * will ever look.\n */\n readonly root?: string | URL;\n /**\n * The built `index.html`, as a path or file URL.\n *\n * Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs\n * after the bundle is written, so this is the file the build just produced.\n *\n * A **relative** path resolves against {@link SpaShellTarget.root}, exactly as\n * {@link SpaShellTarget.path} does. It used to resolve against the process's\n * working directory, which under `pnpm --filter … build` is the *package*\n * directory rather than the repository root — so a consumer naming the file\n * relative to the root it had just been given wrote nowhere, and the plugin\n * reported \"dist/index.html not found, skipping\". That message is also what a\n * genuinely fresh checkout prints on its first build, so the two are\n * indistinguishable in the log, and the worker keeps serving the *previous*\n * shell: the SPA ships yesterday's JavaScript with nothing in the build log\n * to explain it.\n */\n readonly distIndex?: string | URL;\n}\n\n/**\n * What `defineWebViteConfig` accepts.\n */\nexport interface WebViteConfigOptions {\n /**\n * The SPA's plugins — `react()`, `tailwindcss()`, and anything else the app\n * needs. Applied before the spa-shell plugin so the shell is written after the\n * bundle exists.\n */\n readonly plugins?: readonly PluginOption[];\n /**\n * Dev-server proxy entries. Keyed by path prefix.\n */\n readonly proxy?: Readonly<Record<string, ProxyEntry>>;\n /**\n * Where the built shell is embedded. Omit to skip the embedding entirely.\n */\n readonly spaShell?: SpaShellTarget;\n /**\n * The build output directory.\n */\n readonly outDir?: string;\n /**\n * The directory this config is resolved from, as a file URL. Defaults to the\n * caller's location.\n */\n readonly root?: string;\n}\n\n/**\n * The `spa-shell-embed` plugin, converged from all eight copies.\n *\n * It exists because the API worker serves `SPA_HTML` from a module in its own\n * source tree, and both that module and `dist/` are gitignored — so a fresh\n * clone gets an empty stub from `postinstall` and every `GET /` returns a blank\n * page until someone runs a build. This plugin is what makes the build write the\n * real artefact, and `scripts/verify-spa-shell.ts` is what refuses to deploy\n * without it.\n *\n * Written as a factory rather than inlined so the exit conditions are in one\n * place: the `closeBundle` hook runs on every build, including the ones where\n * `dist/index.html` was never produced, and a plugin that throws there fails\n * builds that legitimately emit nothing.\n */\n/**\n * Normalise a path-or-URL option to a URL, so `new URL(...)` can be used on it.\n *\n * Small, and here because two options accept either form: a path is what a consumer\n * naturally writes in a config, and a URL is what `import.meta.url` hands them.\n * Accepting both is one line and saves a `fileURLToPath` at every call site.\n */\n/**\n * Normalise `string | URL` to a `URL`.\n *\n * A string that is **already a file URL** must be parsed, not converted:\n * `pathToFileURL('file:///srv/app')` treats its argument as a filesystem path\n * and produces `file:///<cwd>/file:/srv/app`, so every path built on top of it\n * silently resolves into a directory named after the scheme.\n *\n * The failure this prevented is not loud. `spaShellEmbedPlugin` then reports\n * \"dist/index.html not found, skipping\" — which is also what a genuinely fresh\n * checkout prints on its first build — and the consumer's worker keeps serving\n * the *previous* shell, so the SPA ships yesterday's JavaScript with no error\n * anywhere in the build log. Both `root` and `distIndex` are documented as\n * \"a file URL or a path\", and `new URL('.', import.meta.url).href` — the shape\n * every config file reaches for first — is a file-URL string, so this is the\n * path most callers take.\n */\nfunction toUrl(value: string | URL): URL {\n if (value instanceof URL) return value;\n return value.startsWith('file:') ? new URL(value) : pathToFileURL(value);\n}\n\n/**\n * The same, as a **directory** URL — with the trailing separator `new URL(rel, base)`\n * needs.\n *\n * `new URL('apps/api/x.ts', 'file:///repo')` resolves to `/apps/api/x.ts`, silently\n * dropping the base. The base has to end in a separator, and a path from\n * `process.cwd()` never does, so this is where the plugin would otherwise write the\n * shell into the filesystem root.\n */\nfunction toDirUrl(value: string | URL): URL {\n const url = toUrl(value);\n return url.href.endsWith('/') ? url : new URL(`${url.href}/`);\n}\n\nexport function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBundle: () => void } {\n return {\n name: 'spa-shell-embed',\n closeBundle() {\n // Resolved from the directory the build runs in, never from this module's own\n // URL: the plugin object is created here but executes in the consumer's Vite\n // process, and `new URL(path, import.meta.url)` would resolve against\n // `node_modules/@rexezuge/tooling`. `process.cwd()` is the repo root for\n // `pnpm --filter @scope/web build`, which is how every consumer runs it.\n const root = toDirUrl(target.root ?? process.cwd());\n const outputPath = fileURLToPath(new URL(target.path, root));\n // A relative `distIndex` resolves against the root, like `path` does —\n // not against the process's working directory, which under\n // `pnpm --filter … build` is the package directory.\n const indexPath =\n target.distIndex === undefined\n ? fileURLToPath(new URL('dist/index.html', root))\n : fileURLToPath(\n typeof target.distIndex === 'string' && !/^[a-z][a-z\\d+\\-.]*:/i.test(target.distIndex)\n ? new URL(target.distIndex, root)\n : toUrl(target.distIndex),\n );\n\n if (!existsSync(indexPath)) {\n // eslint-disable-next-line no-restricted-globals -- build-time Vite plugin, not worker code: there is no logger to inject\n console.warn('spa-shell-embed: dist/index.html not found, skipping');\n return;\n }\n\n const html = readFileSync(indexPath, 'utf8');\n const output = `// Auto-generated by Vite build plugin - DO NOT EDIT.\\nexport const SPA_HTML: string = ${JSON.stringify(html)};\\n`;\n\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n },\n };\n}\n\n/**\n * Build the SPA's Vite config.\n *\n * ```ts\n * // apps/web/vite.config.ts\n * import react from '@vitejs/plugin-react';\n * import { defineWebViteConfig, spaShellEmbedPlugin } from '@rexezuge/tooling/vite';\n *\n * export default defineWebViteConfig({\n * plugins: [react()],\n * proxy: { '/user': { target: 'http://localhost:8787', changeOrigin: true } },\n * spaShell: { path: '../../apps/api/src/generated/spa-shell.ts' },\n * });\n * ```\n */\nexport function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {\n const plugins: PluginOption[] = [...(options.plugins ?? [])];\n if (options.spaShell !== undefined) {\n plugins.push(spaShellEmbedPlugin(options.spaShell));\n }\n\n return defineConfig({\n ...(plugins.length > 0 && { plugins: asVitePlugins(plugins) }),\n ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),\n build: {\n outDir: options.outDir ?? 'dist',\n emptyOutDir: true,\n },\n });\n}\n"],
|
|
5
|
+
"mappings": "+EA+BA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAOC,MAAU,YACjB,OAAS,iBAAAC,EAAe,iBAAAC,MAAqB,WAC7C,OAAS,gBAAAC,MAAsD,gBAC/D,OAAS,iBAAAC,MAAqB,qBAoI9B,SAASC,EAAMC,EAAmB,CAChC,OAAIA,aAAiB,IAAYA,EAC1BA,EAAM,WAAW,OAAO,EAAI,IAAI,IAAIA,CAAK,EAAIJ,EAAcI,CAAK,CACzE,CA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AAK,CAAE,CAAE,EAC5E,MAAO,CACL,OAAQA,EAAQ,QAAU,OAC1B,YAAa,IAEhB,CACH,CAdgBX,EAAAU,EAAA",
|
|
6
|
+
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "path", "fileURLToPath", "pathToFileURL", "defineConfig", "asVitePlugins", "toUrl", "value", "__name", "toDirUrl", "url", "spaShellEmbedPlugin", "target", "root", "outputPath", "indexPath", "html", "output", "defineWebViteConfig", "options", "plugins"]
|
|
7
7
|
}
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
* untouched. CalDAV-Bridge's suite passes none of them (plain `node` +
|
|
17
17
|
* `node:sqlite`, no coverage); the workerd suites pass all three.
|
|
18
18
|
*/
|
|
19
|
-
import { defineConfig
|
|
19
|
+
import { defineConfig } from 'vitest/config';
|
|
20
|
+
import type { PluginOption } from './plugin-option.ts';
|
|
20
21
|
import type { Pool } from 'vitest/node';
|
|
21
22
|
import type { VitestAlias } from './vitest-aliases.ts';
|
|
22
23
|
/**
|
|
@@ -51,7 +52,7 @@ export interface IntegrationVitestConfigOptions {
|
|
|
51
52
|
* runner's own plugin so a workerd plugin is accepted and nothing new is
|
|
52
53
|
* imported — this package stays dependency-free.
|
|
53
54
|
*/
|
|
54
|
-
readonly plugins?: readonly
|
|
55
|
+
readonly plugins?: readonly PluginOption[];
|
|
55
56
|
/**
|
|
56
57
|
* The pool (the workerd `cloudflarePool()`). The runner's own `Pool` type,
|
|
57
58
|
* so a custom pool is accepted without importing its provider.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vitest-integration.d.ts","sourceRoot":"","sources":["../src/vitest-integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,YAAY,EAAE,KAAK,
|
|
1
|
+
{"version":3,"file":"vitest-integration.d.ts","sourceRoot":"","sources":["../src/vitest-integration.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAExC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC7C;;OAEG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC;;OAEG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,WAAW,EAAE,CAAC;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,YAAY,EAAE,CAAC;IAC3C;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC;IACrB;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACnD;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5C;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,8BAA8B,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAmBtH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=Object.defineProperty;var r=(e,n)=>s(e,"name",{value:n,configurable:!0});import{defineConfig as a}from"vitest/config";import{asVitePlugins as l}from"./plugin-option.js";import{DEFAULT_WORKSPACE_PACKAGES as t,workspaceAliases as d}from"./vitest-aliases.js";function g(e){const n=e.root??new URL(".",import.meta.url).href,i=[...d({scope:e.scope,root:n,packages:e.packages??t,mocks:[]}),...e.aliases??[]];return a({...e.define!==void 0&&{define:{...e.define}},...e.plugins!==void 0&&{plugins:l(e.plugins)},resolve:{alias:i},test:{globals:!0,environment:"node",include:[...e.include??["test/integration/**/*.int.test.ts"]],...e.pool!==void 0&&{pool:e.pool}},...e.ssrNoExternal!==void 0&&{ssr:{noExternal:[...e.ssrNoExternal]}}})}r(g,"defineIntegrationVitestConfig");export{g as defineIntegrationVitestConfig};
|