@rexezuge/tooling 1.5.0 → 1.5.2

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.
Files changed (54) hide show
  1. package/dist/eslint-boundaries.js +1 -1
  2. package/dist/eslint-boundaries.js.map +2 -2
  3. package/dist/eslint.d.ts.map +1 -1
  4. package/dist/eslint.js +1 -1
  5. package/dist/eslint.js.map +3 -3
  6. package/dist/functions/pages-proxy.js +1 -1
  7. package/dist/functions/pages-proxy.js.map +2 -2
  8. package/dist/scripts/backup/d1-target.js +1 -1
  9. package/dist/scripts/backup/d1-target.js.map +2 -2
  10. package/dist/scripts/backup/destination-config.js +1 -1
  11. package/dist/scripts/backup/destination-config.js.map +2 -2
  12. package/dist/scripts/backup/naming.js +1 -1
  13. package/dist/scripts/backup/naming.js.map +2 -2
  14. package/dist/scripts/check-god-files.js +2 -2
  15. package/dist/scripts/check-god-files.js.map +2 -2
  16. package/dist/scripts/init-secrets.js +2 -2
  17. package/dist/scripts/init-secrets.js.map +2 -2
  18. package/dist/scripts/lib/cli-args.js +1 -1
  19. package/dist/scripts/lib/cli-args.js.map +2 -2
  20. package/dist/scripts/lib/github-actions.js +3 -3
  21. package/dist/scripts/lib/github-actions.js.map +2 -2
  22. package/dist/scripts/lib/wrangler-table.js +2 -2
  23. package/dist/scripts/lib/wrangler-table.js.map +2 -2
  24. package/dist/scripts/spa-shell.js +2 -2
  25. package/dist/scripts/spa-shell.js.map +2 -2
  26. package/dist/scripts/validate-locales.js +4 -4
  27. package/dist/scripts/validate-locales.js.map +2 -2
  28. package/dist/scripts/verify-migrations.js +2 -2
  29. package/dist/scripts/verify-migrations.js.map +2 -2
  30. package/dist/scripts/wrangler-config/cli.js +3 -3
  31. package/dist/scripts/wrangler-config/cli.js.map +2 -2
  32. package/dist/scripts/wrangler-config/patches.js +3 -3
  33. package/dist/scripts/wrangler-config/patches.js.map +2 -2
  34. package/dist/scripts/wrangler-config/resources.js +1 -1
  35. package/dist/scripts/wrangler-config/resources.js.map +2 -2
  36. package/dist/test/integration-migrations.js +2 -2
  37. package/dist/test/integration-migrations.js.map +2 -2
  38. package/dist/test/mocks/cloudflare-workers.js +1 -1
  39. package/dist/test/mocks/cloudflare-workers.js.map +2 -2
  40. package/dist/vite.js +3 -3
  41. package/dist/vite.js.map +2 -2
  42. package/dist/vitest-aliases.js +1 -1
  43. package/dist/vitest-aliases.js.map +2 -2
  44. package/dist/vitest-integration.js +1 -1
  45. package/dist/vitest-integration.js.map +2 -2
  46. package/dist/vitest-repo.js +1 -1
  47. package/dist/vitest-repo.js.map +2 -2
  48. package/dist/vitest-web.js +1 -1
  49. package/dist/vitest-web.js.map +2 -2
  50. package/dist/vitest.js +1 -1
  51. package/dist/vitest.js.map +2 -2
  52. package/package.json +2 -2
  53. package/src/eslint.test.ts +20 -0
  54. package/src/eslint.ts +13 -3
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../src/scripts/lib/wrangler-table.ts"],
4
4
  "sourcesContent": ["/**\n * Parsers for the human-readable tables `wrangler` prints.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-table.ts`, which was\n * factored out of two scripts that had each grown their own copy.\n *\n * `wrangler secrets-store …` renders through `cli-table3`, which draws a\n * box-drawing frame and separates cells with U+2502 (`│`) padded by exactly one\n * space. Columns are therefore *not* space-aligned, and a parser written for\n * aligned output silently matches nothing — which reads as \"the resource is\n * absent\" and makes provisioning create a duplicate.\n *\n * ### Why membership is exact and never a substring\n *\n * Durable-DAV's `init-secrets.ts` used `output.includes(secretName)`, and that is\n * the defect this port replaces: a store holding both\n * `durable-dav-replication-encryption-key` and a `…-key-backup` would satisfy a\n * substring search for the first, so the real secret was reported as already\n * present and never created. A substring match is not a membership test.\n */\n\n/**\n * Cell separator emitted by `cli-table3`.\n */\nconst COLUMN_SEPARATOR = String.fromCodePoint(0x25_02);\n\n/**\n * Horizontal rule drawn by `cli-table3`; a row made of these is not data.\n */\nconst RULE_CHARACTER = String.fromCodePoint(0x25_00);\n\n/**\n * Header row of every `wrangler … list` table.\n */\nconst HEADER_FIRST_CELL = 'Name';\n\n/**\n * Extracts the data rows of a `wrangler` table, dropping the frame, the header,\n * and any surrounding log lines.\n *\n * Rows are returned in print order with cells trimmed and empty cells removed,\n * so a blank optional column (`Comment`, typically unset) does not shift the\n * columns a caller indexes into.\n */\nexport function parseWranglerTableRows(output: string): string[][] {\n const rows: string[][] = [];\n for (const line of output.split('\\n')) {\n // The frame rows use U+253C (`┼`) at the joints rather than U+2502, so they\n // are already excluded here; the rule-character guard below additionally\n // covers borders that happen to contain a separator.\n if (!line.includes(COLUMN_SEPARATOR)) {\n continue;\n }\n\n const cells: string[] = line\n .split(COLUMN_SEPARATOR)\n .map((cell) => cell.trim())\n .filter(Boolean);\n if (cells.length < 2) {\n continue;\n }\n const firstCell = cells[0];\n // The header row and the horizontal rules are frame, not data.\n if (firstCell === HEADER_FIRST_CELL || firstCell.includes(RULE_CHARACTER)) {\n continue;\n }\n rows.push(cells);\n }\n return rows;\n}\n\n/**\n * The exact names in the first column of a `wrangler secrets-store secret list`\n * table.\n *\n * Exact values rather than a substring search — see the header.\n */\nexport function parseWranglerNames(output: string): Set<string> {\n const names = new Set<string>();\n for (const row of parseWranglerTableRows(output)) {\n // `.at()` rather than `[0]`: the absence case is real for a hand-built row\n // in a test double, and the guard below is what keeps it out of the set.\n const name = row.at(0);\n if (name !== undefined) names.add(name);\n }\n return names;\n}\n\n/**\n * wrangler exits non-zero when a Secrets Store holds no secrets\n * (`secrets-store secret list` throws this `FatalError`), which is\n * indistinguishable by exit code from a genuine failure.\n */\nconst EMPTY_STORE_MESSAGE = 'List request returned no secrets';\n\n/**\n * True when a failed `secrets-store secret list` means the store is empty\n * rather than the listing having failed.\n *\n * Callers must treat this as a confirmed absence; every other failure has to\n * stay indistinguishable from \"unknown\", or a transient CLI error would be read\n * as permission to create a secret that already holds a live value.\n */\nexport function isEmptySecretsStoreListing(error: unknown): boolean {\n const message: string = error instanceof Error ? error.message : String(error);\n return message.includes(EMPTY_STORE_MESSAGE);\n}\n"],
5
- "mappings": "AAwBA,MAAMA,EAAmB,OAAO,cAAc,IAAO,EAK/CC,EAAiB,OAAO,cAAc,IAAO,EAK7CC,EAAoB,OAUpB,SAAUC,EAAuBC,EAAc,CACnD,MAAMC,EAAmB,CAAA,EACzB,UAAWC,KAAQF,EAAO,MAAM;CAAI,EAAG,CAIrC,GAAI,CAACE,EAAK,SAASN,CAAgB,EACjC,SAGF,MAAMO,EAAkBD,EACrB,MAAMN,CAAgB,EACtB,IAAKQ,GAASA,EAAK,KAAI,CAAE,EACzB,OAAO,OAAO,EACjB,GAAID,EAAM,OAAS,EACjB,SAEF,MAAME,EAAYF,EAAM,CAAC,EAErBE,IAAcP,GAAqBO,EAAU,SAASR,CAAc,GAGxEI,EAAK,KAAKE,CAAK,CACjB,CACA,OAAOF,CACT,CAQM,SAAUK,EAAmBN,EAAc,CAC/C,MAAMO,EAAQ,IAAI,IAClB,UAAWC,KAAOT,EAAuBC,CAAM,EAAG,CAGhD,MAAMS,EAAOD,EAAI,GAAG,CAAC,EACjBC,IAAS,QAAWF,EAAM,IAAIE,CAAI,CACxC,CACA,OAAOF,CACT,CAOA,MAAMG,EAAsB,mCAUtB,SAAUC,EAA2BC,EAAc,CAEvD,OADwBA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,GAC9D,SAASF,CAAmB,CAC7C",
6
- "names": ["COLUMN_SEPARATOR", "RULE_CHARACTER", "HEADER_FIRST_CELL", "parseWranglerTableRows", "output", "rows", "line", "cells", "cell", "firstCell", "parseWranglerNames", "names", "row", "name", "EMPTY_STORE_MESSAGE", "isEmptySecretsStoreListing", "error"]
5
+ "mappings": "+EAwBA,MAAMA,EAAmB,OAAO,cAAc,IAAO,EAK/CC,EAAiB,OAAO,cAAc,IAAO,EAK7CC,EAAoB,OAUpB,SAAUC,EAAuBC,EAAc,CACnD,MAAMC,EAAmB,CAAA,EACzB,UAAWC,KAAQF,EAAO,MAAM;CAAI,EAAG,CAIrC,GAAI,CAACE,EAAK,SAASN,CAAgB,EACjC,SAGF,MAAMO,EAAkBD,EACrB,MAAMN,CAAgB,EACtB,IAAKQ,GAASA,EAAK,KAAI,CAAE,EACzB,OAAO,OAAO,EACjB,GAAID,EAAM,OAAS,EACjB,SAEF,MAAME,EAAYF,EAAM,CAAC,EAErBE,IAAcP,GAAqBO,EAAU,SAASR,CAAc,GAGxEI,EAAK,KAAKE,CAAK,CACjB,CACA,OAAOF,CACT,CAzBgBK,EAAAP,EAAA,0BAiCV,SAAUQ,EAAmBP,EAAc,CAC/C,MAAMQ,EAAQ,IAAI,IAClB,UAAWC,KAAOV,EAAuBC,CAAM,EAAG,CAGhD,MAAMU,EAAOD,EAAI,GAAG,CAAC,EACjBC,IAAS,QAAWF,EAAM,IAAIE,CAAI,CACxC,CACA,OAAOF,CACT,CATgBF,EAAAC,EAAA,sBAgBhB,MAAMI,EAAsB,mCAUtB,SAAUC,EAA2BC,EAAc,CAEvD,OADwBA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,GAC9D,SAASF,CAAmB,CAC7C,CAHgBL,EAAAM,EAAA",
6
+ "names": ["COLUMN_SEPARATOR", "RULE_CHARACTER", "HEADER_FIRST_CELL", "parseWranglerTableRows", "output", "rows", "line", "cells", "cell", "firstCell", "__name", "parseWranglerNames", "names", "row", "name", "EMPTY_STORE_MESSAGE", "isEmptySecretsStoreListing", "error"]
7
7
  }
@@ -1,3 +1,3 @@
1
- import{existsSync as a,mkdirSync as g,readFileSync as c,writeFileSync as m}from"node:fs";import{pathToFileURL as S}from"node:url";import l from"node:path";const y="apps/api/src/generated/spa-shell.ts",v="apps/web/dist/index.html",T=`// Auto-generated stub - real content is produced by the build step via the Vite plugin.
1
+ var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import{existsSync as c,mkdirSync as S,readFileSync as h,writeFileSync as y}from"node:fs";import{pathToFileURL as v}from"node:url";import l from"node:path";const T="apps/api/src/generated/spa-shell.ts",$="apps/web/dist/index.html",A=`// Auto-generated stub - real content is produced by the build step via the Vite plugin.
2
2
  export const SPA_HTML: string = '';
3
- `,$=200;function h(t){const e=l.resolve(t.root),r=l.join(e,t.shellPath??y),n=l.join(e,t.distIndexPath??v);return{shell:r,distIndex:n,distAssets:l.join(l.dirname(n),"assets")}}function d(t){const{shell:e}=h(t);g(l.dirname(e),{recursive:!0});try{m(e,T,{encoding:"utf8",flag:"wx"})}catch(r){if(r?.code==="EEXIST")return{created:!1,path:e};throw r}return{created:!0,path:e}}function A(t,e){if(!a(t))return e.push(`${t} is missing \u2014 run the build (only apps/web has a build step).`),null;const r=c(t,"utf8"),n="export const SPA_HTML: string = ",s=r.indexOf(n);if(s===-1)return e.push(`${t} does not export SPA_HTML \u2014 regenerate it with the build.`),null;const o=r.slice(s+n.length).replace(/;\s*$/,"");if(o==="''"||o==='""')return e.push(`${t} still holds the empty postinstall stub \u2014 run the build. Until then every browser navigation served by the API worker is a blank page.`),null;let i;try{i=JSON.parse(o)}catch{return e.push(`${t} is not the generated shape \u2014 delete it and run the build.`),null}return typeof i!="string"||i.length<$?(e.push(`${t} holds no usable HTML \u2014 run the build. Until then every browser navigation is a blank page.`),null):i}function p(t){const{shell:e,distIndex:r,distAssets:n}=h(t),s=[],o=A(e,s);if(o===null)return{problems:s};const i=[...o.matchAll(/(?:src|href)="\/assets\/([^"]+)"/g)].map(u=>u[1]);i.length===0&&s.push("The embedded shell references no /assets/ bundles \u2014 it is not a real build output.");for(const u of new Set(i))a(l.join(n,u))||s.push(`The embedded shell references /assets/${u}, which is not in ${n} \u2014 run the build.`);return a(r)?c(r,"utf8")!==o&&s.push(`${e} does not match ${r} \u2014 run the build.`):s.push(`${r} is missing \u2014 run the build.`),{problems:s}}const f="verify|ensure";function b(t=process.argv.slice(2)){const e=t[0]??"verify";if(!f.split("|").includes(e))return console.error(`Usage: tsx spa-shell.ts <${f}> [repo-root]`),1;const r={root:t[1]??process.cwd()};if(e==="ensure"){const s=d(r);return s.created?console.log(`ensure-spa-shell-stub: created stub at ${s.path}`):console.log(`ensure-spa-shell-stub: ${s.path} already present, left untouched`),0}const{problems:n}=p(r);if(n.length>0){console.error("SPA shell check failed:");for(const s of n)console.error(` - ${s}`);return 1}return console.log("SPA shell check passed."),0}process.argv[1]!==void 0&&import.meta.url===S(process.argv[1]).href&&process.exit(b(process.argv.slice(2)));export{d as ensureSpaShellStub,b as spaShellCli,p as verifySpaShell};
3
+ `,x=200;function d(t){const e=l.resolve(t.root),r=l.join(e,t.shellPath??T),n=l.join(e,t.distIndexPath??$);return{shell:r,distIndex:n,distAssets:l.join(l.dirname(n),"assets")}}u(d,"resolvePaths");function p(t){const{shell:e}=d(t);S(l.dirname(e),{recursive:!0});try{y(e,A,{encoding:"utf8",flag:"wx"})}catch(r){if(r?.code==="EEXIST")return{created:!1,path:e};throw r}return{created:!0,path:e}}u(p,"ensureSpaShellStub");function w(t,e){if(!c(t))return e.push(`${t} is missing \u2014 run the build (only apps/web has a build step).`),null;const r=h(t,"utf8"),n="export const SPA_HTML: string = ",s=r.indexOf(n);if(s===-1)return e.push(`${t} does not export SPA_HTML \u2014 regenerate it with the build.`),null;const o=r.slice(s+n.length).replace(/;\s*$/,"");if(o==="''"||o==='""')return e.push(`${t} still holds the empty postinstall stub \u2014 run the build. Until then every browser navigation served by the API worker is a blank page.`),null;let i;try{i=JSON.parse(o)}catch{return e.push(`${t} is not the generated shape \u2014 delete it and run the build.`),null}return typeof i!="string"||i.length<x?(e.push(`${t} holds no usable HTML \u2014 run the build. Until then every browser navigation is a blank page.`),null):i}u(w,"readEmbeddedHtml");function f(t){const{shell:e,distIndex:r,distAssets:n}=d(t),s=[],o=w(e,s);if(o===null)return{problems:s};const i=[...o.matchAll(/(?:src|href)="\/assets\/([^"]+)"/g)].map(a=>a[1]);i.length===0&&s.push("The embedded shell references no /assets/ bundles \u2014 it is not a real build output.");for(const a of new Set(i))c(l.join(n,a))||s.push(`The embedded shell references /assets/${a}, which is not in ${n} \u2014 run the build.`);return c(r)?h(r,"utf8")!==o&&s.push(`${e} does not match ${r} \u2014 run the build.`):s.push(`${r} is missing \u2014 run the build.`),{problems:s}}u(f,"verifySpaShell");const b="verify|ensure";function g(t=process.argv.slice(2)){const e=t[0]??"verify";if(!b.split("|").includes(e))return console.error(`Usage: tsx spa-shell.ts <${b}> [repo-root]`),1;const r={root:t[1]??process.cwd()};if(e==="ensure"){const s=p(r);return s.created?console.log(`ensure-spa-shell-stub: created stub at ${s.path}`):console.log(`ensure-spa-shell-stub: ${s.path} already present, left untouched`),0}const{problems:n}=f(r);if(n.length>0){console.error("SPA shell check failed:");for(const s of n)console.error(` - ${s}`);return 1}return console.log("SPA shell check passed."),0}u(g,"spaShellCli");process.argv[1]!==void 0&&import.meta.url===v(process.argv[1]).href&&process.exit(g(process.argv.slice(2)));export{p as ensureSpaShellStub,g as spaShellCli,f as verifySpaShell};
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/scripts/spa-shell.ts"],
4
4
  "sourcesContent": ["/**\n * The SPA shell pair: `ensure-spa-shell-stub` + `verify-spa-shell`.\n *\n * Provenance: the `scripts/ensure-spa-shell-stub.mjs` +\n * `scripts/verify-spa-shell.mjs` pair (Durable-DAV) and Edge-Sonic's typed\n * `scripts/build/{ensure-spa-shell-stub,spa-shell-checks,verify-spa-shell}.ts`.\n * The generate step itself is a Vite plugin (`spaShellEmbedPlugin` in\n * `vite.ts`) because it must run on every build; this module holds the\n * freshness contract around the generated file.\n *\n * Why the pair exists: `apps/api/src/generated/spa-shell.ts` and\n * `apps/web/dist/` are both gitignored build artifacts. A fresh clone gets the\n * empty postinstall stub and every browser navigation returns a blank page,\n * with nothing in the source tree saying so.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\n\ninterface SpaShellPaths {\n /**\n Repo root.\n */\n root: string;\n /**\n Generated TS module path, relative to root.\n */\n shellPath?: string;\n /**\n Built SPA index.html path, relative to root.\n */\n distIndexPath?: string;\n}\n\ninterface VerifyResult {\n problems: string[];\n}\n\nconst DEFAULT_SHELL = 'apps/api/src/generated/spa-shell.ts';\nconst DEFAULT_DIST_INDEX = 'apps/web/dist/index.html';\nconst STUB_CONTENT =\n \"// Auto-generated stub - real content is produced by the build step via the Vite plugin.\\nexport const SPA_HTML: string = '';\\n\";\n\n/**\nA built shell is a full Vite index.html; any small threshold rejects the stub.\n*/\nconst MIN_HTML_CHARS = 200;\n\nfunction resolvePaths(options: SpaShellPaths): { shell: string; distIndex: string; distAssets: string } {\n const root = path.resolve(options.root);\n const shell = path.join(root, options.shellPath ?? DEFAULT_SHELL);\n const distIndex = path.join(root, options.distIndexPath ?? DEFAULT_DIST_INDEX);\n return { shell, distIndex, distAssets: path.join(path.dirname(distIndex), 'assets') };\n}\n\n/**\n * Create the empty stub when (and only when) nothing is there yet, so a fresh\n * clone typechecks and `pnpm run build` regenerates the real thing. Never\n * overwrites an existing file — overwriting would erase a real build with a\n * stub on the next `pnpm install`.\n */\nfunction ensureSpaShellStub(options: SpaShellPaths): { created: boolean; path: string } {\n const { shell } = resolvePaths(options);\n mkdirSync(path.dirname(shell), { recursive: true });\n try {\n writeFileSync(shell, STUB_CONTENT, { encoding: 'utf8', flag: 'wx' });\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code === 'EEXIST') {\n return { created: false, path: shell };\n }\n throw error;\n }\n return { created: true, path: shell };\n}\n\n/**\nThe `SPA_HTML` string literal, decoded from the generated TS module.\n*/\nfunction readEmbeddedHtml(shell: string, problems: string[]): string | null {\n if (!existsSync(shell)) {\n problems.push(`${shell} is missing — run the build (only apps/web has a build step).`);\n return null;\n }\n const source = readFileSync(shell, 'utf8');\n const marker = 'export const SPA_HTML: string = ';\n const at = source.indexOf(marker);\n if (at === -1) {\n problems.push(`${shell} does not export SPA_HTML — regenerate it with the build.`);\n return null;\n }\n const literal = source.slice(at + marker.length).replace(/;\\s*$/, '');\n if (literal === \"''\" || literal === '\"\"') {\n problems.push(\n `${shell} still holds the empty postinstall stub — run the build. Until then every browser navigation served by the API worker is a blank page.`,\n );\n return null;\n }\n let html: unknown;\n try {\n html = JSON.parse(literal);\n } catch {\n problems.push(`${shell} is not the generated shape — delete it and run the build.`);\n return null;\n }\n if (typeof html !== 'string' || html.length < MIN_HTML_CHARS) {\n problems.push(`${shell} holds no usable HTML — run the build. Until then every browser navigation is a blank page.`);\n return null;\n }\n return html;\n}\n\n/**\n * Fail when the shell the API worker serves is missing or self-inconsistent:\n *\n * - the postinstall stub (or no build at all) still in place;\n * - `/assets/...` bundles referenced but not emitted (a half-cleaned dist,\n * which serves a shell whose JS 404s);\n * - `spa-shell.ts` and `dist/index.html` disagreeing — only one half of the\n * build was refreshed.\n *\n * Known limit, stated rather than papered over: a *stale but self-consistent*\n * pair passes. That class is covered at the source level by each repo's SPA\n * parser integration test; the remaining duty is operational — run the build\n * after touching `apps/web`, before deploy.\n */\nfunction verifySpaShell(options: SpaShellPaths): VerifyResult {\n const { shell, distIndex, distAssets } = resolvePaths(options);\n const problems: string[] = [];\n const html = readEmbeddedHtml(shell, problems);\n if (html === null) {\n return { problems };\n }\n const referenced = [...html.matchAll(/(?:src|href)=\"\\/assets\\/([^\"]+)\"/g)].map((match) => match[1]);\n if (referenced.length === 0) {\n problems.push('The embedded shell references no /assets/ bundles — it is not a real build output.');\n }\n for (const asset of new Set(referenced)) {\n if (!existsSync(path.join(distAssets, asset))) {\n problems.push(`The embedded shell references /assets/${asset}, which is not in ${distAssets} — run the build.`);\n }\n }\n if (!existsSync(distIndex)) {\n problems.push(`${distIndex} is missing — run the build.`);\n } else if (readFileSync(distIndex, 'utf8') !== html) {\n problems.push(`${shell} does not match ${distIndex} — run the build.`);\n }\n return { problems };\n}\n\nconst CLI_SHAPES = 'verify|ensure';\n\n/**\nCLI entry: `spaShellCli(['verify'|'ensure', 'repo-root?'])`.\n*/\nfunction spaShellCli(argv: readonly string[] = process.argv.slice(2)): number {\n const mode = argv[0] ?? 'verify';\n if (!CLI_SHAPES.split('|').includes(mode)) {\n console.error(`Usage: tsx spa-shell.ts <${CLI_SHAPES}> [repo-root]`);\n return 1;\n }\n const options: SpaShellPaths = { root: argv[1] ?? process.cwd() };\n if (mode === 'ensure') {\n const result = ensureSpaShellStub(options);\n if (result.created) {\n console.log(`ensure-spa-shell-stub: created stub at ${result.path}`);\n } else {\n console.log(`ensure-spa-shell-stub: ${result.path} already present, left untouched`);\n }\n return 0;\n }\n const { problems } = verifySpaShell(options);\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('SPA shell check passed.');\n return 0;\n}\n\nexport { ensureSpaShellStub, spaShellCli, verifySpaShell };\nexport type { SpaShellPaths, VerifyResult };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(spaShellCli(process.argv.slice(2)));\n}\n"],
5
- "mappings": "AAeA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAS,iBAAAC,MAAqB,WAC9B,OAAOC,MAAU,YAqBjB,MAAMC,EAAgB,sCAChBC,EAAqB,2BACrBC,EACJ;;EAKIC,EAAiB,IAEvB,SAASC,EAAaC,EAAsB,CAC1C,MAAMC,EAAOP,EAAK,QAAQM,EAAQ,IAAI,EAChCE,EAAQR,EAAK,KAAKO,EAAMD,EAAQ,WAAaL,CAAa,EAC1DQ,EAAYT,EAAK,KAAKO,EAAMD,EAAQ,eAAiBJ,CAAkB,EAC7E,MAAO,CAAE,MAAAM,EAAO,U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AU,QAAQ,MAAM,OAAOgB,CAAO,EAAE,EAC9D,MAAO,EACT,CACA,eAAQ,IAAI,yBAAyB,EAC9B,CACT,CAYI,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQ9B,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAK0B,EAAY,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
- "names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "pathToFileURL", "path", "DEFAULT_SHELL", "DEFAULT_DIST_INDEX", "STUB_CONTENT", "MIN_HTML_CHARS", "resolvePaths", "options", "root", "shell", "distIndex", "ensureSpaShellStub", "error", "readEmbeddedHtml", "problems", "source", "marker", "at", "literal", "html", "verifySpaShell", "distAssets", "referenced", "match", "asset", "CLI_SHAPES", "spaShellCli", "argv", "mode", "result", "problem"]
5
+ "mappings": "+EAeA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAS,iBAAAC,MAAqB,WAC9B,OAAOC,MAAU,YAqBjB,MAAMC,EAAgB,sCAChBC,EAAqB,2BACrBC,EACJ;;EAKIC,EAAiB,IAEvB,SAASC,EAAaC,EAAsB,CAC1C,MAAMC,EAAOP,EAAK,QAAQM,EAAQ,IAAI,EAChCE,EAAQR,EAAK,KAAKO,EAAMD,EAAQ,WAAaL,CAAa,EAC1DQ,EAAYT,EAAK,KAAKO,EAAMD,EAAQ,eAAiBJ,CAAkB,EAC7E,MAAO,CAAE,MAAAM,EAAO,UAAAC,EAAW,WAAYT,EAAK,KAAKA,EAAK,QAAQS,CAAS,EAAG,QAAQ,CAAC,CACrF,CALSC,EAAAL,EAAA,gBAaT,SAASM,EAAmBL,EAAsB,CAChD,KAAM,CAAE,MAAAE,CAAK,EAAKH,EAAaC,CAAO,EACtCV,EAAUI,EAAK,QAAQQ,CAAK,EAAG,CAAE,UAAW,EAAI,CAAE,EAClD,GAAI,CACFV,EAAcU,EAA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,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAK2B,EAAY,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
+ "names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "pathToFileURL", "path", "DEFAULT_SHELL", "DEFAULT_DIST_INDEX", "STUB_CONTENT", "MIN_HTML_CHARS", "resolvePaths", "options", "root", "shell", "distIndex", "__name", "ensureSpaShellStub", "error", "readEmbeddedHtml", "problems", "source", "marker", "at", "literal", "html", "verifySpaShell", "distAssets", "referenced", "match", "asset", "CLI_SHAPES", "spaShellCli", "argv", "mode", "result", "problem"]
7
7
  }
@@ -1,4 +1,4 @@
1
- import{existsSync as b,readdirSync as $,readFileSync as O}from"node:fs";import{pathToFileURL as x}from"node:url";import g from"node:path";function m(e,t=""){if(e===null||typeof e!="object"||Array.isArray(e))return t?[t]:[];const i=Object.entries(e);return i.length===0?t?[t]:[]:i.flatMap(([n,r])=>m(r,t?`${t}.${n}`:n))}function y(e){const t=O(e,"utf8");return e.endsWith(".ts")?S(t,e):JSON.parse(t)}function C(e){let t="",i=!1,n=!1;for(let r=0;r<e.length;r+=1){const o=e[r];if(i){o===`
2
- `&&(i=!1);continue}const c=e[r+1];if(n){o==="*"&&c==="/"&&(n=!1,r+=1);continue}if(t!==""){if(o==="\\"){r+=1;continue}o===t&&(t="");continue}if(o==="-"&&c==="-"){i=!0;continue}if(o==="/"&&c==="*"){n=!0;continue}if(o==="'"||o==='"'||o==="`"){t=o;continue}const s=e[r-1];if(o==="="&&c!=="="&&c!==">"&&s!=="="&&s!=="!"&&s!=="<"&&s!==">"){const u=e.indexOf("{",r);return u===-1?-1:u}}return-1}function S(e,t){const i=C(e);if(i===-1)throw new Error(`${t} has no object literal`);let n=0,r=-1,o="",c=!1,s=!1;for(let a=i;a<e.length;a+=1){const l=e[a];if(c){l===`
3
- `&&(c=!1);continue}const h=e[a+1];if(s){l==="*"&&h==="/"&&(s=!1,a+=1);continue}if(o!==""){if(l==="\\"){a+=1;continue}l===o&&(o="");continue}if(l==="-"&&h==="-"){c=!0;continue}if(l==="/"&&h==="*"){s=!0;continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="{")n+=1;else if(l==="}"&&(n-=1,n===0)){r=a;break}}if(r===-1)throw new Error(`${t} has an unterminated object literal`);const E=e.slice(i,r+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(a,l)=>JSON.stringify(F(l))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(E)}catch(a){throw new Error(`${t} object literal could not be parsed: ${a instanceof Error?a.message:String(a)}`)}}function F(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
4
- `).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}const w={file:"json",module:"ts"};function d(e){return e==="auto"?["dir","file","module"]:[e]}function N(e,t){const i=[];d(t).includes("dir")&&i.push(...$(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name));for(const n of d(t)){if(n==="dir")continue;const r=w[n];i.push(...$(e).filter(o=>o.endsWith(`.${r}`)).map(o=>o.slice(0,-r.length-1)))}return i}function k(e,t,i){const n=[];d(i).includes("dir")&&n.push(g.join(e,t,"translation.json"));for(const r of d(i))r!=="dir"&&n.push(g.join(e,`${t}.${w[r]}`));return n.find(r=>b(r))}function j(e,t="en",i="auto"){const n=[];if(!b(e))return n.push({locale:t,problem:`${e} does not exist`}),{locales:[],keys:0,problems:n};const r=k(e,t,i);if(r===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 o;try{o=new Set(m(y(r)))}catch(s){return n.push({locale:t,problem:`${r}: ${s instanceof Error?s.message:String(s)}`}),{locales:[],keys:0,problems:n}}if(o.size===0)return n.push({locale:t,problem:`${r} has no keys \u2014 the base bundle is empty or unreadable`}),{locales:[t],keys:0,problems:n};const c=[...new Set([...N(e,i),t])].sort((s,u)=>s.localeCompare(u));for(const s of c){const u=k(e,s,i);if(u===void 0){n.push({locale:s,problem:"no bundle found"});continue}let p;try{p=new Set(m(y(u)))}catch(f){n.push({locale:s,problem:`${u}: ${f instanceof Error?f.message:String(f)}`});continue}for(const f of o)p.has(f)||n.push({locale:s,problem:`missing key: ${f}`});for(const f of p)o.has(f)||n.push({locale:s,problem:`extra key not in ${t}: ${f}`})}return{locales:c,keys:o.size,problems:n}}function A(e=process.argv.slice(2)){const t=e.find(o=>!o.startsWith("--"))??"apps/web/src/locales",i=e.find(o=>o.startsWith("--shape="))?.slice(8)??"auto",n=e.find(o=>o.startsWith("--base="))?.slice(7)??"en",r=j(t,n,i);if(r.problems.length>0){console.error(`Locale validation failed for ${t} (${r.problems.length} problem(s)):`);for(const o of r.problems)console.error(` - ${o.locale}: ${o.problem}`);return 1}return console.log(`Locale validation passed (${r.locales.length} locales, ${r.keys} keys each, shape ${i}).`),0}process.argv[1]!==void 0&&import.meta.url===x(process.argv[1]).href&&process.exit(A(process.argv.slice(2)));export{S as parseObjectLiteral,j as validateLocales,A as validateLocalesCli};
1
+ var x=Object.defineProperty;var f=(e,t)=>x(e,"name",{value:t,configurable:!0});import{existsSync as $,readdirSync as g,readFileSync as C}from"node:fs";import{pathToFileURL as F}from"node:url";import y from"node:path";function b(e,t=""){if(e===null||typeof e!="object"||Array.isArray(e))return t?[t]:[];const i=Object.entries(e);return i.length===0?t?[t]:[]:i.flatMap(([n,r])=>b(r,t?`${t}.${n}`:n))}f(b,"flatten");function S(e){const t=C(e,"utf8");return e.endsWith(".ts")?w(t,e):JSON.parse(t)}f(S,"readBundle");function N(e){let t="",i=!1,n=!1;for(let r=0;r<e.length;r+=1){const o=e[r];if(i){o===`
2
+ `&&(i=!1);continue}const c=e[r+1];if(n){o==="*"&&c==="/"&&(n=!1,r+=1);continue}if(t!==""){if(o==="\\"){r+=1;continue}o===t&&(t="");continue}if(o==="-"&&c==="-"){i=!0;continue}if(o==="/"&&c==="*"){n=!0;continue}if(o==="'"||o==='"'||o==="`"){t=o;continue}const s=e[r-1];if(o==="="&&c!=="="&&c!==">"&&s!=="="&&s!=="!"&&s!=="<"&&s!==">"){const p=e.indexOf("{",r);return p===-1?-1:p}}return-1}f(N,"objectLiteralStart");function w(e,t){const i=N(e);if(i===-1)throw new Error(`${t} has no object literal`);let n=0,r=-1,o="",c=!1,s=!1;for(let a=i;a<e.length;a+=1){const l=e[a];if(c){l===`
3
+ `&&(c=!1);continue}const m=e[a+1];if(s){l==="*"&&m==="/"&&(s=!1,a+=1);continue}if(o!==""){if(l==="\\"){a+=1;continue}l===o&&(o="");continue}if(l==="-"&&m==="-"){c=!0;continue}if(l==="/"&&m==="*"){s=!0;continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="{")n+=1;else if(l==="}"&&(n-=1,n===0)){r=a;break}}if(r===-1)throw new Error(`${t} has an unterminated object literal`);const O=e.slice(i,r+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(a,l)=>JSON.stringify(T(l))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(O)}catch(a){throw new Error(`${t} object literal could not be parsed: ${a instanceof Error?a.message:String(a)}`)}}f(w,"parseObjectLiteral");function T(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
4
+ `).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}f(T,"unescapeLiteral");const k={file:"json",module:"ts"};function h(e){return e==="auto"?["dir","file","module"]:[e]}f(h,"layouts");function W(e,t){const i=[];h(t).includes("dir")&&i.push(...g(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name));for(const n of h(t)){if(n==="dir")continue;const r=k[n];i.push(...g(e).filter(o=>o.endsWith(`.${r}`)).map(o=>o.slice(0,-r.length-1)))}return i}f(W,"tagsOnDisk");function j(e,t,i){const n=[];h(i).includes("dir")&&n.push(y.join(e,t,"translation.json"));for(const r of h(i))r!=="dir"&&n.push(y.join(e,`${t}.${k[r]}`));return n.find(r=>$(r))}f(j,"bundleFor");function A(e,t="en",i="auto"){const n=[];if(!$(e))return n.push({locale:t,problem:`${e} does not exist`}),{locales:[],keys:0,problems:n};const r=j(e,t,i);if(r===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 o;try{o=new Set(b(S(r)))}catch(s){return n.push({locale:t,problem:`${r}: ${s instanceof Error?s.message:String(s)}`}),{locales:[],keys:0,problems:n}}if(o.size===0)return n.push({locale:t,problem:`${r} has no keys \u2014 the base bundle is empty or unreadable`}),{locales:[t],keys:0,problems:n};const c=[...new Set([...W(e,i),t])].sort((s,p)=>s.localeCompare(p));for(const s of c){const p=j(e,s,i);if(p===void 0){n.push({locale:s,problem:"no bundle found"});continue}let d;try{d=new Set(b(S(p)))}catch(u){n.push({locale:s,problem:`${p}: ${u instanceof Error?u.message:String(u)}`});continue}for(const u of o)d.has(u)||n.push({locale:s,problem:`missing key: ${u}`});for(const u of d)o.has(u)||n.push({locale:s,problem:`extra key not in ${t}: ${u}`})}return{locales:c,keys:o.size,problems:n}}f(A,"validateLocales");function E(e=process.argv.slice(2)){const t=e.find(o=>!o.startsWith("--"))??"apps/web/src/locales",i=e.find(o=>o.startsWith("--shape="))?.slice(8)??"auto",n=e.find(o=>o.startsWith("--base="))?.slice(7)??"en",r=A(t,n,i);if(r.problems.length>0){console.error(`Locale validation failed for ${t} (${r.problems.length} problem(s)):`);for(const o of r.problems)console.error(` - ${o.locale}: ${o.problem}`);return 1}return console.log(`Locale validation passed (${r.locales.length} locales, ${r.keys} keys each, shape ${i}).`),0}f(E,"validateLocalesCli");process.argv[1]!==void 0&&import.meta.url===F(process.argv[1]).href&&process.exit(E(process.argv.slice(2)));export{w as parseObjectLiteral,A as validateLocales,E as validateLocalesCli};
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/scripts/validate-locales.ts"],
4
4
  "sourcesContent": ["/**\n * Validate that every locale bundle carries exactly the base locale's keys.\n *\n * Provenance: `scripts/validate_locales.{mjs,ts}` in Durable-DAV, Edge-Git and\n * Mail-Meow, and Edge-Sonic's `scripts/i18n/locale-checks.ts` +\n * `validate_locales.ts`, converged. All four copies agree on the contract:\n * flattened dotted key paths, two-way parity (missing AND extra), no empty values,\n * no stray placeholders.\n *\n * ### What the convergence added\n *\n * Edge-Sonic's is the only copy that checks what a value *is*. The rest compare\n * bundle to bundle, so with one shipped language the whole per-tag body is skipped\n * and the script reports `ALL OK` having checked nothing about the application — it\n * could not see that `libraries.scanPausedRequests` was used and absent, because\n * the string in the bundle did not exist to be wrong *about* anything. Hence\n * `--call-sites`: every `t('key')` under `apps/web/src` must resolve.\n *\n * Key **order** drift against the base is a warning, not a failure: locale files\n * are maintained by mirroring new keys into every file, and failing on order would\n * turn an otherwise-correct translation update into a CI failure about formatting.\n *\n * ### Three on-disk shapes, one checker\n *\n * The family ships bundles in three shapes, and the shape is an argument rather\n * than a fork of the script:\n *\n * - `auto` (default) — every layout below, tried in order, so a repo that has\n * half-migrated is reported rather than silently skipped;\n * - `dir` — `<locales-dir>/<tag>/translation.json`, the i18next layout used by\n * seven repos;\n * - `file` — `<locales-dir>/<tag>.json`, one flat file per tag;\n * - `module` — `<locales-dir>/<tag>.ts` exporting an object literal, which is the\n * shape `@rexezuge/i18n` uses for the backend string bundles. The literal is\n * extracted and normalised here, so the same gate covers the backend catalogs\n * the kit ships and the SPA bundles the repos do.\n */\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\n\n/**\nThe bundle layouts the checker understands.\n*/\ntype LocaleShape = 'auto' | 'dir' | 'file' | 'module';\n\n/**\nOne defect, kept as a locale plus a message so a caller can group them.\n*/\ninterface LocaleProblem {\n locale: string;\n problem: string;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface LocaleReport {\n locales: string[];\n keys: number;\n problems: LocaleProblem[];\n}\n\n/**\nEvery dotted key path in a bundle, depth first.\n*/\nfunction flatten(value: unknown, prefix = ''): string[] {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return prefix ? [prefix] : [];\n }\n const entries = Object.entries(value as Record<string, unknown>);\n if (entries.length === 0) return prefix ? [prefix] : [];\n return entries.flatMap(([key, child]) => flatten(child, prefix ? `${prefix}.${key}` : key));\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 * 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 baseKeys: Set<string>;\n try {\n baseKeys = new Set(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\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 keys: Set<string>;\n try {\n keys = new Set(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 (!keys.has(key)) problems.push({ locale, problem: `missing key: ${key}` });\n }\n for (const key of keys) {\n if (!baseKeys.has(key)) problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });\n }\n }\n\n return { locales, keys: baseKeys.size, problems };\n}\n\n/**\nCLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?])`.\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\n const report = validateLocales(dir, base, shape);\n if (report.problems.length > 0) {\n console.error(`Locale validation failed for ${dir} (${report.problems.length} problem(s)):`);\n for (const problem of report.problems) console.error(` - ${problem.locale}: ${problem.problem}`);\n return 1;\n }\n console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);\n return 0;\n}\n\nexport { parseObjectLiteral, validateLocales, validateLocalesCli };\nexport type { LocaleProblem, LocaleReport, LocaleShape };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(validateLocalesCli(process.argv.slice(2)));\n}\n"],
5
- "mappings": "AAqCA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,MAAoB,UACtD,OAAS,iBAAAC,MAAqB,WAC9B,OAAOC,MAAU,YA2BjB,SAASC,EAAQC,EAAgBC,EAAS,GAAE,CAC1C,GAAID,IAAU,MAAQ,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EACpE,OAAOC,EAAS,CAACA,CAAM,EAAI,CAAA,EAE7B,MAAMC,EAAU,OAAO,QAAQF,CAAgC,EAC/D,OAAIE,EAAQ,SAAW,EAAUD,EAAS,CAACA,CAAM,EAAI,CAAA,EAC9CC,EAAQ,QAAQ,CAAC,CAACC,EAAKC,CAAK,IAAML,EAAQK,EAAOH,EAAS,GAAGA,CAAM,IAAIE,CAAG,GAAKA,CAAG,CAAC,CAC5F,CAUA,SAASE,EAAWC,EAAY,CAC9B,MAAMC,EAASX,EAAaU,EAAM,MAAM,EAIxC,OAAOA,EAAK,SAAS,KAAK,EAAIE,EAAmBD,EAAQD,CAAI,EAAK,KAAK,MAAMC,CAAM,CACrF,CAsBA,SAASE,EAAmBF,EAAc,CACxC,IAAIG,EAAQ,GACRC,EAAgB,GAChBC,EAAiB,GACrB,QAASC,EAAQ,EAAGA,EAAQN,EAAO,OAAQM,GAAS,EAAG,CACrD,MAAMC,EAAOP,EAAOM,CAAK,EAEzB,GAAIF,EAAe,CACbG,IAAS;IAAMH,EAAgB,IACnC,QACF,CACA,MAAMI,EAAOR,EAAOM,EAAQ,CAAC,EAC7B,GAAID,EAAgB,CACdE,IAAS,KAAOC,IAAS,MAC3BH,EAAiB,GACjBC,GAAS,GAEX,QACF,CACA,GAAIH,IAAU,GAAI,CAChB,GAAII,IAAS,KAAM,CACjBD,GA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KAAMD,EAAS,KAAM,SAAAF,CAAQ,CACjD,CAKA,SAASO,EAAmBC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CACzE,MAAMC,EAAMD,EAAK,KAAME,GAAQ,CAACA,EAAI,WAAW,IAAI,CAAC,GAAK,uBACnDxB,EAASsB,EAAK,KAAME,GAAQA,EAAI,WAAW,UAAU,CAAC,GAAG,MAAM,CAAiB,GAAK,OACrFC,EAAOH,EAAK,KAAME,GAAQA,EAAI,WAAW,SAAS,CAAC,GAAG,MAAM,CAAgB,GAAK,KAEjFE,EAASd,EAAgBW,EAAKE,EAAMzB,CAAK,EAC/C,GAAI0B,EAAO,SAAS,OAAS,EAAG,CAC9B,QAAQ,MAAM,gCAAgCH,CAAG,KAAKG,EAAO,SAAS,MAAM,eAAe,EAC3F,UAAWC,KAAWD,EAAO,SAAU,QAAQ,MAAM,OAAOC,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EAChG,MAAO,EACT,CACA,eAAQ,IAAI,6BAA6BD,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB1B,CAAK,IAAI,EAC7G,CACT,CAYI,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQ/B,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAKoD,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
- "names": ["existsSync", "readdirSync", "readFileSync", "pathToFileURL", "path", "flatten", "value", "prefix", "entries", "key", "child", "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", "validateLocales", "baseLocale", "problems", "baseFile", "baseKeys", "locales", "a", "b", "keys", "validateLocalesCli",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EAAE,CAAE,CAEvG,CAEA,MAAO,CAAE,QAAA2C,EAAS,KAAMD,EAAS,KAAM,SAAAF,CAAQ,CACjD,CApDStC,EAAAoC,EAAA,mBAyDT,SAASS,EAAmBC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CACzE,MAAMC,EAAMD,EAAK,KAAME,GAAQ,CAACA,EAAI,WAAW,IAAI,CAAC,GAAK,uBACnDxB,EAASsB,EAAK,KAAME,GAAQA,EAAI,WAAW,UAAU,CAAC,GAAG,MAAM,CAAiB,GAAK,OACrFC,EAAOH,EAAK,KAAME,GAAQA,EAAI,WAAW,SAAS,CAAC,GAAG,MAAM,CAAgB,GAAK,KAEjFE,EAASd,EAAgBW,EAAKE,EAAMzB,CAAK,EAC/C,GAAI0B,EAAO,SAAS,OAAS,EAAG,CAC9B,QAAQ,MAAM,gCAAgCH,CAAG,KAAKG,EAAO,SAAS,MAAM,eAAe,EAC3F,UAAWC,KAAWD,EAAO,SAAU,QAAQ,MAAM,OAAOC,EAAQ,MAAM,KAAKA,EAAQ,OAAO,EAAE,EAChG,MAAO,EACT,CACA,eAAQ,IAAI,6BAA6BD,EAAO,QAAQ,MAAM,aAAaA,EAAO,IAAI,qBAAqB1B,CAAK,IAAI,EAC7G,CACT,CAbSxB,EAAA6C,EAAA,sBAyBL,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQrD,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAKqD,EAAmB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
+ "names": ["existsSync", "readdirSync", "readFileSync", "pathToFileURL", "path", "flatten", "value", "prefix", "entries", "key", "child", "__name", "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", "validateLocales", "baseLocale", "problems", "baseFile", "baseKeys", "locales", "a", "b", "keys", "validateLocalesCli", "argv", "dir", "arg", "base", "report", "problem"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{createHash as S}from"node:crypto";import{pathToFileURL as w}from"node:url";import{existsSync as b,readFileSync as u,readdirSync as M,writeFileSync as _}from"node:fs";import p from"node:path";const a="migrations.lock.json",$=/^(\d{4})_[a-z0-9_]+\.sql$/,O=/^\d{4}_squash\.sql$/,d=1;function k(r){return S("sha256").update(r,"utf8").digest("hex")}function x(r){let t;for(const o of r)O.test(o)&&(t===void 0||o>t)&&(t=o);return t}function m(r,t){return t!==void 0&&r<=t}function y(r){const t=[];if(!b(r))return t.push({problem:`${r} does not exist`}),{files:[],problems:t,lock:null};const o=M(r).filter(e=>e.endsWith(".sql")).sort((e,i)=>e.localeCompare(i));for(const e of o)$.test(e)||t.push({problem:`${e} does not match NNNN_snake_case.sql`});const s=x(o),c=o.map(e=>$.exec(e)?.[1]);for(let e=1;e<c.length;e+=1){const i=c[e-1],f=c[e];i!==void 0&&f!==void 0&&f<=i&&t.push({problem:`${o[e]??"?"} sorts at or before ${o[e-1]??"?"} \u2014 D1 applies in filename order, so one of the two can never run`})}if(s===void 0)for(const[e,i]of c.entries()){const f=String(e+1).padStart(4,"0");i!==f&&t.push({problem:`migration numbering is not contiguous: expected ${f}_*.sql, found ${o[e]??"?"}`})}const l=p.join(r,a);let n=null;if(b(l))try{n=JSON.parse(u(l,"utf8"))}catch{t.push({problem:`${a} is not valid JSON`})}return{files:o,problems:t,lock:n}}function E(r,t,o,s){const c=n=>k(u(p.join(r,n),"utf8"));if(o===null)return{version:d,...s!==void 0&&{baseline:s},migrations:t.map(n=>({name:n,sha256:c(n)}))};const l=new Map;for(const n of t){const e=o.migrations.find(i=>i.name===n);e!==void 0&&l.set(n,n===s?c(n):e.sha256)}for(const n of t)!l.has(n)&&o.migrations.every(e=>e.name!==n)&&l.set(n,c(n));for(const n of o.migrations)!t.includes(n.name)&&!m(n.name,s)&&l.set(n.name,n.sha256);return{version:d,...s!==void 0&&{baseline:s},migrations:[...l].sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>({name:n,sha256:e}))}}function v(r,t={}){const o=y(r),s=x(o.files);if(o.problems.length>0)return o;if(t.write===!0){const e=E(r,o.files,o.lock,s),i=`${JSON.stringify(e,null,2)}
2
- `,f=p.join(r,a);let h=null;try{h=u(f,"utf8")}catch(g){if(g?.code!=="ENOENT")throw g}return h!==i&&_(f,i,"utf8"),o.lock=e,o}const c=o.lock;if(c===null)return o.problems.push({problem:`${a} is missing \u2014 run migrations:lock`}),o;const l=new Map(c.migrations.map(e=>[e.name,e.sha256]));for(const e of o.files){const i=l.get(e);if(i===void 0){o.problems.push({problem:`${e} has no lock entry \u2014 run migrations:lock`});continue}if(m(e,s))continue;const f=k(u(p.join(r,e),"utf8"));f!==i&&o.problems.push({problem:`${e} changed after locking (expected ${i.slice(0,12)}\u2026, got ${f.slice(0,12)}\u2026)`})}for(const e of c.migrations)o.files.includes(e.name)||m(e.name,s)||o.problems.push({problem:`${e.name} is in the lock but no longer exists`});const n=[...l.keys()].sort((e,i)=>e.localeCompare(i)).at(-1);if(n!==void 0)for(const e of o.files)e<n&&!l.has(e)&&o.problems.push({problem:`${e} sorts before ${n}, which is already locked \u2014 D1 applies in filename order, so it would never run on a database that has applied ${n}`});return o}function N(r=process.argv.slice(2)){const t=r.find(c=>!c.startsWith("--"))??"migrations",o=r.includes("--write"),s=v(t,{write:o});if(s.problems.length>0){console.error(`Migration validation failed for ${t}:`);for(const c of s.problems)console.error(` - ${c.problem}`);return 1}return o?(console.log(`Migration lock written (${s.files.length} files).`),0):(console.log(`Migration validation passed (${s.files.length} files, lock in sync).`),0)}process.argv[1]!==void 0&&import.meta.url===w(process.argv[1]).href&&process.exit(N(process.argv.slice(2)));export{a as LOCK_NAME,d as LOCK_VERSION,x as baselineOf,y as inspectMigrations,v as verifyMigrations,N as verifyMigrationsCli};
1
+ var w=Object.defineProperty;var a=(r,t)=>w(r,"name",{value:t,configurable:!0});import{createHash as M}from"node:crypto";import{pathToFileURL as _}from"node:url";import{existsSync as $,readFileSync as p,readdirSync as O,writeFileSync as E}from"node:fs";import d from"node:path";const u="migrations.lock.json",k=/^(\d{4})_[a-z0-9_]+\.sql$/,q=/^\d{4}_squash\.sql$/,m=1;function x(r){return M("sha256").update(r,"utf8").digest("hex")}a(x,"sha256Hex");function y(r){let t;for(const o of r)q.test(o)&&(t===void 0||o>t)&&(t=o);return t}a(y,"baselineOf");function h(r,t){return t!==void 0&&r<=t}a(h,"isSubsumed");function v(r){const t=[];if(!$(r))return t.push({problem:`${r} does not exist`}),{files:[],problems:t,lock:null};const o=O(r).filter(e=>e.endsWith(".sql")).sort((e,i)=>e.localeCompare(i));for(const e of o)k.test(e)||t.push({problem:`${e} does not match NNNN_snake_case.sql`});const s=y(o),c=o.map(e=>k.exec(e)?.[1]);for(let e=1;e<c.length;e+=1){const i=c[e-1],f=c[e];i!==void 0&&f!==void 0&&f<=i&&t.push({problem:`${o[e]??"?"} sorts at or before ${o[e-1]??"?"} \u2014 D1 applies in filename order, so one of the two can never run`})}if(s===void 0)for(const[e,i]of c.entries()){const f=String(e+1).padStart(4,"0");i!==f&&t.push({problem:`migration numbering is not contiguous: expected ${f}_*.sql, found ${o[e]??"?"}`})}const l=d.join(r,u);let n=null;if($(l))try{n=JSON.parse(p(l,"utf8"))}catch{t.push({problem:`${u} is not valid JSON`})}return{files:o,problems:t,lock:n}}a(v,"inspectMigrations");function C(r,t,o,s){const c=a(n=>x(p(d.join(r,n),"utf8")),"digestOf");if(o===null)return{version:m,...s!==void 0&&{baseline:s},migrations:t.map(n=>({name:n,sha256:c(n)}))};const l=new Map;for(const n of t){const e=o.migrations.find(i=>i.name===n);e!==void 0&&l.set(n,n===s?c(n):e.sha256)}for(const n of t)!l.has(n)&&o.migrations.every(e=>e.name!==n)&&l.set(n,c(n));for(const n of o.migrations)!t.includes(n.name)&&!h(n.name,s)&&l.set(n.name,n.sha256);return{version:m,...s!==void 0&&{baseline:s},migrations:[...l].sort(([n],[e])=>n.localeCompare(e)).map(([n,e])=>({name:n,sha256:e}))}}a(C,"buildUpdatedLock");function N(r,t={}){const o=v(r),s=y(o.files);if(o.problems.length>0)return o;if(t.write===!0){const e=C(r,o.files,o.lock,s),i=`${JSON.stringify(e,null,2)}
2
+ `,f=d.join(r,u);let g=null;try{g=p(f,"utf8")}catch(b){if(b?.code!=="ENOENT")throw b}return g!==i&&E(f,i,"utf8"),o.lock=e,o}const c=o.lock;if(c===null)return o.problems.push({problem:`${u} is missing \u2014 run migrations:lock`}),o;const l=new Map(c.migrations.map(e=>[e.name,e.sha256]));for(const e of o.files){const i=l.get(e);if(i===void 0){o.problems.push({problem:`${e} has no lock entry \u2014 run migrations:lock`});continue}if(h(e,s))continue;const f=x(p(d.join(r,e),"utf8"));f!==i&&o.problems.push({problem:`${e} changed after locking (expected ${i.slice(0,12)}\u2026, got ${f.slice(0,12)}\u2026)`})}for(const e of c.migrations)o.files.includes(e.name)||h(e.name,s)||o.problems.push({problem:`${e.name} is in the lock but no longer exists`});const n=[...l.keys()].sort((e,i)=>e.localeCompare(i)).at(-1);if(n!==void 0)for(const e of o.files)e<n&&!l.has(e)&&o.problems.push({problem:`${e} sorts before ${n}, which is already locked \u2014 D1 applies in filename order, so it would never run on a database that has applied ${n}`});return o}a(N,"verifyMigrations");function S(r=process.argv.slice(2)){const t=r.find(c=>!c.startsWith("--"))??"migrations",o=r.includes("--write"),s=N(t,{write:o});if(s.problems.length>0){console.error(`Migration validation failed for ${t}:`);for(const c of s.problems)console.error(` - ${c.problem}`);return 1}return o?(console.log(`Migration lock written (${s.files.length} files).`),0):(console.log(`Migration validation passed (${s.files.length} files, lock in sync).`),0)}a(S,"verifyMigrationsCli");process.argv[1]!==void 0&&import.meta.url===_(process.argv[1]).href&&process.exit(S(process.argv.slice(2)));export{u as LOCK_NAME,m as LOCK_VERSION,y as baselineOf,v as inspectMigrations,N as verifyMigrations,S as verifyMigrationsCli};
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/scripts/verify-migrations.ts"],
4
4
  "sourcesContent": ["/**\n * Verify the migration set is complete, ordered, and locked; write the lock.\n *\n * Provenance: Edge-Sonic's `scripts/migrations/{verify-migrations,lock-check}.ts`\n * (the rule module plus its entrypoint) and AWS's `verify-migrations.ts`,\n * converged. Every copy checks the same properties of a `migrations/` directory;\n * they differ in lock-file naming, in whether the lock is enforced on CI, and in\n * how much of D1's ordering semantics they encode.\n *\n * ### Why a checksum lock at all\n *\n * D1 records *which* migrations it has applied — the filename and a timestamp —\n * but not *what the file contained* when it applied them. So editing a migration\n * that has already run is not caught by anything: the deploy still succeeds, the\n * local database built from the baseline plus the edited file picks up the new\n * statements, and production keeps the schema it had. The two databases then\n * differ silently and permanently, and the next migration that assumes the newer\n * shape fails only in production. A committed digest per file turns that into a\n * CI failure.\n *\n * ### What the checks are, and where each comes from\n *\n * - **`NNNN_snake_case.sql`** (AWS) — the numbering *is* the ordering: D1 sorts by\n * filename, so a file that sorts *after* the ones already applied is the only\n * kind that can be introduced safely.\n * - **Contiguous prefixes** (AWS) — a hole means one database applied 0001 and\n * 0003 while another applied only 0001, and nothing downstream can tell which.\n * Checked **only when no squash baseline exists**: a squash legitimately\n * absorbs its predecessors, so numbering restarts wherever it starts, and a\n * contiguity rule that fires on a squash is a rule that blocks the squash.\n * - **One entry per file** (all) — a file with no recorded digest is one nothing\n * can say anything about.\n * - **Digest unchanged** (all) — the edited-after-locking failure.\n * - **No orphan entries** (Edge-Sonic) — a locked file that is gone has been\n * applied to a live database and is no longer reproducible from this repo.\n * - **Strictly increasing prefixes** (Edge-Sonic's `out-of-order`) — a file\n * sorting *before* the newest locked one can never reach a database that has\n * applied that newest one, so its statements would only run on a fresh build.\n * - **No duplicate prefixes** (Edge-Sonic) — two files numbered `0033_` are not a\n * style problem: D1 orders them by the rest of the filename, so which one lands\n * on a given database depends on a lexicographic tiebreak nobody intended.\n *\n * ### The squash baseline\n *\n * `0008_squash.sql` holds the combined schema of every migration before it, and\n * those files are deleted when it is created. A later squash repeats that. So a\n * squash legitimately (a) rewrites one file and (b) removes files the lock still\n * lists, and neither may be reported as drift. The baseline is the\n * highest-numbered `NNNN_squash.sql` **on disk**, never the value the lock claims\n * — deriving it means a stale or forged `baseline` cannot widen the exempt set.\n *\n * ### The one write path\n *\n * `--write` is add-only where it counts: it records unlocked files, refreshes the\n * baseline's own entry, and drops entries the baseline absorbed. Every other\n * entry is left exactly as it is, so an incremental `edited` finding **survives a\n * `--write`** — re-baselining one means deleting its entry by hand, which shows\n * up in the diff. There is deliberately no `--force`, because a write that could\n * bless a drift would be the operator blessing their own edit.\n */\nimport { createHash } from 'node:crypto';\nimport { pathToFileURL } from 'node:url';\nimport { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\n\n/**\nOne migration as the lock records it.\n*/\ninterface MigrationEntry {\n name: string;\n sha256: string;\n}\n\n/**\nThe parsed `migrations/migrations.lock.json`.\n*/\ninterface MigrationLockFile {\n version: 1;\n /**\n * The squashed-baseline filename, when the repo has squashed.\n *\n * Everything at or before it is exempt from the `edited` and `orphan` checks,\n * because that is exactly the set a squash rewrites or absorbs.\n */\n baseline?: string;\n migrations: MigrationEntry[];\n}\n\n/**\nOne failure, phrased for the operator.\n*/\ninterface MigrationProblem {\n problem: string;\n}\n\n/**\nThe outcome of one run.\n*/\ninterface MigrationReport {\n /**\n Migration filenames, in apply order.\n */\n files: string[];\n problems: MigrationProblem[];\n /**\n The lock as it reads after the run.\n */\n lock: MigrationLockFile | null;\n}\n\n/**\n * The lock's filename, beside the `.sql` files.\n *\n * Named `migrations.lock.json` rather than `migrations.json` so it cannot be\n * mistaken for a migration: wrangler applies `*.sql` only, and a lock named like\n * one would be a deploy-time mystery.\n */\nconst LOCK_NAME = 'migrations.lock.json';\n\n/**\nThe filename shape every migration must have. `NNNN_` is fixed at four digits.\n*/\nconst NAME_PATTERN = /^(\\d{4})_[a-z0-9_]+\\.sql$/;\n\n/**\nThe squashed-baseline shape. The highest-numbered match is the baseline.\n*/\nconst SQUASH_PATTERN = /^\\d{4}_squash\\.sql$/;\n\n/**\nThe lock's format version. Bumped only on an incompatible shape change.\n*/\nconst LOCK_VERSION = 1;\n\nfunction sha256Hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n\n/**\n * The highest-numbered `NNNN_squash.sql` on disk, or `undefined` when the repo\n * has not squashed — in which case every migration is incremental and therefore\n * every one of them is immutable.\n */\nexport function baselineOf(files: readonly string[]): string | undefined {\n let highest: string | undefined;\n for (const name of files) {\n if (SQUASH_PATTERN.test(name) && (highest === undefined || name > highest)) {\n highest = name;\n }\n }\n return highest;\n}\n\n/**\nTrue when `name` is at or before the baseline, i.e. the set a squash absorbs.\n*/\nfunction isSubsumed(name: string, baseline: string | undefined): boolean {\n return baseline !== undefined && name <= baseline;\n}\n\n/**\n * Read the migration set and validate its shape without consulting the lock.\n *\n * The lock is read here too, so one walk answers both \"what is on disk\" and \"what\n * is recorded\"; a lock that is merely *absent* is reported by `verifyMigrations`\n * rather than here, because that is the bootstrap case rather than a defect.\n */\nfunction inspectMigrations(migrationsDir: string): MigrationReport {\n const problems: MigrationProblem[] = [];\n if (!existsSync(migrationsDir)) {\n problems.push({ problem: `${migrationsDir} does not exist` });\n return { files: [], problems, lock: null };\n }\n\n // Top level only, matching wrangler's default `${migrationsDir}/*.sql`, so the\n // lock describes exactly the set wrangler will run. `migrations.lock.json` is\n // not one of them, because it is not a `.sql` file.\n const files = readdirSync(migrationsDir)\n .filter((name) => name.endsWith('.sql'))\n .sort((left, right) => left.localeCompare(right));\n\n for (const name of files) {\n if (!NAME_PATTERN.test(name)) {\n problems.push({ problem: `${name} does not match NNNN_snake_case.sql` });\n }\n }\n\n const baseline = baselineOf(files);\n const prefixes = files.map((name) => NAME_PATTERN.exec(name)?.[1]);\n\n // Strictly increasing: the property D1 actually depends on. A duplicate or a\n // descending prefix means two files compete for the same slot in the apply\n // order, and which one wins is a lexicographic tiebreak nobody intended.\n for (let index = 1; index < prefixes.length; index += 1) {\n const previous = prefixes[index - 1];\n const current = prefixes[index];\n if (previous !== undefined && current !== undefined && current <= previous) {\n problems.push({\n problem: `${files[index] ?? '?'} sorts at or before ${files[index - 1] ?? '?'} — D1 applies in filename order, so one of the two can never run`,\n });\n }\n }\n\n // Contiguity is checked only with no squash on disk: a squash deletes the files\n // it absorbs, so numbering restarts wherever it starts and a hole is the\n // expected shape rather than a defect.\n if (baseline === undefined) {\n for (const [index, prefix] of prefixes.entries()) {\n const expected = String(index + 1).padStart(4, '0');\n if (prefix !== expected) {\n problems.push({\n problem: `migration numbering is not contiguous: expected ${expected}_*.sql, found ${files[index] ?? '?'}`,\n });\n }\n }\n }\n\n const lockPath = path.join(migrationsDir, LOCK_NAME);\n let lock: MigrationLockFile | null = null;\n if (existsSync(lockPath)) {\n try {\n lock = JSON.parse(readFileSync(lockPath, 'utf8')) as MigrationLockFile;\n } catch {\n problems.push({ problem: `${LOCK_NAME} is not valid JSON` });\n }\n }\n\n return { files, problems, lock };\n}\n\n/**\n * The lock as `--write` would leave it.\n *\n * `null` when the existing lock cannot be trusted as a base, which is exactly\n * when a `--write` must refuse rather than overwrite contents it failed to\n * understand. A lock that is merely *absent* is not malformed: that is the\n * bootstrap case, and it is built from disk like any other.\n */\nfunction buildUpdatedLock(\n migrationsDir: string,\n files: readonly string[],\n existing: MigrationLockFile | null,\n baseline: string | undefined,\n): MigrationLockFile | null {\n const digestOf = (name: string): string => sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n\n if (existing === null) {\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: files.map((name) => ({ name, sha256: digestOf(name) })),\n };\n }\n\n const kept = new Map<string, string>();\n for (const file of files) {\n const recorded = existing.migrations.find((entry) => entry.name === file);\n if (recorded === undefined) continue;\n // The baseline is the one file a squash is allowed to rewrite.\n kept.set(file, file === baseline ? digestOf(file) : recorded.sha256);\n }\n // Unlocked files are added — that is the new-migration case. Every other entry\n // is carried across untouched, so an `edited` finding survives the write.\n for (const file of files) {\n if (!kept.has(file) && existing.migrations.every((entry) => entry.name !== file)) {\n kept.set(file, digestOf(file));\n }\n }\n // Entries the baseline absorbed are dropped: committing a squash looks exactly\n // like this, and neither it nor a rewritten baseline can hide a divergence,\n // because a database that applied those files already has them recorded in D1's\n // own `d1_migrations`.\n for (const entry of existing.migrations) {\n if (!files.includes(entry.name) && !isSubsumed(entry.name, baseline)) {\n kept.set(entry.name, entry.sha256);\n }\n }\n\n return {\n version: LOCK_VERSION,\n ...(baseline !== undefined && { baseline }),\n migrations: [...kept].sort(([left], [right]) => left.localeCompare(right)).map(([name, sha256]) => ({ name, sha256 })),\n };\n}\n\n/**\nVerify (or with `write: true`, record) the lock against the files.\n*/\nfunction verifyMigrations(migrationsDir: string, options: { write?: boolean } = {}): MigrationReport {\n const report = inspectMigrations(migrationsDir);\n const baseline = baselineOf(report.files);\n\n // A malformed lock is a finding in its own right, and a `--write` must not\n // overwrite contents it failed to understand.\n if (report.problems.length > 0) {\n return report;\n }\n\n if (options.write === true) {\n const updated = buildUpdatedLock(migrationsDir, report.files, report.lock, baseline);\n const next = `${JSON.stringify(updated, null, 2)}\\n`;\n const lockfile = path.join(migrationsDir, LOCK_NAME);\n let before: string | null = null;\n try {\n before = readFileSync(lockfile, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {\n throw error;\n }\n }\n if (before !== next) {\n writeFileSync(lockfile, next, 'utf8');\n }\n report.lock = updated;\n return report;\n }\n\n const lock = report.lock;\n if (lock === null) {\n report.problems.push({ problem: `${LOCK_NAME} is missing — run migrations:lock` });\n return report;\n }\n\n const recorded = new Map(lock.migrations.map((entry) => [entry.name, entry.sha256]));\n for (const name of report.files) {\n const expected = recorded.get(name);\n if (expected === undefined) {\n report.problems.push({ problem: `${name} has no lock entry — run migrations:lock` });\n continue;\n }\n // At or before the baseline, a squash rewrites its own file, and that is the\n // whole reason a baseline exists.\n if (isSubsumed(name, baseline)) continue;\n const actual = sha256Hex(readFileSync(path.join(migrationsDir, name), 'utf8'));\n if (actual !== expected) {\n report.problems.push({\n problem: `${name} changed after locking (expected ${expected.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,\n });\n }\n }\n\n for (const entry of lock.migrations) {\n if (report.files.includes(entry.name) || isSubsumed(entry.name, baseline)) continue;\n report.problems.push({ problem: `${entry.name} is in the lock but no longer exists` });\n }\n\n // A file sorting before the newest locked one can never reach a database that\n // has already applied that newest one, so its statements would only run on a\n // fresh build — the same silent split the checksum exists to prevent.\n const newest = [...recorded.keys()].sort((left, right) => left.localeCompare(right)).at(-1);\n if (newest !== undefined) {\n for (const name of report.files) {\n if (name < newest && !recorded.has(name)) {\n report.problems.push({\n problem: `${name} sorts before ${newest}, which is already locked — D1 applies in filename order, so it would never run on a database that has applied ${newest}`,\n });\n }\n }\n }\n\n return report;\n}\n\n/**\nCLI entry: `verifyMigrationsCli(['[migrations-dir]?', '--write'?'])`.\n*/\nfunction verifyMigrationsCli(argv: readonly string[] = process.argv.slice(2)): number {\n const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'migrations';\n const write = argv.includes('--write');\n const report = verifyMigrations(dir, { write });\n if (report.problems.length > 0) {\n console.error(`Migration validation failed for ${dir}:`);\n for (const problem of report.problems) console.error(` - ${problem.problem}`);\n return 1;\n }\n if (write) {\n console.log(`Migration lock written (${report.files.length} files).`);\n return 0;\n }\n console.log(`Migration validation passed (${report.files.length} files, lock in sync).`);\n return 0;\n}\n\nexport { inspectMigrations, verifyMigrations, verifyMigrationsCli, LOCK_NAME, LOCK_VERSION };\nexport type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationReport };\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {\n process.exit(verifyMigrationsCli(process.argv.slice(2)));\n}\n"],
5
- "mappings": "AA4DA,OAAS,cAAAA,MAAkB,cAC3B,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,iBAAAC,MAAqB,UACrE,OAAOC,MAAU,YAsDjB,MAAMC,EAAY,uBAKZC,EAAe,4BAKfC,EAAiB,sBAKjBC,EAAe,EAErB,SAASC,EAAUC,EAAe,CAChC,OAAOZ,EAAW,QAAQ,EAAE,OAAOY,EAAS,MAAM,EAAE,OAAO,KAAK,CAClE,CAOM,SAAUC,EAAWC,EAAwB,CACjD,IAAIC,EACJ,UAAWC,KAAQF,EACbL,EAAe,KAAKO,CAAI,IAAMD,IAAY,QAAaC,EAAOD,KAChEA,EAAUC,GAGd,OAAOD,CACT,CAKA,SAASE,EAAWD,EAAcE,EAA4B,CAC5D,OAAOA,IAAa,QAAaF,GAAQE,CAC3C,CASA,SAASC,EAAkBC,EAAqB,CAC9C,MAAMC,EAA+B,CAAA,EACrC,GAAI,CAACnB,EAAWkB,CAAa,EAC3B,OAAAC,EAAS,KAAK,CAAE,QAAS,GAAGD,CAAa,iBAAiB,CAAE,EACrD,CAAE,MAAO,CAAA,EAAI,SAAAC,EAAU,KAAM,IAAI,EAM1C,MAAMP,EAAQV,EAAYgB,CAAa,EACpC,OAAQJ,GAASA,EAAK,SAAS,MAAM,CAAC,EACtC,KAAK,CAACM,EAAMC,IAAUD,EAAK,cAAcC,CAAK,CAAC,EAElD,UAAWP,KAAQF,EACZN,EAAa,KAAKQ,CAAI,GACzBK,EAAS,KAAK,CAAE,QAAS,GAAGL,CAAI,qCAAqC,CAAE,EAI3E,MAAME,EAAWL,EAAWC,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GAAU,CAACZ,EAAS,IAAIrB,CAAI,GACrC0B,EAAO,SAAS,KAAK,CACnB,QAAS,GAAG1B,CAAI,iBAAiBiC,CAAM,uHAAkHA,CAAM,GAChK,EAKP,OAAOP,CACT,CAKA,SAASQ,EAAoBC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CAC1E,MAAMC,EAAMD,EAAK,KAAME,GAAQ,CAACA,EAAI,WAAW,IAAI,CAAC,GAAK,aACnDC,EAAQH,EAAK,SAAS,SAAS,EAC/BT,EAASF,EAAiBY,EAAK,CAAE,MAAAE,CAAK,CAAE,EAC9C,GAAIZ,EAAO,SAAS,OAAS,EAAG,CAC9B,QAAQ,MAAM,mCAAmCU,CAAG,GAAG,EACvD,UAAWG,KAAWb,EAAO,SAAU,QAAQ,MAAM,OAAOa,EAAQ,OAAO,EAAE,EAC7E,MAAO,EACT,CACA,OAAID,GACF,QAAQ,IAAI,2BAA2BZ,EAAO,MAAM,MAAM,UAAU,EAC7D,IAET,QAAQ,IAAI,gCAAgCA,EAAO,MAAM,MAAM,wBAAwB,EAChF,EACT,CAYI,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQzC,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAKiD,EAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
- "names": ["createHash", "pathToFileURL", "existsSync", "readFileSync", "readdirSync", "writeFileSync", "path", "LOCK_NAME", "NAME_PATTERN", "SQUASH_PATTERN", "LOCK_VERSION", "sha256Hex", "content", "baselineOf", "files", "highest", "name", "isSubsumed", "baseline", "inspectMigrations", "migrationsDir", "problems", "left", "right", "prefixes", "index", "previous", "current", "prefix", "expected", "lockPath", "lock", "buildUpdatedLock", "existing", "digestOf", "kept", "file", "recorded", "entry", "sha256", "verifyMigrations", "options", "report", "updated", "next", "lockfile", "before", "error", "actual", "newest", "verifyMigrationsCli", "argv", "dir", "arg", "write", "problem"]
5
+ "mappings": "+EA4DA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CAAM,uHAAkHA,CAAM,GAChK,EAKP,OAAOP,CACT,CAzES9B,EAAA4B,EAAA,oBA8ET,SAASU,EAAoBC,EAA0B,QAAQ,KAAK,MAAM,CAAC,EAAC,CAC1E,MAAMC,EAAMD,EAAK,KAAME,GAAQ,CAACA,EAAI,WAAW,IAAI,CAAC,GAAK,aACnDC,EAAQH,EAAK,SAAS,SAAS,EAC/BT,EAASF,EAAiBY,EAAK,CAAE,MAAAE,CAAK,CAAE,EAC9C,GAAIZ,EAAO,SAAS,OAAS,EAAG,CAC9B,QAAQ,MAAM,mCAAmCU,CAAG,GAAG,EACvD,UAAWG,KAAWb,EAAO,SAAU,QAAQ,MAAM,OAAOa,EAAQ,OAAO,EAAE,EAC7E,MAAO,EACT,CACA,OAAID,GACF,QAAQ,IAAI,2BAA2BZ,EAAO,MAAM,MAAM,UAAU,EAC7D,IAET,QAAQ,IAAI,gCAAgCA,EAAO,MAAM,MAAM,wBAAwB,EAChF,EACT,CAfS9B,EAAAsC,EAAA,uBA2BL,QAAQ,KAAK,CAAC,IAAM,QAAa,YAAY,MAAQlD,EAAc,QAAQ,KAAK,CAAC,CAAC,EAAE,MACtF,QAAQ,KAAKkD,EAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
+ "names": ["createHash", "pathToFileURL", "existsSync", "readFileSync", "readdirSync", "writeFileSync", "path", "LOCK_NAME", "NAME_PATTERN", "SQUASH_PATTERN", "LOCK_VERSION", "sha256Hex", "content", "__name", "baselineOf", "files", "highest", "name", "isSubsumed", "baseline", "inspectMigrations", "migrationsDir", "problems", "left", "right", "prefixes", "index", "previous", "current", "prefix", "expected", "lockPath", "lock", "buildUpdatedLock", "existing", "digestOf", "kept", "file", "recorded", "entry", "sha256", "verifyMigrations", "options", "report", "updated", "next", "lockfile", "before", "error", "actual", "newest", "verifyMigrationsCli", "argv", "dir", "arg", "write", "problem"]
7
7
  }
@@ -1,3 +1,3 @@
1
- import{execFileSync as c}from"node:child_process";function d(r,e){try{return c("pnpm",["exec","wrangler",...r],{encoding:"utf8",stdio:[e===void 0?"ignore":"pipe","pipe","pipe"],...e!==void 0&&{input:e}})}catch(n){const t=n,o=t.stdout?t.stdout.toString():"",s=t.stderr?t.stderr.toString():"";throw new Error(`Command failed: pnpm exec wrangler ${r.join(" ")}
2
- ${o}${s||t.message||""}`)}}function i(r,e){try{const n=JSON.parse(r);if(Array.isArray(n))return n}catch{}throw new Error(`Expected JSON array output from ${e}. Output:
3
- ${r}`)}export{i as parseJsonArray,d as runWrangler};
1
+ var a=Object.defineProperty;var o=(r,e)=>a(r,"name",{value:e,configurable:!0});import{execFileSync as d}from"node:child_process";function u(r,e){try{return d("pnpm",["exec","wrangler",...r],{encoding:"utf8",stdio:[e===void 0?"ignore":"pipe","pipe","pipe"],...e!==void 0&&{input:e}})}catch(n){const t=n,s=t.stdout?t.stdout.toString():"",c=t.stderr?t.stderr.toString():"";throw new Error(`Command failed: pnpm exec wrangler ${r.join(" ")}
2
+ ${s}${c||t.message||""}`)}}o(u,"runWrangler");function f(r,e){try{const n=JSON.parse(r);if(Array.isArray(n))return n}catch{}throw new Error(`Expected JSON array output from ${e}. Output:
3
+ ${r}`)}o(f,"parseJsonArray");export{f as parseJsonArray,u as runWrangler};
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../src/scripts/wrangler-config/cli.ts"],
4
4
  "sourcesContent": ["/**\n * Running `wrangler` and reading its output.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/cli.ts`.\n */\n\nimport { execFileSync } from 'node:child_process';\n\n/**\n * Runs a wrangler subcommand and returns stdout.\n *\n * Arguments are passed as an argv array rather than interpolated into a shell\n * string, so a value containing shell metacharacters cannot alter the command.\n */\nexport function runWrangler(args: readonly string[], input?: string): string {\n try {\n // `pnpm` is resolved from PATH deliberately: the scripts run on CI runners and\n // in local shells, and both resolve it the same way.\n // eslint-disable-next-line sonarjs/no-os-command-from-path\n return execFileSync('pnpm', ['exec', 'wrangler', ...args], {\n encoding: 'utf8',\n stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],\n ...(input !== undefined && { input }),\n });\n } catch (error: unknown) {\n const maybeProcessError = error as { stdout?: string | Buffer; stderr?: string | Buffer; message?: string };\n const stdout: string = maybeProcessError.stdout ? maybeProcessError.stdout.toString() : '';\n const stderr: string = maybeProcessError.stderr ? maybeProcessError.stderr.toString() : '';\n throw new Error(`Command failed: pnpm exec wrangler ${args.join(' ')}\\n${stdout}${stderr || maybeProcessError.message || ''}`);\n }\n}\n\n/**\n * Parses a JSON array from a command's stdout, naming the command on failure.\n *\n * Several wrangler subcommands print a human-readable table when they detect a\n * TTY, so \"not JSON\" is an expected outcome that the caller often has a table\n * parser for. Passing the command description turns that into a catchable,\n * self-explanatory error instead of an unlabelled `SyntaxError`.\n */\nexport function parseJsonArray<T>(output: string, commandDescription: string): T[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (Array.isArray(parsed)) {\n return parsed as T[];\n }\n } catch {\n // Fall through to the explicit error below.\n }\n throw new Error(`Expected JSON array output from ${commandDescription}. Output:\\n${output}`);\n}\n"],
5
- "mappings": "AAMA,OAAS,gBAAAA,MAAoB,qBAQvB,SAAUC,EAAYC,EAAyBC,EAAc,CACjE,GAAI,CAIF,OAAOH,EAAa,OAAQ,CAAC,OAAQ,WAAY,GAAGE,CAAI,EAAG,CACzD,SAAU,OACV,MAAO,CAACC,IAAU,OAAY,SAAW,OAAQ,OAAQ,MAAM,EAC/D,GAAIA,IAAU,QAAa,CAAE,MAAAA,CAAK,EACnC,CACH,OAASC,EAAgB,CACvB,MAAMC,EAAoBD,EACpBE,EAAiBD,EAAkB,OAASA,EAAkB,OAAO,SAAQ,EAAK,GAClFE,EAAiBF,EAAkB,OAASA,EAAkB,OAAO,SAAQ,EAAK,GACxF,MAAM,IAAI,MAAM,sCAAsCH,EAAK,KAAK,GAAG,CAAC;EAAKI,CAAM,GAAGC,GAAUF,EAAkB,SAAW,EAAE,EAAE,CAC/H,CACF,CAUM,SAAUG,EAAkBC,EAAgBC,EAA0B,CAC1E,GAAI,CACF,MAAMC,EAAkB,KAAK,MAAMF,CAAM,EACzC,GAAI,MAAM,QAAQE,CAAM,EACtB,OAAOA,CAEX,MAAQ,CAER,CACA,MAAM,IAAI,MAAM,mCAAmCD,CAAkB;EAAcD,CAAM,EAAE,CAC7F",
6
- "names": ["execFileSync", "runWrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "parseJsonArray", "output", "commandDescription", "parsed"]
5
+ "mappings": "+EAMA,OAAS,gBAAAA,MAAoB,qBAQvB,SAAUC,EAAYC,EAAyBC,EAAc,CACjE,GAAI,CAIF,OAAOH,EAAa,OAAQ,CAAC,OAAQ,WAAY,GAAGE,CAAI,EAAG,CACzD,SAAU,OACV,MAAO,CAACC,IAAU,OAAY,SAAW,OAAQ,OAAQ,MAAM,EAC/D,GAAIA,IAAU,QAAa,CAAE,MAAAA,CAAK,EACnC,CACH,OAASC,EAAgB,CACvB,MAAMC,EAAoBD,EACpBE,EAAiBD,EAAkB,OAASA,EAAkB,OAAO,SAAQ,EAAK,GAClFE,EAAiBF,EAAkB,OAASA,EAAkB,OAAO,SAAQ,EAAK,GACxF,MAAM,IAAI,MAAM,sCAAsCH,EAAK,KAAK,GAAG,CAAC;EAAKI,CAAM,GAAGC,GAAUF,EAAkB,SAAW,EAAE,EAAE,CAC/H,CACF,CAhBgBG,EAAAP,EAAA,eA0BV,SAAUQ,EAAkBC,EAAgBC,EAA0B,CAC1E,GAAI,CACF,MAAMC,EAAkB,KAAK,MAAMF,CAAM,EACzC,GAAI,MAAM,QAAQE,CAAM,EACtB,OAAOA,CAEX,MAAQ,CAER,CACA,MAAM,IAAI,MAAM,mCAAmCD,CAAkB;EAAcD,CAAM,EAAE,CAC7F,CAVgBF,EAAAC,EAAA",
6
+ "names": ["execFileSync", "runWrangler", "args", "input", "error", "maybeProcessError", "stdout", "stderr", "__name", "parseJsonArray", "output", "commandDescription", "parsed"]
7
7
  }
@@ -1,4 +1,4 @@
1
- import{copyFileSync as g,readFileSync as p,writeFileSync as A}from"node:fs";import{applyEdits as y,modify as R,parse as f}from"jsonc-parser";import{CONFIG_PATH as i,TEMPLATE_PATH as l}from"./types.js";function s(){const e=p(i,"utf8");return{content:e,config:f(e)}}function a(e,n,r){const t=R(e,n,r,{formattingOptions:{insertSpaces:!0,tabSize:2,eol:`
2
- `}});return y(e,t)}function c(e){A(i,e.endsWith(`
1
+ var A=Object.defineProperty;var o=(e,n)=>A(e,"name",{value:n,configurable:!0});import{copyFileSync as y,readFileSync as f,writeFileSync as R}from"node:fs";import{applyEdits as d,modify as v,parse as l}from"jsonc-parser";import{CONFIG_PATH as s,TEMPLATE_PATH as u}from"./types.js";function a(){const e=f(s,"utf8");return{content:e,config:l(e)}}o(a,"readConfig");function c(e,n,r){const t=v(e,n,r,{formattingOptions:{insertSpaces:!0,tabSize:2,eol:`
2
+ `}});return d(e,t)}o(c,"writeConfigValue");function p(e){R(s,e.endsWith(`
3
3
  `)?e:`${e}
4
- `)}function d(){return u(process.env.WRANGLER_PATCH_JSON,"WRANGLER_PATCH_JSON","a JSON object")}function v(){const e=u(process.env.WRANGLER_VARS_PATCH_JSON,"WRANGLER_VARS_PATCH_JSON","a JSON object of string values");if(e===void 0)return;const n={};for(const[r,t]of Object.entries(e)){if(!r.trim())throw new Error("WRANGLER_VARS_PATCH_JSON contains an empty variable name.");if(typeof t!="string")throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${r} must be a string.`);n[r]=t}return n}function u(e,n,r){if(e===void 0||!e.trim())return;let t;try{t=JSON.parse(e)}catch{throw new Error(`${n} must be ${r}.`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${n} must be ${r}.`);return t}function S(){const e=process.env.WRANGLER_JSONC;if(e?.trim()){c(e),console.log("Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.");return}g(l,i),console.log("WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.")}function b(){const e=f(p(l,"utf8"));if(typeof e.$minimumVersion!="number")return;const{config:n}=s(),r=n.$version;if(typeof r!="number"||r<e.$minimumVersion)throw new Error(`wrangler.jsonc version (${typeof r=="number"?r:"missing"}) is below minimum template version (${e.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`)}function w(){const e=d(),n=Object.entries(e??{});if(n.length===0)return;let{content:r}=s();for(const[t,o]of n)r=a(r,[t],o);c(r),console.log(`Applied ${n.length} Wrangler top-level patch entr${n.length===1?"y":"ies"}.`)}function E(){const e=v(),n=Object.entries(e??{});if(n.length===0)return;const r=s();let t=r.content;if(r.config.vars!==void 0&&(r.config.vars===null||typeof r.config.vars!="object"||Array.isArray(r.config.vars)))throw new Error("wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.");r.config.vars===void 0&&(t=a(t,["vars"],{}));for(const[o,m]of n)t=a(t,["vars",o],m);c(t),console.log(`Applied ${n.length} Wrangler vars patch entr${n.length===1?"y":"ies"}.`)}export{w as applyTopLevelPatch,E as applyVarsPatch,b as ensureMinimumConfigVersion,d as parseTopLevelPatch,v as parseVarsPatch,S as prepareConfigFile,s as readConfig,c as writeConfig,a as writeConfigValue};
4
+ `)}o(p,"writeConfig");function N(){return m(process.env.WRANGLER_PATCH_JSON,"WRANGLER_PATCH_JSON","a JSON object")}o(N,"parseTopLevelPatch");function _(){const e=m(process.env.WRANGLER_VARS_PATCH_JSON,"WRANGLER_VARS_PATCH_JSON","a JSON object of string values");if(e===void 0)return;const n={};for(const[r,t]of Object.entries(e)){if(!r.trim())throw new Error("WRANGLER_VARS_PATCH_JSON contains an empty variable name.");if(typeof t!="string")throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${r} must be a string.`);n[r]=t}return n}o(_,"parseVarsPatch");function m(e,n,r){if(e===void 0||!e.trim())return;let t;try{t=JSON.parse(e)}catch{throw new Error(`${n} must be ${r}.`)}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error(`${n} must be ${r}.`);return t}o(m,"parseJsonObject");function E(){const e=process.env.WRANGLER_JSONC;if(e?.trim()){p(e),console.log("Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.");return}y(u,s),console.log("WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.")}o(E,"prepareConfigFile");function O(){const e=l(f(u,"utf8"));if(typeof e.$minimumVersion!="number")return;const{config:n}=a(),r=n.$version;if(typeof r!="number"||r<e.$minimumVersion)throw new Error(`wrangler.jsonc version (${typeof r=="number"?r:"missing"}) is below minimum template version (${e.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`)}o(O,"ensureMinimumConfigVersion");function C(){const e=N(),n=Object.entries(e??{});if(n.length===0)return;let{content:r}=a();for(const[t,i]of n)r=c(r,[t],i);p(r),console.log(`Applied ${n.length} Wrangler top-level patch entr${n.length===1?"y":"ies"}.`)}o(C,"applyTopLevelPatch");function $(){const e=_(),n=Object.entries(e??{});if(n.length===0)return;const r=a();let t=r.content;if(r.config.vars!==void 0&&(r.config.vars===null||typeof r.config.vars!="object"||Array.isArray(r.config.vars)))throw new Error("wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.");r.config.vars===void 0&&(t=c(t,["vars"],{}));for(const[i,g]of n)t=c(t,["vars",i],g);p(t),console.log(`Applied ${n.length} Wrangler vars patch entr${n.length===1?"y":"ies"}.`)}o($,"applyVarsPatch");export{C as applyTopLevelPatch,$ as applyVarsPatch,O as ensureMinimumConfigVersion,N as parseTopLevelPatch,_ as parseVarsPatch,E as prepareConfigFile,a as readConfig,p as writeConfig,c as writeConfigValue};
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../src/scripts/wrangler-config/patches.ts"],
4
4
  "sourcesContent": ["/**\n * Reading, writing and patching `wrangler.jsonc`.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/patches.ts`.\n *\n * The config is JSONC — `//` comments and trailing commas — so it is edited\n * through jsonc-parser's `modify`/`applyEdits` rather than parsed and re-serialized.\n * A round trip through `JSON.parse` would drop every comment and reformat the\n * file, which is a diff nobody can review and a reason to regenerate the config by\n * hand instead.\n */\n\nimport { copyFileSync, readFileSync, writeFileSync } from 'node:fs';\nimport { applyEdits, modify, parse } from 'jsonc-parser';\nimport { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types.ts';\n\n/**\nThe config's current text and its parsed form.\n*/\nexport interface ConfigFile {\n content: string;\n config: WranglerConfig;\n}\n\nexport function readConfig(): ConfigFile {\n const content = readFileSync(CONFIG_PATH, 'utf8');\n return { content, config: parse(content) as WranglerConfig };\n}\n\n/**\n * Apply one edit to the config text, preserving comments and formatting.\n */\nexport function writeConfigValue(content: string, path: Array<string | number>, value: unknown): string {\n const edits = modify(content, path, value, { formattingOptions: { insertSpaces: true, tabSize: 2, eol: '\\n' } });\n return applyEdits(content, edits);\n}\n\n/**\nWrite the config, guaranteeing a trailing newline so Prettier sees a fixed point.\n*/\nexport function writeConfig(content: string): void {\n writeFileSync(CONFIG_PATH, content.endsWith('\\n') ? content : `${content}\\n`);\n}\n\n/**\n * The top-level keys a caller wants to merge into the config, from the environment.\n *\n * `WRANGLER_PATCH_JSON` is how a repository variable supplies per-environment\n * settings without a second file: a repo with one worker and three environments\n * patches the routes and the vars rather than keeping three templates in step.\n */\nexport function parseTopLevelPatch(): Record<string, unknown> | undefined {\n return parseJsonObject(process.env['WRANGLER_PATCH_JSON'], 'WRANGLER_PATCH_JSON', 'a JSON object');\n}\n\n/**\nThe `vars` entries a caller wants to merge, from the environment.\n*/\nexport function parseVarsPatch(): Record<string, string> | undefined {\n const parsed = parseJsonObject(process.env['WRANGLER_VARS_PATCH_JSON'], 'WRANGLER_VARS_PATCH_JSON', 'a JSON object of string values');\n if (parsed === undefined) {\n return undefined;\n }\n const patch: Record<string, string> = {};\n for (const [key, value] of Object.entries(parsed)) {\n if (!key.trim()) {\n throw new Error('WRANGLER_VARS_PATCH_JSON contains an empty variable name.');\n }\n if (typeof value !== 'string') {\n throw new TypeError(`WRANGLER_VARS_PATCH_JSON value for ${key} must be a string.`);\n }\n patch[key] = value;\n }\n return patch;\n}\n\nfunction parseJsonObject(raw: string | undefined, name: string, expected: string): Record<string, unknown> | undefined {\n if (raw === undefined || !raw.trim()) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n throw new Error(`${name} must be ${expected}.`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error(`${name} must be ${expected}.`);\n }\n return parsed as Record<string, unknown>;\n}\n\n/**\n * Materialize the config: the repository variable when it is set, otherwise the\n * committed template.\n */\nexport function prepareConfigFile(): void {\n const dumpedConfig = process.env['WRANGLER_JSONC'];\n if (dumpedConfig?.trim()) {\n writeConfig(dumpedConfig);\n console.log('Wrote wrangler.jsonc from WRANGLER_JSONC repository variable.');\n return;\n }\n copyFileSync(TEMPLATE_PATH, CONFIG_PATH);\n console.log('WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.');\n}\n\n/**\n * Refuse a config older than the template requires.\n *\n * The template is the one file in the repo that says which wrangler behaviour the\n * worker was written against, and a config written by an older template can name\n * bindings the worker no longer reads. Failing here rather than at deploy time is\n * the whole reason the check exists.\n */\nexport function ensureMinimumConfigVersion(): void {\n const template = parse(readFileSync(TEMPLATE_PATH, 'utf8')) as { $minimumVersion?: unknown };\n if (typeof template.$minimumVersion !== 'number') {\n return;\n }\n const { config } = readConfig();\n const currentVersion = config.$version;\n if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {\n throw new Error(\n `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`,\n );\n }\n}\n\nexport function applyTopLevelPatch(): void {\n const patch = parseTopLevelPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n let { content } = readConfig();\n for (const [key, value] of entries) {\n content = writeConfigValue(content, [key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler top-level patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n\nexport function applyVarsPatch(): void {\n const patch = parseVarsPatch();\n const entries = Object.entries(patch ?? {});\n if (entries.length === 0) {\n return;\n }\n const prepared = readConfig();\n let content = prepared.content;\n if (\n prepared.config.vars !== undefined &&\n (prepared.config.vars === null || typeof prepared.config.vars !== 'object' || Array.isArray(prepared.config.vars))\n ) {\n throw new Error('wrangler.jsonc vars must be an object before applying WRANGLER_VARS_PATCH_JSON.');\n }\n // `null` needs no branch here: the guard above throws for it, so by this\n // line `vars` is either absent or an object.\n if (prepared.config.vars === undefined) {\n content = writeConfigValue(content, ['vars'], {});\n }\n for (const [key, value] of entries) {\n content = writeConfigValue(content, ['vars', key], value);\n }\n writeConfig(content);\n console.log(`Applied ${entries.length} Wrangler vars patch entr${entries.length === 1 ? 'y' : 'ies'}.`);\n}\n"],
5
- "mappings": "AAYA,OAAS,gBAAAA,EAAc,gBAAAC,EAAc,iBAAAC,MAAqB,UAC1D,OAAS,cAAAC,EAAY,UAAAC,EAAQ,SAAAC,MAAa,eAC1C,OAAS,eAAAC,EAAa,iBAAAC,MAA0C,aAU1D,SAAUC,GAAU,CACxB,MAAMC,EAAUR,EAAaK,EAAa,MAAM,EAChD,MAAO,CAAE,QAAAG,EAAS,OAAQJ,EAAMI,CAAO,CAAmB,CAC5D,CAKM,SAAUC,EAAiBD,EAAiBE,EAA8BC,EAAc,CAC5F,MAAMC,EAAQT,EAAOK,EAASE,EAAMC,EAAO,CAAE,kBAAmB,CAAE,aAAc,GAAM,QAAS,EAAG,IAAK;CAAI,CAAE,CAAE,EAC/G,OAAOT,EAAWM,EAASI,CAAK,CAClC,CAKM,SAAUC,EAAYL,EAAe,CACzCP,EAAcI,EAAaG,EAAQ,SAAS;CAAI,EAAIA,EAAU,GAAGA,CAAO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eFileSync", "applyEdits", "modify", "parse", "CONFIG_PATH", "TEMPLATE_PATH", "readConfig", "content", "writeConfigValue", "path", "value", "edits", "writeConfig", "parseTopLevelPatch", "parseJsonObject", "parseVarsPatch", "parsed", "patch", "key", "raw", "name", "expected", "prepareConfigFile", "dumpedConfig", "ensureMinimumConfigVersion", "template", "config", "currentVersion", "applyTopLevelPatch", "entries", "applyVarsPatch", "prepared"]
5
+ "mappings": "+EAYA,OAAS,gBAAAA,EAAc,gBAAAC,EAAc,iBAAAC,MAAqB,UAC1D,OAAS,cAAAC,EAAY,UAAAC,EAAQ,SAAAC,MAAa,eAC1C,OAAS,eAAAC,EAAa,iBAAAC,MAA0C,aAU1D,SAAUC,GAAU,CACxB,MAAMC,EAAUR,EAAaK,EAAa,MAAM,EAChD,MAAO,CAAE,QAAAG,EAAS,OAAQJ,EAAMI,CAAO,CAAmB,CAC5D,CAHgBC,EAAAF,EAAA,cAQV,SAAUG,EAAiBF,EAAiBG,EAA8BC,EAAc,CAC5F,MAAMC,EAAQV,EAAOK,EAASG,EAAMC,EAAO,CAAE,kBAAmB,CAAE,aAAc,GAAM,QAAS,EAAG,IAAK;CAAI,CAAE,CAAE,EAC/G,OAAOV,EAAWM,EAASK,CAAK,CAClC,CAHgBJ,EAAAC,EAAA,oBAQV,SAAUI,EAAYN,EAAe,CACzCP,EAAcI,EAAaG,EAAQ,SAAS;CAAI,EAAIA,EAAU,GAAGA,CAAO;CAAI,CAC9E,CAFgBC,EAAAK,EAAA,eAWV,SAAUC,GAAkB,CAChC,OAAOC,EAAgB,QAAQ,IAAI,oBAAwB,sBAAuB,eAAe,CACnG,CAFgBP,EAAAM,EAAA,sBAOV,SAAUE,GAAc,CAC5B,MAAMC,EAASF,EAAgB,QAAQ,IAAI,yBAA6B,2BAA4B,gCAAgC,EACpI,GAAIE,IAAW,OACb,OAEF,MAAMC,EAAgC,CAAA,EACtC,SAAW,CAACC,EAAKR,CAAK,IAAK,OAAO,QAAQM,CAAM,EAAG,C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X,EAAQJ,EAAkB,EAC1BgB,EAAU,OAAO,QAAQZ,GAAS,CAAA,CAAE,EAC1C,GAAIY,EAAQ,SAAW,EACrB,OAEF,GAAI,CAAE,QAAAvB,CAAO,EAAKD,EAAU,EAC5B,SAAW,CAACa,EAAKR,CAAK,IAAKmB,EACzBvB,EAAUE,EAAiBF,EAAS,CAACY,CAAG,EAAGR,CAAK,EAElDE,EAAYN,CAAO,EACnB,QAAQ,IAAI,WAAWuB,EAAQ,MAAM,iCAAiCA,EAAQ,SAAW,EAAI,IAAM,KAAK,GAAG,CAC7G,CAZgBtB,EAAAqB,EAAA,sBAcV,SAAUE,GAAc,CAC5B,MAAMb,EAAQF,EAAc,EACtBc,EAAU,OAAO,QAAQZ,GAAS,CAAA,CAAE,EAC1C,GAAIY,EAAQ,SAAW,EACrB,OAEF,MAAME,EAAW1B,EAAU,EAC3B,IAAIC,EAAUyB,EAAS,QACvB,GACEA,EAAS,OAAO,OAAS,SACxBA,EAAS,OAAO,OAAS,MAAQ,OAAOA,EAAS,OAAO,MAAS,UAAY,MAAM,QAAQA,EAAS,OAAO,IAAI,GAEhH,MAAM,IAAI,MAAM,iFAAiF,EAI/FA,EAAS,OAAO,OAAS,SAC3BzB,EAAUE,EAAiBF,EAAS,CAAC,MAAM,EAAG,CAAA,CAAE,GAElD,SAAW,CAACY,EAAKR,CAAK,IAAKmB,EACzBvB,EAAUE,EAAiBF,EAAS,CAAC,OAAQY,CAAG,EAAGR,CAAK,EAE1DE,EAAYN,CAAO,EACnB,QAAQ,IAAI,WAAWuB,EAAQ,MAAM,4BAA4BA,EAAQ,SAAW,EAAI,IAAM,KAAK,GAAG,CACxG,CAxBgBtB,EAAAuB,EAAA",
6
+ "names": ["copyFileSync", "readFileSync", "writeFileSync", "applyEdits", "modify", "parse", "CONFIG_PATH", "TEMPLATE_PATH", "readConfig", "content", "__name", "writeConfigValue", "path", "value", "edits", "writeConfig", "parseTopLevelPatch", "parseJsonObject", "parseVarsPatch", "parsed", "patch", "key", "raw", "name", "expected", "prepareConfigFile", "dumpedConfig", "ensureMinimumConfigVersion", "template", "config", "currentVersion", "applyTopLevelPatch", "entries", "applyVarsPatch", "prepared"]
7
7
  }
@@ -1 +1 @@
1
- import{parse as u}from"jsonc-parser";import{parseWranglerTableRows as x}from"../lib/wrangler-table.js";import{DEFAULT_HEX_ID as l,DEFAULT_KV_NAMESPACE_NAMES as g,DEFAULT_SECRET_STORE_NAME as d,DEFAULT_UUID as v,DEFAULT_WORKER_NAME as _,VECTORIZE_DIMENSIONS as S}from"./types.js";import{parseJsonArray as p,runWrangler as a}from"./cli.js";import{readConfig as D,writeConfig as E,writeConfigValue as f}from"./patches.js";function w(e){return e.uuid??e.database_id??e.id}function b(){return p(a(["d1","list","--json"]),"wrangler d1 list --json")}function q(e){let n=b().find(i=>i.name===e),r=!1;n===void 0&&(console.log(`Creating D1 database: ${e}`),a(["d1","create",e]),n=b().find(i=>i.name===e),r=!0);const t=n===void 0?void 0:w(n);if(t===void 0||t==="")throw new Error(`Unable to discover D1 database ID for ${e}.`);return{id:t,created:r}}function h(){return p(a(["kv","namespace","list"]),"wrangler kv namespace list")}function $(e,n){return g[n]??`${e.name??_}-${n.toLowerCase()}`}function I(e,n){const r=$(e,n),t=new Set([r,`${e.name??_}-${n}`,n]);let i=h().find(o=>{const c=o.title??o.name;return o.id!==void 0&&c!==void 0&&t.has(c)}),s=!1;if(i===void 0&&(console.log(`Creating KV namespace: ${r}`),a(["kv","namespace","create",r]),i=h().find(o=>o.id!==void 0&&(o.title??o.name)===r),s=!0),i?.id===void 0)throw new Error(`Unable to discover KV namespace ID for ${r}.`);return{id:i.id,created:s}}function V(){return Object.keys(g)}function K(e,n){const r=new Set((n.kv_namespaces??[]).map(s=>s.binding).filter(s=>s!==void 0)),t=V().filter(s=>!r.has(s));if(t.length===0)return e;const i=[...n.kv_namespaces??[]];for(const s of t)console.log(`Adding missing KV namespace binding: ${s}`),i.push({binding:s,id:l});return f(e,["kv_namespaces"],i)}function U(e){const n=[];for(const r of x(e)){const t=r.at(0),i=r.at(1);t!==void 0&&i!==void 0&&/^[a-f0-9]{32}$/i.test(i)&&n.push({name:t,id:i})}return n}function m(){const e=a(["secrets-store","store","list","--remote"]);try{return p(e,"wrangler secrets-store store list --remote")}catch{return U(e)}}function A(){const e=m(),n=e.find(o=>o.name===d)??e.at(0);if(n!==void 0)return n.id;console.log(`Creating Secrets Store: ${d}`);const r=a(["secrets-store","store","create",d,"--remote"]),t=/ID:\s*([a-f0-9]{32})/i.exec(r)?.[1];if(t!==void 0)return t;const i=m(),s=i.find(o=>o.name===d)??i.at(0);if(s?.id===void 0)throw new Error(`Unable to discover Secrets Store ID for ${d}.`);return s.id}function C(e){try{return a(["queues","info",e]),console.log(`Queue ${e} already exists.`),!1}catch{return console.log(`Creating queue: ${e}`),a(["queues","create",e]),!0}}function k(e){const n=[],r=new Set;for(const t of e.queues?.producers??[])t.queue===""||r.has(t.queue)||(r.add(t.queue),n.push(t.queue));for(const t of e.queues?.consumers??[])t.queue===""||r.has(t.queue)||(r.add(t.queue),n.push(t.queue));return n}function T(e,n){try{a(["vectorize","info",e]),console.log(`Vectorize index ${e} already exists.`)}catch{console.log(`Creating Vectorize index: ${e} with ${n} dimensions`),a(["vectorize","create",e,`--dimensions=${n}`,"--metric=cosine"])}}function R(e,n,r){let t=e;for(const[i,s]of n.d1_databases?.entries()??[]){if(s.database_id!==v)continue;if(s.database_name===void 0||s.database_name==="")throw new Error(`D1 database binding ${s.binding??i} has a placeholder database_id but no database_name.`);const o=q(s.database_name);o.created&&r.push(`d1:${s.database_name}`),console.log(`Using D1 database ${s.database_name}: ${o.id}`),t=f(t,["d1_databases",i,"database_id"],o.id)}return t}function y(e,n,r){let t=e;for(const[i,s]of n.kv_namespaces?.entries()??[]){if(s.id!==l)continue;if(s.binding===void 0||s.binding==="")throw new Error(`KV namespace at index ${i} has a placeholder id but no binding.`);const o=I(n,s.binding),c=$(n,s.binding);o.created&&r.push(`kv:${c}`),console.log(`Using KV namespace ${c}: ${o.id}`),t=f(t,["kv_namespaces",i,"id"],o.id)}return t}function N(e,n,r){const t=(n.secrets_store_secrets??[]).map((o,c)=>({secret:o,index:c})).filter(({secret:o})=>o.store_id===l);if(t.length===0)return e;const i=m().some(o=>o.name===d),s=A();return i||r.push(`secrets-store:${d}`),console.log(`Using Secrets Store: ${s}`),t.reduce((o,{index:c})=>f(o,["secrets_store_secrets",c,"store_id"],s),e)}function W(){const e=[];let{content:n,config:r}=D();n=K(n,r),r=u(n),n=R(n,r,e),r=u(n),n=y(n,r,e),r=u(n),n=N(n,r,e),E(n),r=u(n);for(const t of k(r))C(t)&&e.push(`queue:${t}`);for(const t of r.vectorize??[])T(t.index_name,S);return e}export{q as ensureD1Database,I as ensureKVNamespace,C as ensureQueue,K as ensureRequiredKvBindings,A as ensureSecretStore,T as ensureVectorizeIndex,w as getD1Id,$ as getKVNamespaceName,V as getRequiredKvBindings,b as listD1Databases,h as listKVNamespaces,m as listSecretStores,U as parseSecretStoresTable,W as provisionWranglerResources,k as queueNamesIn};
1
+ var v=Object.defineProperty;var a=(e,n)=>v(e,"name",{value:n,configurable:!0});import{parse as f}from"jsonc-parser";import{parseWranglerTableRows as S}from"../lib/wrangler-table.js";import{DEFAULT_HEX_ID as p,DEFAULT_KV_NAMESPACE_NAMES as _,DEFAULT_SECRET_STORE_NAME as u,DEFAULT_UUID as D,DEFAULT_WORKER_NAME as b,VECTORIZE_DIMENSIONS as E}from"./types.js";import{parseJsonArray as m,runWrangler as c}from"./cli.js";import{readConfig as w,writeConfig as q,writeConfigValue as l}from"./patches.js";function I(e){return e.uuid??e.database_id??e.id}a(I,"getD1Id");function h(){return m(c(["d1","list","--json"]),"wrangler d1 list --json")}a(h,"listD1Databases");function V(e){let n=h().find(i=>i.name===e),r=!1;n===void 0&&(console.log(`Creating D1 database: ${e}`),c(["d1","create",e]),n=h().find(i=>i.name===e),r=!0);const t=n===void 0?void 0:I(n);if(t===void 0||t==="")throw new Error(`Unable to discover D1 database ID for ${e}.`);return{id:t,created:r}}a(V,"ensureD1Database");function $(){return m(c(["kv","namespace","list"]),"wrangler kv namespace list")}a($,"listKVNamespaces");function x(e,n){return _[n]??`${e.name??b}-${n.toLowerCase()}`}a(x,"getKVNamespaceName");function K(e,n){const r=x(e,n),t=new Set([r,`${e.name??b}-${n}`,n]);let i=$().find(o=>{const d=o.title??o.name;return o.id!==void 0&&d!==void 0&&t.has(d)}),s=!1;if(i===void 0&&(console.log(`Creating KV namespace: ${r}`),c(["kv","namespace","create",r]),i=$().find(o=>o.id!==void 0&&(o.title??o.name)===r),s=!0),i?.id===void 0)throw new Error(`Unable to discover KV namespace ID for ${r}.`);return{id:i.id,created:s}}a(K,"ensureKVNamespace");function U(){return Object.keys(_)}a(U,"getRequiredKvBindings");function A(e,n){const r=new Set((n.kv_namespaces??[]).map(s=>s.binding).filter(s=>s!==void 0)),t=U().filter(s=>!r.has(s));if(t.length===0)return e;const i=[...n.kv_namespaces??[]];for(const s of t)console.log(`Adding missing KV namespace binding: ${s}`),i.push({binding:s,id:p});return l(e,["kv_namespaces"],i)}a(A,"ensureRequiredKvBindings");function C(e){const n=[];for(const r of S(e)){const t=r.at(0),i=r.at(1);t!==void 0&&i!==void 0&&/^[a-f0-9]{32}$/i.test(i)&&n.push({name:t,id:i})}return n}a(C,"parseSecretStoresTable");function g(){const e=c(["secrets-store","store","list","--remote"]);try{return m(e,"wrangler secrets-store store list --remote")}catch{return C(e)}}a(g,"listSecretStores");function k(){const e=g(),n=e.find(o=>o.name===u)??e.at(0);if(n!==void 0)return n.id;console.log(`Creating Secrets Store: ${u}`);const r=c(["secrets-store","store","create",u,"--remote"]),t=/ID:\s*([a-f0-9]{32})/i.exec(r)?.[1];if(t!==void 0)return t;const i=g(),s=i.find(o=>o.name===u)??i.at(0);if(s?.id===void 0)throw new Error(`Unable to discover Secrets Store ID for ${u}.`);return s.id}a(k,"ensureSecretStore");function T(e){try{return c(["queues","info",e]),console.log(`Queue ${e} already exists.`),!1}catch{return console.log(`Creating queue: ${e}`),c(["queues","create",e]),!0}}a(T,"ensureQueue");function R(e){const n=[],r=new Set;for(const t of e.queues?.producers??[])t.queue===""||r.has(t.queue)||(r.add(t.queue),n.push(t.queue));for(const t of e.queues?.consumers??[])t.queue===""||r.has(t.queue)||(r.add(t.queue),n.push(t.queue));return n}a(R,"queueNamesIn");function y(e,n){try{c(["vectorize","info",e]),console.log(`Vectorize index ${e} already exists.`)}catch{console.log(`Creating Vectorize index: ${e} with ${n} dimensions`),c(["vectorize","create",e,`--dimensions=${n}`,"--metric=cosine"])}}a(y,"ensureVectorizeIndex");function N(e,n,r){let t=e;for(const[i,s]of n.d1_databases?.entries()??[]){if(s.database_id!==D)continue;if(s.database_name===void 0||s.database_name==="")throw new Error(`D1 database binding ${s.binding??i} has a placeholder database_id but no database_name.`);const o=V(s.database_name);o.created&&r.push(`d1:${s.database_name}`),console.log(`Using D1 database ${s.database_name}: ${o.id}`),t=l(t,["d1_databases",i,"database_id"],o.id)}return t}a(N,"provisionD1Databases");function z(e,n,r){let t=e;for(const[i,s]of n.kv_namespaces?.entries()??[]){if(s.id!==p)continue;if(s.binding===void 0||s.binding==="")throw new Error(`KV namespace at index ${i} has a placeholder id but no binding.`);const o=K(n,s.binding),d=x(n,s.binding);o.created&&r.push(`kv:${d}`),console.log(`Using KV namespace ${d}: ${o.id}`),t=l(t,["kv_namespaces",i,"id"],o.id)}return t}a(z,"provisionKvNamespaces");function L(e,n,r){const t=(n.secrets_store_secrets??[]).map((o,d)=>({secret:o,index:d})).filter(({secret:o})=>o.store_id===p);if(t.length===0)return e;const i=g().some(o=>o.name===u),s=k();return i||r.push(`secrets-store:${u}`),console.log(`Using Secrets Store: ${s}`),t.reduce((o,{index:d})=>l(o,["secrets_store_secrets",d,"store_id"],s),e)}a(L,"provisionSecretStore");function Q(){const e=[];let{content:n,config:r}=w();n=A(n,r),r=f(n),n=N(n,r,e),r=f(n),n=z(n,r,e),r=f(n),n=L(n,r,e),q(n),r=f(n);for(const t of R(r))T(t)&&e.push(`queue:${t}`);for(const t of r.vectorize??[])y(t.index_name,E);return e}a(Q,"provisionWranglerResources");export{V as ensureD1Database,K as ensureKVNamespace,T as ensureQueue,A as ensureRequiredKvBindings,k as ensureSecretStore,y as ensureVectorizeIndex,I as getD1Id,x as getKVNamespaceName,U as getRequiredKvBindings,h as listD1Databases,$ as listKVNamespaces,g as listSecretStores,C as parseSecretStoresTable,Q as provisionWranglerResources,R as queueNamesIn};
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../../src/scripts/wrangler-config/resources.ts"],
4
4
  "sourcesContent": ["/**\n * Creating the resources `wrangler.jsonc` names, and writing their real ids over\n * the placeholders.\n *\n * Provenance: ported from Edge-Sonic's `scripts/lib/wrangler-config/resources.ts`.\n *\n * The placeholder rule: a template carries an all-zero id meaning \"resolve me\",\n * and a config carrying one cannot be deployed. So provisioning walks the config,\n * creates what is missing, and patches the id in place. A placeholder with nothing\n * to create it *under* — a KV id with no binding, a D1 id with no name — is\n * refused rather than skipped, because a silently skipped placeholder is a deploy\n * that fails later with no link back to the reason.\n */\n\nimport { parse } from 'jsonc-parser';\nimport { parseWranglerTableRows } from '../lib/wrangler-table.ts';\nimport {\n DEFAULT_HEX_ID,\n DEFAULT_KV_NAMESPACE_NAMES,\n DEFAULT_SECRET_STORE_NAME,\n DEFAULT_UUID,\n DEFAULT_WORKER_NAME,\n VECTORIZE_DIMENSIONS,\n type D1Database,\n type KVNamespace,\n type SecretStore,\n type WranglerConfig,\n} from './types.ts';\nimport { parseJsonArray, runWrangler } from './cli.ts';\nimport { readConfig, writeConfig, writeConfigValue } from './patches.ts';\n\n/**\nWhat `ensure*` did, so a caller can act on the difference.\n*/\nexport interface Provisioned {\n id: string;\n created: boolean;\n}\n\n/**\nThe id a D1 database is reported under, whichever key the CLI used.\n*/\nexport function getD1Id(database: D1Database): string | undefined {\n return database.uuid ?? database.database_id ?? database.id;\n}\n\nexport function listD1Databases(): D1Database[] {\n return parseJsonArray<D1Database>(runWrangler(['d1', 'list', '--json']), 'wrangler d1 list --json');\n}\n\n/**\n * The D1 database `binding` names, created when it does not exist.\n *\n * Whether it was created is reported, not inferred: a database created moments ago\n * holds no user data, so a backup workflow must refuse to upload its empty dump.\n * The caller cannot re-derive that from the config, because this very function\n * patches the placeholder away before the reader ever runs.\n */\nexport function ensureD1Database(databaseName: string): Provisioned {\n let database = listD1Databases().find((candidate) => candidate.name === databaseName);\n let created = false;\n if (database === undefined) {\n console.log(`Creating D1 database: ${databaseName}`);\n runWrangler(['d1', 'create', databaseName]);\n database = listD1Databases().find((candidate) => candidate.name === databaseName);\n created = true;\n }\n const databaseId = database === undefined ? undefined : getD1Id(database);\n if (databaseId === undefined || databaseId === '') {\n throw new Error(`Unable to discover D1 database ID for ${databaseName}.`);\n }\n return { id: databaseId, created };\n}\n\nexport function listKVNamespaces(): KVNamespace[] {\n return parseJsonArray<KVNamespace>(runWrangler(['kv', 'namespace', 'list']), 'wrangler kv namespace list');\n}\n\n/**\nThe namespace name a binding's namespace is created under.\n*/\nexport function getKVNamespaceName(config: WranglerConfig, binding: string): string {\n return DEFAULT_KV_NAMESPACE_NAMES[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;\n}\n\nexport function ensureKVNamespace(config: WranglerConfig, binding: string): Provisioned {\n const namespaceName = getKVNamespaceName(config, binding);\n const candidateNames = new Set([namespaceName, `${config.name ?? DEFAULT_WORKER_NAME}-${binding}`, binding]);\n let namespace = listKVNamespaces().find((candidate) => {\n const candidateName = candidate.title ?? candidate.name;\n return candidate.id !== undefined && candidateName !== undefined && candidateNames.has(candidateName);\n });\n let created = false;\n if (namespace === undefined) {\n console.log(`Creating KV namespace: ${namespaceName}`);\n runWrangler(['kv', 'namespace', 'create', namespaceName]);\n namespace = listKVNamespaces().find((candidate) => candidate.id !== undefined && (candidate.title ?? candidate.name) === namespaceName);\n created = true;\n }\n if (namespace?.id === undefined) {\n throw new Error(`Unable to discover KV namespace ID for ${namespaceName}.`);\n }\n return { id: namespace.id, created };\n}\n\n/**\nThe bindings a deployment always needs, whether or not a custom config lists them.\n*/\nexport function getRequiredKvBindings(): string[] {\n return Object.keys(DEFAULT_KV_NAMESPACE_NAMES);\n}\n\n/**\n * Add the always-needed KV bindings a hand-written config left out.\n *\n * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without\n * this the worker starts with an unbound `CACHE` and fails on the first read.\n */\nexport function ensureRequiredKvBindings(content: string, config: WranglerConfig): string {\n const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));\n const missing = getRequiredKvBindings().filter((binding) => !existing.has(binding));\n if (missing.length === 0) {\n return content;\n }\n const next = [...(config.kv_namespaces ?? [])];\n for (const binding of missing) {\n console.log(`Adding missing KV namespace binding: ${binding}`);\n next.push({ binding, id: DEFAULT_HEX_ID });\n }\n return writeConfigValue(content, ['kv_namespaces'], next);\n}\n\n/**\nThe stores in a `secrets-store store list` table.\n*/\nexport function parseSecretStoresTable(output: string): SecretStore[] {\n const stores: SecretStore[] = [];\n // Through the shared table parser rather than a second inline split: `wrangler`\n // renders through `cli-table3`, whose cells are separated by U+2502 and are *not*\n // space-aligned, so a parser written for aligned output silently matches nothing\n // — which reads as \"the store does not exist\" and makes provisioning create a\n // duplicate.\n for (const row of parseWranglerTableRows(output)) {\n // `.at()` rather than indexing: a short row is possible when the table\n // shape drifts, and the guards below are what skip it.\n const name = row.at(0);\n const id = row.at(1);\n // Store ids are 32 hex characters; a row without one is a header, a border, or\n // an unrelated column, and is skipped rather than stored with an undefined id.\n if (name !== undefined && id !== undefined && /^[a-f0-9]{32}$/i.test(id)) {\n stores.push({ name, id });\n }\n }\n return stores;\n}\n\nexport function listSecretStores(): SecretStore[] {\n const output = runWrangler(['secrets-store', 'store', 'list', '--remote']);\n try {\n return parseJsonArray<SecretStore>(output, 'wrangler secrets-store store list --remote');\n } catch {\n // The subcommand prints a table rather than JSON on some versions.\n return parseSecretStoresTable(output);\n }\n}\n\nexport function ensureSecretStore(): string {\n const stores = listSecretStores();\n const existing = stores.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? stores.at(0);\n if (existing !== undefined) {\n return existing.id;\n }\n console.log(`Creating Secrets Store: ${DEFAULT_SECRET_STORE_NAME}`);\n const output = runWrangler(['secrets-store', 'store', 'create', DEFAULT_SECRET_STORE_NAME, '--remote']);\n const createdStoreId = /ID:\\s*([a-f0-9]{32})/i.exec(output)?.[1];\n if (createdStoreId !== undefined) {\n return createdStoreId;\n }\n // The create output did not name the id, so read it back rather than guessing.\n const refreshed = listSecretStores();\n const store = refreshed.find((candidate) => candidate.name === DEFAULT_SECRET_STORE_NAME) ?? refreshed.at(0);\n if (store?.id === undefined) {\n throw new Error(`Unable to discover Secrets Store ID for ${DEFAULT_SECRET_STORE_NAME}.`);\n }\n return store.id;\n}\n\n/**\nCreate a queue when it is absent, reporting whether it had to be created.\n*/\nexport function ensureQueue(queueName: string): boolean {\n try {\n runWrangler(['queues', 'info', queueName]);\n console.log(`Queue ${queueName} already exists.`);\n return false;\n } catch {\n console.log(`Creating queue: ${queueName}`);\n runWrangler(['queues', 'create', queueName]);\n return true;\n }\n}\n\n/**\n * Queue names a deployment needs, in first-seen order.\n *\n * Producers and consumers name the same queue twice — one queue, two roles — and a\n * name appearing in both must be created once. Pure so it is testable without\n * wrangler.\n */\nexport function queueNamesIn(config: WranglerConfig): string[] {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const producer of config.queues?.producers ?? []) {\n if (producer.queue === '' || seen.has(producer.queue)) continue;\n seen.add(producer.queue);\n names.push(producer.queue);\n }\n for (const consumer of config.queues?.consumers ?? []) {\n if (consumer.queue === '' || seen.has(consumer.queue)) continue;\n seen.add(consumer.queue);\n names.push(consumer.queue);\n }\n return names;\n}\n\nexport function ensureVectorizeIndex(indexName: string, dimensions: number): void {\n try {\n runWrangler(['vectorize', 'info', indexName]);\n console.log(`Vectorize index ${indexName} already exists.`);\n } catch {\n console.log(`Creating Vectorize index: ${indexName} with ${dimensions} dimensions`);\n runWrangler(['vectorize', 'create', indexName, `--dimensions=${dimensions}`, '--metric=cosine']);\n }\n}\n\n/**\nReplace each placeholder D1 `database_id` with a real one.\n*/\nfunction provisionD1Databases(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, database] of config.d1_databases?.entries() ?? []) {\n if (database.database_id !== DEFAULT_UUID) continue;\n if (database.database_name === undefined || database.database_name === '') {\n throw new Error(`D1 database binding ${database.binding ?? index} has a placeholder database_id but no database_name.`);\n }\n const resolved = ensureD1Database(database.database_name);\n if (resolved.created) {\n created.push(`d1:${database.database_name}`);\n }\n console.log(`Using D1 database ${database.database_name}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['d1_databases', index, 'database_id'], resolved.id);\n }\n return patched;\n}\n\n/**\nReplace each placeholder KV namespace id with a real one.\n*/\nfunction provisionKvNamespaces(content: string, config: WranglerConfig, created: string[]): string {\n let patched = content;\n for (const [index, namespace] of config.kv_namespaces?.entries() ?? []) {\n if (namespace.id !== DEFAULT_HEX_ID) continue;\n if (namespace.binding === undefined || namespace.binding === '') {\n throw new Error(`KV namespace at index ${index} has a placeholder id but no binding.`);\n }\n const resolved = ensureKVNamespace(config, namespace.binding);\n const namespaceName = getKVNamespaceName(config, namespace.binding);\n if (resolved.created) {\n created.push(`kv:${namespaceName}`);\n }\n console.log(`Using KV namespace ${namespaceName}: ${resolved.id}`);\n patched = writeConfigValue(patched, ['kv_namespaces', index, 'id'], resolved.id);\n }\n return patched;\n}\n\n/**\n * Point every placeholder Secrets Store `store_id` at one store, creating it if\n * absent. `existed` is read **before** the create, because whether the store was\n * created is what the caller reports.\n */\nfunction provisionSecretStore(content: string, config: WranglerConfig, created: string[]): string {\n const placeholders = (config.secrets_store_secrets ?? [])\n .map((secret, index) => ({ secret, index }))\n .filter(({ secret }) => secret.store_id === DEFAULT_HEX_ID);\n if (placeholders.length === 0) {\n return content;\n }\n const existed = listSecretStores().some((store) => store.name === DEFAULT_SECRET_STORE_NAME);\n const storeId = ensureSecretStore();\n if (!existed) {\n created.push(`secrets-store:${DEFAULT_SECRET_STORE_NAME}`);\n }\n console.log(`Using Secrets Store: ${storeId}`);\n return placeholders.reduce(\n (patched, { index }) => writeConfigValue(patched, ['secrets_store_secrets', index, 'store_id'], storeId),\n content,\n );\n}\n\n/**\n * Create every resource the config names, and write the real ids over the\n * placeholders.\n *\n * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,\n * because a caller acts on it: the backup workflow refuses to export a D1 database\n * that appears here, since one created moments ago holds no user data and an empty\n * dump uploaded on schedule is a false sense of safety.\n */\nexport function provisionWranglerResources(): string[] {\n const created: string[] = [];\n let { content, config } = readConfig();\n\n content = ensureRequiredKvBindings(content, config);\n config = parse(content) as WranglerConfig;\n\n // Each of the three below re-parses before it patches, because each writes into\n // the config text the previous one produced. They are separate functions because\n // they are separate resources with separate rules, and one loop holding all\n // three would read as a single resource list with the differences hidden in the\n // bodies.\n content = provisionD1Databases(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionKvNamespaces(content, config, created);\n config = parse(content) as WranglerConfig;\n\n content = provisionSecretStore(content, config, created);\n\n writeConfig(content);\n\n config = parse(content) as WranglerConfig;\n for (const queueName of queueNamesIn(config)) {\n if (ensureQueue(queueName)) {\n created.push(`queue:${queueName}`);\n }\n }\n\n // Vectorize indexes are name-based, so nothing in the file is patched — but the\n // created names are still reported like every other resource, so a deploy log\n // shows what appeared.\n for (const binding of config.vectorize ?? []) {\n ensureVectorizeIndex(binding.index_name, VECTORIZE_DIMENSIONS);\n }\n\n return created;\n}\n"],
5
- "mappings": "AAcA,OAAS,SAAAA,MAAa,eACtB,OAAS,0BAAAC,MAA8B,2BACvC,OACE,kBAAAC,EACA,8BAAAC,EACA,6BAAAC,EACA,gBAAAC,EACA,uBAAAC,EACA,wBAAAC,MAKK,aACP,OAAS,kBAAAC,EAAgB,eAAAC,MAAmB,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BC,EAAST,CAAM,EAClDA,EAASvB,EAAMgC,CAAO,EAOtBA,EAAUyB,EAAqBzB,EAAST,EAAQJ,CAAO,EACvDI,EAASvB,EAAMgC,CAAO,EAEtBA,EAAU6B,EAAsB7B,EAAST,EAAQJ,CAAO,EACxDI,EAASvB,EAAMgC,CAAO,EAEtBA,EAAU8B,EAAqB9B,EAAST,EAAQJ,CAAO,EAEvDR,EAAYqB,CAAO,EAEnBT,EAASvB,EAAMgC,CAAO,EACtB,UAAWgB,KAAaC,EAAa1B,CAAM,EACrCwB,EAAYC,CAAS,GACvB7B,EAAQ,KAAK,SAAS6B,CAAS,EAAE,EAOrC,UAAWxB,KAAWD,EAAO,WAAa,CAAA,EACxC+B,EAAqB9B,EAAQ,WAAYjB,CAAoB,EAG/D,OAAOY,CACT",
6
- "names": ["parse", "parseWranglerTableRows", "DEFAULT_HEX_ID", "DEFAULT_KV_NAMESPACE_NAMES", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "listD1Databases", "ensureD1Database", "databaseName", "candidate", "created", "databaseId", "listKVNamespaces", "getKVNamespaceName", "config", "binding", "ensureKVNamespace", "namespaceName", "candidateNames", "namespace", "candidateName", "getRequiredKvBindings", "ensureRequiredKvBindings", "content", "existing", "missing", "next", "parseSecretStoresTable", "output", "stores", "row", "name", "id", "listSecretStores", "ensureSecretStore", "createdStoreId", "refreshed", "store", "ensureQueue", "queueName", "queueNamesIn", "names", "seen", "producer", "consumer", "ensureVectorizeIndex", "indexName", "dimensions", "provisionD1Databases", "patched", "index", "resolved", "provisionKvNamespaces", "provisionSecretStore", "placeholders", "secret", "existed", "storeId", "provisionWranglerResources"]
5
+ "mappings": "+EAcA,OAAS,SAAAA,MAAa,eACtB,OAAS,0BAAAC,MAA8B,2BACvC,OACE,kBAAAC,EACA,8BAAAC,EACA,6BA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,EAAa,SAAW,EAC1B,OAAO/B,EAET,MAAMiC,EAAUvB,EAAgB,EAAG,KAAMI,GAAUA,EAAM,OAAS3C,CAAyB,EACrF+D,EAAUvB,EAAiB,EACjC,OAAKsB,GACH9C,EAAQ,KAAK,iBAAiBhB,CAAyB,EAAE,EAE3D,QAAQ,IAAI,wBAAwB+D,CAAO,EAAE,EACtCH,EAAa,OAClB,CAACL,EAAS,CAAE,MAAAC,CAAK,IAAOhD,EAAiB+C,EAAS,CAAC,wBAAyBC,EAAO,UAAU,EAAGO,CAAO,EACvGlC,CAAO,CAEX,CAjBSlB,EAAAgD,EAAA,wBA4BH,SAAUK,GAA0B,CACxC,MAAMhD,EAAoB,CAAA,EAC1B,GAAI,CAAE,QAAAa,EAAS,OAAAT,CAAM,EAAKd,EAAU,EAEpCuB,EAAUD,EAAyBC,EAAST,CAAM,EAClDA,EAASxB,EAAMiC,CAAO,EAOtBA,EAAUyB,EAAqBzB,EAAST,EAAQJ,CAAO,EACvDI,EAASxB,EAAMiC,CAAO,EAEtBA,EAAU6B,EAAsB7B,EAAST,EAAQJ,CAAO,EACxDI,EAASxB,EAAMiC,CAAO,EAEtBA,EAAU8B,EAAqB9B,EAAST,EAAQJ,CAAO,EAEvDT,EAAYsB,CAAO,EAEnBT,EAASxB,EAAMiC,CAAO,EACtB,UAAWgB,KAAaC,EAAa1B,CAAM,EACrCwB,EAAYC,CAAS,GACvB7B,EAAQ,KAAK,SAAS6B,CAAS,EAAE,EAOrC,UAAWxB,KAAWD,EAAO,WAAa,CAAA,EACxC+B,EAAqB9B,EAAQ,WAAYlB,CAAoB,EAG/D,OAAOa,CACT,CArCgBL,EAAAqD,EAAA",
6
+ "names": ["parse", "parseWranglerTableRows", "DEFAULT_HEX_ID", "DEFAULT_KV_NAMESPACE_NAMES", "DEFAULT_SECRET_STORE_NAME", "DEFAULT_UUID", "DEFAULT_WORKER_NAME", "VECTORIZE_DIMENSIONS", "parseJsonArray", "runWrangler", "readConfig", "writeConfig", "writeConfigValue", "getD1Id", "database", "__name", "listD1Databases", "ensureD1Database", "databaseName", "candidate", "created", "databaseId", "listKVNamespaces", "getKVNamespaceName", "config", "binding", "ensureKVNamespace", "namespaceName", "candidateNames", "namespace", "candidateName", "getRequiredKvBindings", "ensureRequiredKvBindings", "content", "existing", "missing", "next", "parseSecretStoresTable", "output", "stores", "row", "name", "id", "listSecretStores", "ensureSecretStore", "createdStoreId", "refreshed", "store", "ensureQueue", "queueName", "queueNamesIn", "names", "seen", "producer", "consumer", "ensureVectorizeIndex", "indexName", "dimensions", "provisionD1Databases", "patched", "index", "resolved", "provisionKvNamespaces", "provisionSecretStore", "placeholders", "secret", "existed", "storeId", "provisionWranglerResources"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{executableStatements as p,splitSql as g}from"@rexezuge/d1";import{readdirSync as d,readFileSync as h}from"node:fs";import w from"node:path";function q(r){return d(r,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".sql")).map(t=>({name:t.name,sql:h(w.join(r,t.name),"utf8")})).sort((t,f)=>t.name.localeCompare(f.name))}function S(r){let n=r;for(;;){const t=n.replace(/^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/)\s*/,"");if(t===n)return n.trim();n=t}}function F(r){const n=r.files===void 0?q(r.migrationsDir):[...r.files],t=new WeakMap,f=(e,o)=>{if(e===void 0)return o;const i=n.findIndex(s=>s.name===e);if(i===-1)throw new Error(`Unknown migration file: ${e}. Available: ${n.map(s=>s.name).join(", ")}`);return i};return{migrationFiles:()=>n.map(e=>({...e})),migrationFileNames:()=>n.map(e=>e.name),migrationSql:()=>n.map(e=>e.sql).join(`
2
- `),migrationSqlOf:e=>{const o=n.find(i=>i.name===e);if(o===void 0)throw new Error(`Unknown migration file: ${e}. Available: ${n.map(i=>i.name).join(", ")}`);return o.sql},splitSql:g,executableStatements:p,applyMigrations:async(e,o)=>{const i=f(o?.from,0),s=f(o?.to,n.length-1),m=`${i}:${s}`;if(t.get(e)===m)return;const u=n.slice(i,s+1);for(const c of u){const l=p(c.sql);if(l.length!==0){if(typeof e.batch=="function"){try{await e.batch(l.map(a=>e.prepare(a)))}catch(a){throw new Error(`${c.name}: batch of ${l.length} statements failed at ${S(l.at(-1)??"").slice(0,200)}: ${a instanceof Error?a.message:String(a)}`,{cause:a})}continue}for(const a of l)await e.prepare(a).run()}}t.set(e,m)}}}import{executableStatements as E,splitSql as M}from"@rexezuge/d1";export{F as createMigrationHelper,E as executableStatements,q as readMigrationFiles,M as splitSql};
1
+ var d=Object.defineProperty;var r=(i,n)=>d(i,"name",{value:n,configurable:!0});import{executableStatements as u,splitSql as h}from"@rexezuge/d1";import{readdirSync as w,readFileSync as q}from"node:fs";import S from"node:path";function $(i){return w(i,{withFileTypes:!0}).filter(t=>t.isFile()&&t.name.endsWith(".sql")).map(t=>({name:t.name,sql:q(S.join(i,t.name),"utf8")})).sort((t,m)=>t.name.localeCompare(m.name))}r($,"readMigrationFiles");function x(i){let n=i;for(;;){const t=n.replace(/^\s*(?:--[^\n]*\n|\/\*[\s\S]*?\*\/)\s*/,"");if(t===n)return n.trim();n=t}}r(x,"stripLeadingComments");function E(i){const n=i.files===void 0?$(i.migrationsDir):[...i.files],t=new WeakMap,m=r((e,s)=>{if(e===void 0)return s;const a=n.findIndex(l=>l.name===e);if(a===-1)throw new Error(`Unknown migration file: ${e}. Available: ${n.map(l=>l.name).join(", ")}`);return a},"indexOf");return{migrationFiles:r(()=>n.map(e=>({...e})),"migrationFiles"),migrationFileNames:r(()=>n.map(e=>e.name),"migrationFileNames"),migrationSql:r(()=>n.map(e=>e.sql).join(`
2
+ `),"migrationSql"),migrationSqlOf:r(e=>{const s=n.find(a=>a.name===e);if(s===void 0)throw new Error(`Unknown migration file: ${e}. Available: ${n.map(a=>a.name).join(", ")}`);return s.sql},"migrationSqlOf"),splitSql:h,executableStatements:u,applyMigrations:r(async(e,s)=>{const a=m(s?.from,0),l=m(s?.to,n.length-1),c=`${a}:${l}`;if(t.get(e)===c)return;const g=n.slice(a,l+1);for(const p of g){const f=u(p.sql);if(f.length!==0){if(typeof e.batch=="function"){try{await e.batch(f.map(o=>e.prepare(o)))}catch(o){throw new Error(`${p.name}: batch of ${f.length} statements failed at ${x(f.at(-1)??"").slice(0,200)}: ${o instanceof Error?o.message:String(o)}`,{cause:o})}continue}for(const o of f)await e.prepare(o).run()}}t.set(e,c)},"applyMigrations")}}r(E,"createMigrationHelper");import{executableStatements as v,splitSql as A}from"@rexezuge/d1";export{E as createMigrationHelper,v as executableStatements,$ as readMigrationFiles,A as splitSql};