@rexezuge/tooling 1.6.1 → 1.7.1

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/vitest.ts"],
4
- "sourcesContent": ["/**\n * The unit-test Vitest config for the worker-and-packages half of the suite.\n *\n * Provenance: converged from all nine repos' `vitest.config.mts`. The coverage\n * block is Durable-DAV-Router's (the most complete: v8 provider, explicit\n * include/exclude patterns, thresholds with the reasoning for why they sit just\n * under the measured value); the alias block is the union of Durable-DAV's\n * `cloudflare:*` mocks, every repo's `@scope/* → src` workspace table, and the\n * shared `@/` + `~/` prefixes — see {@link ./vitest-aliases.js}.\n *\n * Canonical decisions:\n *\n * 1. **Every file matching `include` is reported** — Vitest 4 removed\n * `coverage.all`, and an explicit `include` now covers files no test\n * imported. That is the behaviour the source repos configured `all: true` for,\n * and the reason it mattered: without it a brand-new module with no test is\n * invisible rather than counted as zero, which is the exact regression this\n * gate exists to catch.\n * 2. **The SPA is excluded here**, so this config and `defineWebVitestConfig()`\n * partition the suite rather than each running all of it. The default covers\n * every suite shape the family uses (`test/web/**`, `test/**​/web-*`,\n * `apps/web/**`); see `defineRepoVitestConfig()` for the single-file\n * `projects` composition the AWS/Mail-Meow/CalDAV repos use.\n * 3. **A custom `exclude` re-lists `node_modules`** — `test/` is a workspace\n * project and therefore has its own, so without the re-list the glob reaches\n * into `test/node_modules` and tries to run other packages' suites.\n * 4. **Thresholds are a consumer argument**, not a kit default. A floor is a\n * per-repo ratchet measured against that repo's suite; the kit cannot know a\n * number, and guessing one is how floors get lowered.\n * 5. **`@rexezuge/*` is never externalized** — see `KIT_NO_EXTERNAL`: the kit\n * ships ESM `dist/` with bundler-style extensionless imports, which Node's\n * resolver refuses, so the kit stays inside Vite's pipeline (the same\n * resolver that bundles the worker).\n */\n\nimport { defineConfig, type Plugin } from 'vitest/config';\nimport { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';\nimport type { VitestAlias } from './vitest-aliases.ts';\n\nexport type { VitestAlias } from './vitest-aliases.ts';\n\n/**\n * Coverage thresholds, in the four figures Vitest gates on.\n */\nexport interface CoverageThresholds {\n readonly statements?: number;\n readonly branches?: number;\n readonly functions?: number;\n readonly lines?: number;\n}\n\n/**\n * What `defineUnitVitestConfig` accepts. Every field is optional: the defaults\n * cover the canonical monorepo layout, and a consumer overrides only what its\n * tree actually differs in.\n */\nexport interface UnitVitestConfigOptions {\n /**\n * The consuming repo's npm scope, e.g. `'@myapp'`. When supplied, `@scope/*`\n * workspace aliases are generated from `packages` (plus `background` under\n * `apps/`); when omitted, only the `cloudflare:*`, `@/` and `~/` aliases\n * apply and `aliases` carries the workspace table by hand.\n */\n readonly scope?: string;\n /**\n * Workspace package directory names. Defaults to the family superset; a repo\n * without a domain package keeps the default harmlessly (its alias never\n * matches).\n */\n readonly packages?: readonly string[];\n /**\n * Which `cloudflare:*` mocks to alias. Defaults to workers/sockets/workflows.\n */\n readonly mocks?: readonly string[];\n /**\n * Extra resolver entries, applied after the canonical ones (e.g. the `hono`\n * dedupe two repos carry, or an `/index.ts` exact entry).\n */\n readonly aliases?: readonly VitestAlias[];\n /**\n * Where the repo root is, as a file URL. Defaults to the directory this\n * factory is *called* from, which is the repo root's `vitest.config.mts`.\n * Pass `new URL('.', import.meta.url).href` explicitly from the caller —\n * never rely on this module's own URL, which points into `node_modules`.\n */\n readonly root?: string;\n /**\n * Which suites to collect. Defaults to the whole unit suite.\n */\n readonly include?: readonly string[];\n /**\n * Suite paths to skip, replacing the default. Defaults re-list\n * `node_modules`/`dist`/`integration` plus every SPA shape.\n */\n readonly exclude?: readonly string[];\n /**\n * `node_modules` specifiers to inline through Vite rather than externalize.\n * Defaults to `['dofs']` (Durable-DAV: `dofs` imports `cloudflare:workers`,\n * which Node rejects before `resolve.alias` is consulted).\n */\n readonly serverDepsInline?: readonly string[];\n /**\n * Resolver `noExternal` patterns. Defaults to keeping `@rexezuge/*` inside\n * Vite's pipeline; see `KIT_NO_EXTERNAL`.\n */\n readonly noExternal?: readonly (string | RegExp)[];\n /**\n * Vite plugins for the suite (rare on the backend half; the SPA half passes\n * `react()` here).\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Setup files run before each test file (e.g. AWS's floci guard, Meow's\n * backend/web setups).\n */\n readonly setupFiles?: readonly string[];\n /**\n * Coverage `include` globs. Defaults to the worker plus every workspace\n * package's `src`.\n */\n readonly coverageInclude?: readonly string[];\n /**\n * Coverage `exclude` globs, merged with the canonical set.\n */\n readonly coverageExclude?: readonly string[];\n /**\n * Coverage floors. Omitted by default; a repo that wants them sets them.\n */\n readonly thresholds?: CoverageThresholds;\n /**\n * Where the coverage report is written.\n */\n readonly reportsDirectory?: string;\n}\n\n/**\n * The SPA's suites, excluded here so the two configs partition the suite.\n *\n * Every shape the family uses: the `test/web/**` directory convention\n * (CalDAV-Bridge, Mail-Meow), the root-suite `web-*` naming convention\n * (Durable-DAV-Router), and suites bundled under `apps/web` (Mail-Otter).\n * `defineWebVitestConfig()` includes the same globs, so a file is collected by\n * exactly one config.\n */\nconst SPA_FILES: readonly string[] = ['test/web/**', 'test/**/web-*.test.{ts,tsx}', 'apps/web/**/*.test.{ts,tsx}'];\n\n/**\n * Coverage `exclude` globs converged from the source repos.\n *\n * The categories: build and test tooling (`scripts/` grows with project surface,\n * not complexity, and the god-file guard excludes it for the same reason), test\n * files, declarations, re-export barrels (`index.ts` carries no logic of its\n * own), model records, generated files (the SPA shell is a one-line HTML blob\n * with no logic to exercise), and type-only modules.\n */\nconst CANONICAL_COVERAGE_EXCLUDE: readonly string[] = [\n 'scripts/**',\n '**/*.test.ts',\n '**/*.test.tsx',\n '**/*.d.ts',\n '**/index.ts',\n '**/types.d.ts',\n '**/model/**',\n '**/generated/**',\n '**/D1Types.ts',\n '**/ServiceEnv.ts',\n '**/env.d.ts',\n];\n\n/**\n * Build the unit-test config.\n *\n * ```ts\n * // vitest.config.mts\n * import { defineUnitVitestConfig } from '@rexezuge/tooling/vitest';\n * export default defineUnitVitestConfig({\n * scope: '@myapp',\n * thresholds: { statements: 60, branches: 55, functions: 65, lines: 60 },\n * });\n * ```\n */\nexport function defineUnitVitestConfig(options: UnitVitestConfigOptions = {}): ReturnType<typeof defineConfig> {\n const root = options.root ?? new URL('.', import.meta.url).href;\n const coverageInclude = options.coverageInclude ?? ['apps/api/src/**/*.ts', 'apps/background/src/**/*.ts', 'packages/**/src/**/*.ts'];\n const coverageExclude = [...CANONICAL_COVERAGE_EXCLUDE, ...(options.coverageExclude ?? [])];\n const baseAliases = workspaceAliases({\n scope: options.scope ?? '@unused',\n root,\n packages: options.scope === undefined ? [] : (options.packages ?? DEFAULT_WORKSPACE_PACKAGES),\n mocks: options.mocks ?? DEFAULT_CLOUDFLARE_MOCKS,\n });\n // A placeholder scope contributes no `@unused/*` entries; the mocks plus\n // `@/`/`~/` survive either way.\n const aliases = [\n ...baseAliases.filter((alias) => typeof alias.find !== 'string' || !alias.find.startsWith('@unused')),\n ...(options.aliases ?? []),\n ];\n\n return defineConfig({\n ...(options.plugins !== undefined && { plugins: [...options.plugins] }),\n resolve: { alias: aliases, noExternal: [...KIT_NO_EXTERNAL, ...(options.noExternal ?? [])] },\n test: {\n globals: true,\n environment: 'node',\n include: [...(options.include ?? ['test/**/*.test.{ts,tsx}'])],\n // `test` is a workspace project and therefore has its own node_modules;\n // without the re-list, the glob reaches into it.\n exclude: [...(options.exclude ?? ['**/node_modules/**', '**/dist/**', 'test/integration/**', ...SPA_FILES])],\n ...(options.setupFiles !== undefined && { setupFiles: [...options.setupFiles] }),\n server: {\n deps: {\n // A `node_modules` dependency is externalized by default, so Node's\n // own ESM loader resolves a `cloudflare:workers` specifier and rejects\n // the scheme before `resolve.alias` is ever consulted. Inlining routes\n // it back through Vite, where the alias applies.\n inline: [...(options.serverDepsInline ?? ['dofs'])],\n },\n },\n coverage: {\n provider: 'v8',\n // Vitest 4 removed `coverage.all`; an explicit `include` now reports\n // every matching file whether or not a test imported it, which is the\n // behaviour the source repos' `all: true` was there to get: a brand-new\n // module with no test is counted as zero rather than being invisible,\n // which is the exact regression this gate exists to catch.\n reporter: ['text', 'lcov', 'html'],\n reportsDirectory: options.reportsDirectory ?? './coverage',\n include: [...coverageInclude],\n exclude: coverageExclude,\n ...(options.thresholds !== undefined && { thresholds: { ...options.thresholds } }),\n },\n },\n });\n}\n"],
5
- "mappings": "+EAmCA,OAAS,gBAAAA,MAAiC,gBAC1C,OAAS,4BAAAC,EAA0B,8BAAAC,EAA4B,mBAAAC,EAAiB,oBAAAC,MAAwB,sBA4GxG,MAAMC,EAA+B,CAAC,cAAe,8BAA+B,6BAA6B,EAW3GC,EAAgD,CACpD,aACA,eACA,gBACA,YACA,cACA,gBACA,cACA,kBACA,gBACA,mBACA,eAeI,SAAUC,EAAuBC,EAAmC,CAAA,EAAE,CAC1E,MAAMC,EAAOD,EAAQ,MAAQ,IAAI,IAAI,IAAK,YAAY,GAAG,EAAE,KACrDE,EAAkBF,EAAQ,iBAAmB,CAAC,uBAAwB,8BAA+B,yBAAyB,EAC9HG,EAAkB,CAAC,GAAGL,EAA4B,GAAIE,EAAQ,iBAAmB,CAAA,CAAG,EASpFI,EAAU,CACd,GATkBR,EAAiB,CACnC,MAAOI,EAAQ,OAAS,UACxB,KAAAC,EACA,SAAUD,EAAQ,QAAU,OAAY,CAAA,EAAMA,EAAQ,UAAYN,EAClE,MAAOM,EAAQ,OAASP,EACzB,EAIgB,OAAQY,GAAU,OAAOA,EAAM,MAAS,UAAY,CAACA,EAAM,KAAK,WAAW,SAAS,CAAC,EACpG,GAAIL,EAAQ,SAAW,CAAA,GAGzB,OAAOR,EAAa,CAClB,GAAIQ,EAAQ,UAAY,QAAa,CAAE,QAAS,CAAC,GAAGA,EAAQ,OAAO,CAAC,EACpE,QAAS,CAAE,MAAOI,EAAS,WAAY,CAAC,GAAGT,EAAiB,GAAIK,EAAQ,YAAc,CAAA,CAAG,CAAC,EAC1F,KAAM,CACJ,QAAS,GACT,YAAa,OACb,QAAS,CAAC,GAAIA,EAAQ,SAAW,CAAC,yBAAyB,CAAE,EAG7D,QAAS,CAAC,GAAIA,EAAQ,SAAW,CAAC,qBAAsB,aAAc,sBAAuB,GAAGH,CAAS,CAAE,EAC3G,GAAIG,EAAQ,aAAe,QAAa,CAAE,WAAY,CAAC,GAAGA,EAAQ,UAAU,CAAC,EAC7E,OAAQ,CACN,KAAM,CAKJ,OAAQ,CAAC,GAAIA,EAAQ,kBAAoB,CAAC,MAAM,CAAE,IAGtD,SAAU,CACR,SAAU,KAMV,SAAU,CAAC,OAAQ,OAAQ,MAAM,EACjC,iBAAkBA,EAAQ,kBAAoB,aAC9C,QAAS,CAAC,GAAGE,CAAe,EAC5B,QAASC,EACT,GAAIH,EAAQ,aAAe,QAAa,CAAE,WAAY,CAAE,GAAGA,EAAQ,UAAU,CAAE,IAGpF,CACH,CApDgBM,EAAAP,EAAA",
6
- "names": ["defineConfig", "DEFAULT_CLOUDFLARE_MOCKS", "DEFAULT_WORKSPACE_PACKAGES", "KIT_NO_EXTERNAL", "workspaceAliases", "SPA_FILES", "CANONICAL_COVERAGE_EXCLUDE", "defineUnitVitestConfig", "options", "root", "coverageInclude", "coverageExclude", "aliases", "alias", "__name"]
4
+ "sourcesContent": ["/**\n * The unit-test Vitest config for the worker-and-packages half of the suite.\n *\n * Provenance: converged from all nine repos' `vitest.config.mts`. The coverage\n * block is Durable-DAV-Router's (the most complete: v8 provider, explicit\n * include/exclude patterns, thresholds with the reasoning for why they sit just\n * under the measured value); the alias block is the union of Durable-DAV's\n * `cloudflare:*` mocks, every repo's `@scope/* → src` workspace table, and the\n * shared `@/` + `~/` prefixes — see {@link ./vitest-aliases.js}.\n *\n * Canonical decisions:\n *\n * 1. **Every file matching `include` is reported** — Vitest 4 removed\n * `coverage.all`, and an explicit `include` now covers files no test\n * imported. That is the behaviour the source repos configured `all: true` for,\n * and the reason it mattered: without it a brand-new module with no test is\n * invisible rather than counted as zero, which is the exact regression this\n * gate exists to catch.\n * 2. **The SPA is excluded here**, so this config and `defineWebVitestConfig()`\n * partition the suite rather than each running all of it. The default covers\n * every suite shape the family uses (`test/web/**`, `test/**​/web-*`,\n * `apps/web/**`); see `defineRepoVitestConfig()` for the single-file\n * `projects` composition the AWS/Mail-Meow/CalDAV repos use.\n * 3. **A custom `exclude` re-lists `node_modules`** — `test/` is a workspace\n * project and therefore has its own, so without the re-list the glob reaches\n * into `test/node_modules` and tries to run other packages' suites.\n * 4. **Thresholds are a consumer argument**, not a kit default. A floor is a\n * per-repo ratchet measured against that repo's suite; the kit cannot know a\n * number, and guessing one is how floors get lowered.\n * 5. **`@rexezuge/*` is never externalized** — see `KIT_NO_EXTERNAL`: the kit\n * ships ESM `dist/` with bundler-style extensionless imports, which Node's\n * resolver refuses, so the kit stays inside Vite's pipeline (the same\n * resolver that bundles the worker).\n */\n\nimport { defineConfig, type Plugin } from 'vitest/config';\nimport { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_DEDUPE, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';\nimport type { VitestAlias } from './vitest-aliases.ts';\n\nexport type { VitestAlias } from './vitest-aliases.ts';\n\n/**\n * Coverage thresholds, in the four figures Vitest gates on.\n */\nexport interface CoverageThresholds {\n readonly statements?: number;\n readonly branches?: number;\n readonly functions?: number;\n readonly lines?: number;\n}\n\n/**\n * What `defineUnitVitestConfig` accepts. Every field is optional: the defaults\n * cover the canonical monorepo layout, and a consumer overrides only what its\n * tree actually differs in.\n */\nexport interface UnitVitestConfigOptions {\n /**\n * The consuming repo's npm scope, e.g. `'@myapp'`. When supplied, `@scope/*`\n * workspace aliases are generated from `packages` (plus `background` under\n * `apps/`); when omitted, only the `cloudflare:*`, `@/` and `~/` aliases\n * apply and `aliases` carries the workspace table by hand.\n */\n readonly scope?: string;\n /**\n * Workspace package directory names. Defaults to the family superset; a repo\n * without a domain package keeps the default harmlessly (its alias never\n * matches).\n */\n readonly packages?: readonly string[];\n /**\n * Which `cloudflare:*` mocks to alias. Defaults to workers/sockets/workflows.\n */\n readonly mocks?: readonly string[];\n /**\n * Extra resolver entries, applied after the canonical ones (e.g. the `hono`\n * dedupe two repos carry, or an `/index.ts` exact entry).\n */\n readonly aliases?: readonly VitestAlias[];\n /**\n * Where the repo root is, as a file URL. Defaults to the directory this\n * factory is *called* from, which is the repo root's `vitest.config.mts`.\n * Pass `new URL('.', import.meta.url).href` explicitly from the caller —\n * never rely on this module's own URL, which points into `node_modules`.\n */\n readonly root?: string;\n /**\n * Which suites to collect. Defaults to the whole unit suite.\n */\n readonly include?: readonly string[];\n /**\n * Suite paths to skip, replacing the default. Defaults re-list\n * `node_modules`/`dist`/`integration` plus every SPA shape.\n */\n readonly exclude?: readonly string[];\n /**\n * `node_modules` specifiers to inline through Vite rather than externalize.\n * Defaults to `['dofs']` (Durable-DAV: `dofs` imports `cloudflare:workers`,\n * which Node rejects before `resolve.alias` is consulted).\n */\n readonly serverDepsInline?: readonly string[];\n /**\n * Resolver `noExternal` patterns. Defaults to keeping `@rexezuge/*` inside\n * Vite's pipeline; see `KIT_NO_EXTERNAL`.\n */\n readonly noExternal?: readonly (string | RegExp)[];\n /**\n * Vite plugins for the suite (rare on the backend half; the SPA half passes\n * `react()` here).\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Setup files run before each test file (e.g. AWS's floci guard, Meow's\n * backend/web setups).\n */\n readonly setupFiles?: readonly string[];\n /**\n * Coverage `include` globs. Defaults to the worker plus every workspace\n * package's `src`.\n */\n readonly coverageInclude?: readonly string[];\n /**\n * Coverage `exclude` globs, merged with the canonical set.\n */\n readonly coverageExclude?: readonly string[];\n /**\n * Coverage floors. Omitted by default; a repo that wants them sets them.\n */\n readonly thresholds?: CoverageThresholds;\n /**\n * Where the coverage report is written.\n */\n readonly reportsDirectory?: string;\n}\n\n/**\n * The SPA's suites, excluded here so the two configs partition the suite.\n *\n * Every shape the family uses: the `test/web/**` directory convention\n * (CalDAV-Bridge, Mail-Meow), the root-suite `web-*` naming convention\n * (Durable-DAV-Router), and suites bundled under `apps/web` (Mail-Otter).\n * `defineWebVitestConfig()` includes the same globs, so a file is collected by\n * exactly one config.\n */\nconst SPA_FILES: readonly string[] = ['test/web/**', 'test/**/web-*.test.{ts,tsx}', 'apps/web/**/*.test.{ts,tsx}'];\n\n/**\n * Coverage `exclude` globs converged from the source repos.\n *\n * The categories: build and test tooling (`scripts/` grows with project surface,\n * not complexity, and the god-file guard excludes it for the same reason), test\n * files, declarations, re-export barrels (`index.ts` carries no logic of its\n * own), model records, generated files (the SPA shell is a one-line HTML blob\n * with no logic to exercise), and type-only modules.\n */\nconst CANONICAL_COVERAGE_EXCLUDE: readonly string[] = [\n 'scripts/**',\n '**/*.test.ts',\n '**/*.test.tsx',\n '**/*.d.ts',\n '**/index.ts',\n '**/types.d.ts',\n '**/model/**',\n '**/generated/**',\n '**/D1Types.ts',\n '**/ServiceEnv.ts',\n '**/env.d.ts',\n];\n\n/**\n * Build the unit-test config.\n *\n * ```ts\n * // vitest.config.mts\n * import { defineUnitVitestConfig } from '@rexezuge/tooling/vitest';\n * export default defineUnitVitestConfig({\n * scope: '@myapp',\n * thresholds: { statements: 60, branches: 55, functions: 65, lines: 60 },\n * });\n * ```\n */\nexport function defineUnitVitestConfig(options: UnitVitestConfigOptions = {}): ReturnType<typeof defineConfig> {\n const root = options.root ?? new URL('.', import.meta.url).href;\n const coverageInclude = options.coverageInclude ?? ['apps/api/src/**/*.ts', 'apps/background/src/**/*.ts', 'packages/**/src/**/*.ts'];\n const coverageExclude = [...CANONICAL_COVERAGE_EXCLUDE, ...(options.coverageExclude ?? [])];\n const baseAliases = workspaceAliases({\n scope: options.scope ?? '@unused',\n root,\n packages: options.scope === undefined ? [] : (options.packages ?? DEFAULT_WORKSPACE_PACKAGES),\n mocks: options.mocks ?? DEFAULT_CLOUDFLARE_MOCKS,\n });\n // A placeholder scope contributes no `@unused/*` entries; the mocks plus\n // `@/`/`~/` survive either way.\n const aliases = [\n ...baseAliases.filter((alias) => typeof alias.find !== 'string' || !alias.find.startsWith('@unused')),\n ...(options.aliases ?? []),\n ];\n\n return defineConfig({\n ...(options.plugins !== undefined && { plugins: [...options.plugins] }),\n resolve: {\n alias: aliases,\n noExternal: [...KIT_NO_EXTERNAL, ...(options.noExternal ?? [])],\n // The peer runtime a consumer and the kit must agree on. `@rexezuge/web`\n // declares `react`, `react-dom` and `lucide-react` as peers, which under a\n // registry install means neither package carries its own copy. Under the\n // `link:` workflow this repo's own README recommends, the symlinked\n // directory **does** have one — so the kit resolves its own React and the\n // consumer resolves theirs, and every hook in a kit component throws\n // `Cannot read properties of null (reading 'useState')`. Dedupe points the\n // bare specifier at one copy for both.\n dedupe: [...KIT_DEDUPE],\n },\n test: {\n globals: true,\n environment: 'node',\n include: [...(options.include ?? ['test/**/*.test.{ts,tsx}'])],\n // `test` is a workspace project and therefore has its own node_modules;\n // without the re-list, the glob reaches into it.\n exclude: [...(options.exclude ?? ['**/node_modules/**', '**/dist/**', 'test/integration/**', ...SPA_FILES])],\n ...(options.setupFiles !== undefined && { setupFiles: [...options.setupFiles] }),\n server: {\n deps: {\n // A `node_modules` dependency is externalized by default, so Node's\n // own ESM loader resolves a `cloudflare:workers` specifier and rejects\n // the scheme before `resolve.alias` is ever consulted. Inlining routes\n // it back through Vite, where the alias applies.\n inline: [...(options.serverDepsInline ?? ['dofs'])],\n },\n },\n coverage: {\n provider: 'v8',\n // Vitest 4 removed `coverage.all`; an explicit `include` now reports\n // every matching file whether or not a test imported it, which is the\n // behaviour the source repos' `all: true` was there to get: a brand-new\n // module with no test is counted as zero rather than being invisible,\n // which is the exact regression this gate exists to catch.\n reporter: ['text', 'lcov', 'html'],\n reportsDirectory: options.reportsDirectory ?? './coverage',\n include: [...coverageInclude],\n exclude: coverageExclude,\n ...(options.thresholds !== undefined && { thresholds: { ...options.thresholds } }),\n },\n },\n });\n}\n"],
5
+ "mappings": "+EAmCA,OAAS,gBAAAA,MAAiC,gBAC1C,OAAS,4BAAAC,EAA0B,8BAAAC,EAA4B,cAAAC,EAAY,mBAAAC,EAAiB,oBAAAC,MAAwB,sBA4GpH,MAAMC,EAA+B,CAAC,cAAe,8BAA+B,6BAA6B,EAW3GC,EAAgD,CACpD,aACA,eACA,gBACA,YACA,cACA,gBACA,cACA,kBACA,gBACA,mBACA,eAeI,SAAUC,EAAuBC,EAAmC,CAAA,EAAE,CAC1E,MAAMC,EAAOD,EAAQ,MAAQ,IAAI,IAAI,IAAK,YAAY,GAAG,EAAE,KACrDE,EAAkBF,EAAQ,iBAAmB,CAAC,uBAAwB,8BAA+B,yBAAyB,EAC9HG,EAAkB,CAAC,GAAGL,EAA4B,GAAIE,EAAQ,iBAAmB,CAAA,CAAG,EASpFI,EAAU,CACd,GATkBR,EAAiB,CACnC,MAAOI,EAAQ,OAAS,UACxB,KAAAC,EACA,SAAUD,EAAQ,QAAU,OAAY,CAAA,EAAMA,EAAQ,UAAYP,EAClE,MAAOO,EAAQ,OAASR,EACzB,EAIgB,OAAQa,GAAU,OAAOA,EAAM,MAAS,UAAY,CAACA,EAAM,KAAK,WAAW,SAAS,CAAC,EACpG,GAAIL,EAAQ,SAAW,CAAA,GAGzB,OAAOT,EAAa,CAClB,GAAIS,EAAQ,UAAY,QAAa,CAAE,QAAS,CAAC,GAAGA,EAAQ,OAAO,CAAC,EACpE,QAAS,CACP,MAAOI,EACP,WAAY,CAAC,GAAGT,EAAiB,GAAIK,EAAQ,YAAc,CAAA,CAAG,EAS9D,OAAQ,CAAC,GAAGN,CAAU,GAExB,KAAM,CACJ,QAAS,GACT,YAAa,OACb,QAAS,CAAC,GAAIM,EAAQ,SAAW,CAAC,yBAAyB,CAAE,EAG7D,QAAS,CAAC,GAAIA,EAAQ,SAAW,CAAC,qBAAsB,aAAc,sBAAuB,GAAGH,CAAS,CAAE,EAC3G,GAAIG,EAAQ,aAAe,QAAa,CAAE,WAAY,CAAC,GAAGA,EAAQ,UAAU,CAAC,EAC7E,OAAQ,CACN,KAAM,CAKJ,OAAQ,CAAC,GAAIA,EAAQ,kBAAoB,CAAC,MAAM,CAAE,IAGtD,SAAU,CACR,SAAU,KAMV,SAAU,CAAC,OAAQ,OAAQ,MAAM,EACjC,iBAAkBA,EAAQ,kBAAoB,aAC9C,QAAS,CAAC,GAAGE,CAAe,EAC5B,QAASC,EACT,GAAIH,EAAQ,aAAe,QAAa,CAAE,WAAY,CAAE,GAAGA,EAAQ,UAAU,CAAE,IAGpF,CACH,CAhEgBM,EAAAP,EAAA",
6
+ "names": ["defineConfig", "DEFAULT_CLOUDFLARE_MOCKS", "DEFAULT_WORKSPACE_PACKAGES", "KIT_DEDUPE", "KIT_NO_EXTERNAL", "workspaceAliases", "SPA_FILES", "CANONICAL_COVERAGE_EXCLUDE", "defineUnitVitestConfig", "options", "root", "coverageInclude", "coverageExclude", "aliases", "alias", "__name"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/tooling",
3
- "version": "1.6.1",
3
+ "version": "1.7.1",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -19,6 +19,18 @@
19
19
  "./*": {
20
20
  "types": "./dist/*.d.ts",
21
21
  "default": "./dist/*.js"
22
+ },
23
+ "./src/*": {
24
+ "types": "./src/*.ts",
25
+ "default": "./src/*.ts"
26
+ },
27
+ "./src/*/*": {
28
+ "types": "./src/*/*.ts",
29
+ "default": "./src/*/*.ts"
30
+ },
31
+ "./src/*/*/*": {
32
+ "types": "./src/*/*/*.ts",
33
+ "default": "./src/*/*/*.ts"
22
34
  }
23
35
  },
24
36
  "files": [
@@ -26,7 +38,7 @@
26
38
  "src"
27
39
  ],
28
40
  "dependencies": {
29
- "@rexezuge/d1": "1.6.1"
41
+ "@rexezuge/d1": "1.7.1"
30
42
  },
31
43
  "peerDependencies": {
32
44
  "eslint": "^10.0.0",
package/src/index.ts CHANGED
@@ -30,7 +30,7 @@ export type { RepoBackendOptions, RepoVitestConfigOptions, RepoWebOptions } from
30
30
  export { defineIntegrationVitestConfig } from './vitest-integration.ts';
31
31
  export type { IntegrationVitestConfigOptions } from './vitest-integration.ts';
32
32
 
33
- export { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';
33
+ export { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_DEDUPE, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';
34
34
  export type { VitestAlias as WorkspaceAlias, WorkspaceAliasesOptions } from './vitest-aliases.ts';
35
35
 
36
36
  export { defineWebViteConfig, spaShellEmbedPlugin } from './vite.ts';
@@ -59,7 +59,14 @@ export function parseFlags(argv: readonly string[], spec: FlagSpec): ParsedFlags
59
59
  const flags: ParsedFlags = new Map();
60
60
 
61
61
  for (let index = 0; index < argv.length; index += 1) {
62
- const arg = argv[index];
62
+ // `?? ''` rather than `as string`. `argv[index]` is `string | undefined` under
63
+ // `noUncheckedIndexedAccess`, which this package's own tsconfig does not enable
64
+ // and a consuming repo's does — so an assertion is redundant here and required
65
+ // there, and a script that only typechecks in its author's repository is a
66
+ // script a consumer cannot adopt. The loop bound already proves the element is
67
+ // present, and `''` is not a flag, so the fallthrough reports it rather than
68
+ // hiding it.
69
+ const arg = argv[index] ?? '';
63
70
  if (!arg.startsWith('-')) {
64
71
  throw new Error(`Unexpected argument: ${arg}`);
65
72
  }
@@ -135,7 +142,7 @@ export function splitPositional(
135
142
  const rest: string[] = [];
136
143
 
137
144
  for (let index = 0; index < argv.length; index += 1) {
138
- const arg = argv[index];
145
+ const arg = argv[index] ?? '';
139
146
  if (arg.startsWith('-')) {
140
147
  rest.push(arg);
141
148
  continue;
@@ -59,9 +59,13 @@ export function parseWranglerTableRows(output: string): string[][] {
59
59
  if (cells.length < 2) {
60
60
  continue;
61
61
  }
62
- const firstCell = cells[0];
63
- // The header row and the horizontal rules are frame, not data.
64
- if (firstCell === HEADER_FIRST_CELL || firstCell.includes(RULE_CHARACTER)) {
62
+ // The header row and the horizontal rules are frame, not data; an empty row is
63
+ // frame too. Destructured rather than indexed so it is total under
64
+ // `noUncheckedIndexedAccess` as well as without it — a consuming repo enables
65
+ // that flag and this package does not, and a script that only typechecks in its
66
+ // author's repository is a script a consumer cannot adopt.
67
+ const [firstCell] = cells;
68
+ if (firstCell === undefined || firstCell === HEADER_FIRST_CELL || firstCell.includes(RULE_CHARACTER)) {
65
69
  continue;
66
70
  }
67
71
  rows.push(cells);
@@ -0,0 +1,190 @@
1
+ import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { validateLocales, validateLocalesCli } from './validate-locales.ts';
6
+
7
+ function repo(): string {
8
+ return mkdtempSync(path.join(tmpdir(), 'locales-'));
9
+ }
10
+
11
+ function bundle(root: string, tag: string, value: Record<string, unknown>): void {
12
+ const dir = path.join(root, 'locales', tag);
13
+ mkdirSync(dir, { recursive: true });
14
+ writeFileSync(path.join(dir, 'translation.json'), JSON.stringify(value));
15
+ }
16
+
17
+ describe('validateLocales', () => {
18
+ it('passes on two-way parity alone', () => {
19
+ const root = repo();
20
+ bundle(root, 'en', { common: { save: 'Save', cancel: 'Cancel' } });
21
+ bundle(root, 'de', { common: { save: 'Speichern', cancel: 'Abbrechen' } });
22
+ expect(validateLocales(path.join(root, 'locales')).problems).toEqual([]);
23
+ });
24
+
25
+ it('reports an empty value, which is indistinguishable from a missing key', () => {
26
+ // The check the header advertised and did not implement. i18next renders `''`
27
+ // for an empty value and for an absent key alike, so a locale can look complete
28
+ // in a diff and be blank on the page.
29
+ const root = repo();
30
+ bundle(root, 'en', { common: { save: 'Save' } });
31
+ bundle(root, 'de', { common: { save: '' } });
32
+ const problems = validateLocales(path.join(root, 'locales')).problems;
33
+ expect(problems.some((problem) => problem.problem.includes('empty value: common.save'))).toBe(true);
34
+ });
35
+
36
+ it('reports a non-string value', () => {
37
+ const root = repo();
38
+ bundle(root, 'en', { common: { save: 'Save' } });
39
+ bundle(root, 'de', { common: { save: 42 } });
40
+ const problems = validateLocales(path.join(root, 'locales')).problems;
41
+ expect(problems.some((problem) => problem.problem.includes('empty value'))).toBe(true);
42
+ });
43
+
44
+ it('reports a dropped placeholder', () => {
45
+ // Substitution is by name, so a translation that drops `{{count}}` renders the
46
+ // sentence with a hole in it and no error anywhere.
47
+ const root = repo();
48
+ bundle(root, 'en', { libraries: { indexed: 'Indexed {{count}} tracks' } });
49
+ bundle(root, 'de', { libraries: { indexed: 'Indizierte Tracks' } });
50
+ const problems = validateLocales(path.join(root, 'locales')).problems;
51
+ expect(problems.some((problem) => problem.problem.includes('placeholder mismatch at libraries.indexed'))).toBe(true);
52
+ });
53
+
54
+ it('accepts a placeholder that moved position', () => {
55
+ const root = repo();
56
+ bundle(root, 'en', { greeting: 'Hi {{name}}, you have {{count}}' });
57
+ bundle(root, 'de', { greeting: '{{count}} Nachrichten für {{name}}' });
58
+ expect(validateLocales(path.join(root, 'locales')).problems).toEqual([]);
59
+ });
60
+
61
+ it('reports a placeholder the base never had', () => {
62
+ const root = repo();
63
+ bundle(root, 'en', { greeting: 'Hi {{name}}' });
64
+ bundle(root, 'de', { greeting: 'Hi {{name}} {{surname}}' });
65
+ const problems = validateLocales(path.join(root, 'locales')).problems;
66
+ expect(problems.some((problem) => problem.problem.includes('placeholder mismatch'))).toBe(true);
67
+ });
68
+
69
+ it('reports both a missing and an extra key', () => {
70
+ const root = repo();
71
+ bundle(root, 'en', { common: { save: 'Save', cancel: 'Cancel' } });
72
+ bundle(root, 'de', { common: { save: 'Speichern', extra: 'Zusatz' } });
73
+ const problems = validateLocales(path.join(root, 'locales')).problems.map((problem) => problem.problem);
74
+ expect(problems.some((problem) => problem.includes('missing key: common.cancel'))).toBe(true);
75
+ expect(problems.some((problem) => problem.includes('extra key not in en: common.extra'))).toBe(true);
76
+ });
77
+
78
+ it('reports a bundle on disk with no declared counterpart', () => {
79
+ const root = repo();
80
+ bundle(root, 'en', { common: { save: 'Save' } });
81
+ bundle(root, 'fr', { common: { save: 'Enregistrer' } });
82
+ const report = validateLocales(path.join(root, 'locales'));
83
+ expect(report.locales).toEqual(['en', 'fr']);
84
+ expect(report.problems).toEqual([]);
85
+ });
86
+
87
+ it('refuses an empty base rather than reporting all clear', () => {
88
+ const root = repo();
89
+ bundle(root, 'en', {});
90
+ bundle(root, 'de', {});
91
+ const problems = validateLocales(path.join(root, 'locales')).problems;
92
+ expect(problems.some((problem) => problem.problem.includes('has no keys'))).toBe(true);
93
+ });
94
+
95
+ it('reports a directory that does not exist', () => {
96
+ const root = repo();
97
+ expect(validateLocales(path.join(root, 'nope')).problems.length).toBe(1);
98
+ });
99
+ });
100
+
101
+ /**
102
+ * Capture what the CLI wrote, so a gate's exit code and its report can be asserted
103
+ * together. The alternative — reading stdout — makes the test depend on the
104
+ * reporter's formatting rather than on the finding.
105
+ */
106
+ function capture(fn: () => number): { code: number; out: string } {
107
+ const original = { error: console.error, log: console.log };
108
+ let out = '';
109
+ console.error = (...args: unknown[]): void => void (out += `${args.join(' ')}\n`);
110
+ console.log = (...args: unknown[]): void => void (out += `${args.join(' ')}\n`);
111
+ try {
112
+ return { code: fn(), out };
113
+ } finally {
114
+ console.error = original.error;
115
+ console.log = original.log;
116
+ }
117
+ }
118
+
119
+ describe('validateLocalesCli --call-sites', () => {
120
+ it('passes a call site whose inline default equals the bundle', () => {
121
+ const root = repo();
122
+ bundle(root, 'en', { common: { save: 'Save' } });
123
+ const src = path.join(root, 'src');
124
+ mkdirSync(src, { recursive: true });
125
+ writeFileSync(path.join(src, 'Button.tsx'), "const label = t('common.save', 'Save');\n");
126
+ const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
127
+ expect(out).toContain('Locale validation passed');
128
+ expect(code).toBe(0);
129
+ });
130
+
131
+ it('passes a default containing an apostrophe, which is the ordinary case', () => {
132
+ // The defect a real corpus found: a scan for either quote character stops at the
133
+ // apostrophe in `D1's` and reports `D1` as the whole default, so every line
134
+ // quoting an English possessive becomes a false "default disagrees".
135
+ const root = repo();
136
+ const text = "D1's daily write allowance is spent. Paused until {{time}} UTC; the scan resumes itself.";
137
+ bundle(root, 'en', { libraries: { scanPaused: text } });
138
+ const src = path.join(root, 'src');
139
+ mkdirSync(src, { recursive: true });
140
+ writeFileSync(path.join(src, 'LibraryRow.tsx'), `const paused = t('libraries.scanPaused', ${JSON.stringify(text)});\n`);
141
+ const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
142
+ expect(out).toContain('Locale validation passed');
143
+ expect(code).toBe(0);
144
+ });
145
+
146
+ it('fails a call site whose key is not in the bundle', () => {
147
+ // The check the header advertised and never implemented: bundle-to-bundle parity
148
+ // cannot see a key the application uses and the bundle lacks, because with one
149
+ // shipped language the whole per-tag body is skipped.
150
+ const root = repo();
151
+ bundle(root, 'en', { common: { save: 'Save' } });
152
+ const src = path.join(root, 'src');
153
+ mkdirSync(src, { recursive: true });
154
+ writeFileSync(path.join(src, 'View.tsx'), "const label = t('common.saved');\n");
155
+ const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
156
+ expect(out).toContain("t('common.saved') is not in the bundle");
157
+ expect(code).toBe(1);
158
+ });
159
+
160
+ it('fails a default that disagrees with the bundle', () => {
161
+ const root = repo();
162
+ bundle(root, 'en', { common: { save: 'Save' } });
163
+ const src = path.join(root, 'src');
164
+ mkdirSync(src, { recursive: true });
165
+ writeFileSync(path.join(src, 'View.tsx'), "const label = t('common.save', 'Store');\n");
166
+ const { code, out } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
167
+ expect(out).toContain('default disagrees with the bundle');
168
+ expect(code).toBe(1);
169
+ });
170
+
171
+ it('skips a dynamic key rather than guessing at it', () => {
172
+ const root = repo();
173
+ bundle(root, 'en', { common: { save: 'Save' } });
174
+ const src = path.join(root, 'src');
175
+ mkdirSync(src, { recursive: true });
176
+ writeFileSync(path.join(src, 'View.tsx'), 'const label = t(`common.${name}`);\n');
177
+ const { code } = capture(() => validateLocalesCli([path.join(root, 'locales'), `--call-sites=${src}`]));
178
+ expect(code).toBe(0);
179
+ });
180
+
181
+ it('does not look at call sites without the flag', () => {
182
+ const root = repo();
183
+ bundle(root, 'en', { common: { save: 'Save' } });
184
+ const src = path.join(root, 'src');
185
+ mkdirSync(src, { recursive: true });
186
+ writeFileSync(path.join(src, 'View.tsx'), "const label = t('common.neverShipped');\n");
187
+ const { code } = capture(() => validateLocalesCli([path.join(root, 'locales')]));
188
+ expect(code).toBe(0);
189
+ });
190
+ });
@@ -64,13 +64,47 @@ interface LocaleReport {
64
64
  /**
65
65
  Every dotted key path in a bundle, depth first.
66
66
  */
67
- function flatten(value: unknown, prefix = ''): string[] {
67
+ function flatten(value: unknown, prefix = '', out: Map<string, unknown> = new Map()): Map<string, unknown> {
68
68
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
69
- return prefix ? [prefix] : [];
69
+ if (prefix) out.set(prefix, value);
70
+ return out;
70
71
  }
71
72
  const entries = Object.entries(value as Record<string, unknown>);
72
- if (entries.length === 0) return prefix ? [prefix] : [];
73
- return entries.flatMap(([key, child]) => flatten(child, prefix ? `${prefix}.${key}` : key));
73
+ if (entries.length === 0) {
74
+ if (prefix) out.set(prefix, value);
75
+ return out;
76
+ }
77
+ for (const [key, child] of entries) {
78
+ flatten(child, prefix ? `${prefix}.${key}` : key, out);
79
+ }
80
+ return out;
81
+ }
82
+
83
+ /**
84
+ * The interpolation tokens in a value, sorted.
85
+ *
86
+ * Sorted so two values carrying the same tokens in different orders compare equal —
87
+ * substitution is by name, so order carries no meaning. `localeCompare` rather than
88
+ * the default comparator so a reported mismatch does not change with the machine's
89
+ * locale.
90
+ */
91
+ function placeholdersOf(value: unknown): string[] {
92
+ if (typeof value !== 'string') return [];
93
+ return [...new Set(value.match(/\{\{[^{}]+\}\}/g))].sort((left: string, right: string) => left.localeCompare(right));
94
+ }
95
+
96
+ /**
97
+ * A source file to check `t()` call sites under, and how far down to look.
98
+ */
99
+ interface CallSiteScope {
100
+ /**
101
+ Directory walked for source files.
102
+ */
103
+ dir: string;
104
+ /**
105
+ Extensions treated as source.
106
+ */
107
+ extensions: readonly string[];
74
108
  }
75
109
 
76
110
  /**
@@ -305,6 +339,21 @@ function bundleFor(localesDir: string, locale: string, shape: LocaleShape): stri
305
339
  return candidates.find((candidate) => existsSync(candidate));
306
340
  }
307
341
 
342
+ /**
343
+ * The base bundle, flattened, for a scope that checks the application against it.
344
+ *
345
+ * @throws when the bundle cannot be found or parsed — the caller reports that as a
346
+ * problem rather than reporting "all clear" against an empty key set, which is
347
+ * the one outcome a locale gate must never produce silently.
348
+ */
349
+ function bundleAt(localesDir: string, baseLocale: string, shape: LocaleShape): Map<string, unknown> {
350
+ const file = bundleFor(localesDir, baseLocale, shape);
351
+ if (file === undefined) {
352
+ throw new Error(`no bundle found for the base locale (expected ${baseLocale}/translation.json)`);
353
+ }
354
+ return flatten(readBundle(file));
355
+ }
356
+
308
357
  /**
309
358
  * Validate a directory of locale bundles against `baseLocale`'s key set.
310
359
  *
@@ -324,13 +373,14 @@ function validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleSha
324
373
  return { locales: [], keys: 0, problems };
325
374
  }
326
375
 
327
- let baseKeys: Set<string>;
376
+ let baseBundle: Map<string, unknown>;
328
377
  try {
329
- baseKeys = new Set(flatten(readBundle(baseFile)));
378
+ baseBundle = flatten(readBundle(baseFile));
330
379
  } catch (error: unknown) {
331
380
  problems.push({ locale: baseLocale, problem: `${baseFile}: ${error instanceof Error ? error.message : String(error)}` });
332
381
  return { locales: [], keys: 0, problems };
333
382
  }
383
+ const baseKeys = new Set(baseBundle.keys());
334
384
 
335
385
  if (baseKeys.size === 0) {
336
386
  // An empty base is the one defect that reaches the most users: it is the fallback
@@ -347,18 +397,40 @@ function validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleSha
347
397
  problems.push({ locale, problem: 'no bundle found' });
348
398
  continue;
349
399
  }
350
- let keys: Set<string>;
400
+ let bundle: Map<string, unknown>;
351
401
  try {
352
- keys = new Set(flatten(readBundle(file)));
402
+ bundle = flatten(readBundle(file));
353
403
  } catch (error: unknown) {
354
404
  problems.push({ locale, problem: `${file}: ${error instanceof Error ? error.message : String(error)}` });
355
405
  continue;
356
406
  }
357
407
  for (const key of baseKeys) {
358
- if (!keys.has(key)) problems.push({ locale, problem: `missing key: ${key}` });
408
+ if (!bundle.has(key)) problems.push({ locale, problem: `missing key: ${key}` });
359
409
  }
360
- for (const key of keys) {
361
- if (!baseKeys.has(key)) problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });
410
+ for (const [key, value] of bundle) {
411
+ if (!baseKeys.has(key)) {
412
+ problems.push({ locale, problem: `extra key not in ${baseLocale}: ${key}` });
413
+ continue;
414
+ }
415
+ // An empty value is reported for the base too. i18next renders `''` for a key
416
+ // whose value is empty and for a key that is absent, so the two are the same
417
+ // blank screen — which is why a "translated" locale can look complete in a
418
+ // diff and be missing on the page.
419
+ if (typeof value !== 'string' || value === '') {
420
+ problems.push({ locale, problem: `empty value: ${key} — indistinguishable from a missing key at runtime` });
421
+ continue;
422
+ }
423
+ // Placeholder parity. Substitution is by name, so a translation that drops
424
+ // `{{count}}` renders the sentence with a hole in it and no error anywhere.
425
+ const expected = placeholdersOf(baseBundle.get(key));
426
+ if (expected.length === 0) continue;
427
+ const actual = placeholdersOf(value);
428
+ if (expected.length !== actual.length || expected.some((token, index) => token !== actual[index])) {
429
+ problems.push({
430
+ locale,
431
+ problem: `placeholder mismatch at ${key}: ${locale} has ${JSON.stringify(actual)}, ${baseLocale} has ${JSON.stringify(expected)}`,
432
+ });
433
+ }
362
434
  }
363
435
  }
364
436
 
@@ -366,17 +438,148 @@ function validateLocales(localesDir: string, baseLocale = 'en', shape: LocaleSha
366
438
  }
367
439
 
368
440
  /**
369
- CLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?])`.
441
+ * Every `t('key')` call site under a scope, with its inline default if it has one.
442
+ *
443
+ * This is the only part of the check that reaches the application rather than the
444
+ * bundles: the rest compare bundle to bundle, so with one shipped language the whole
445
+ * per-tag body is skipped and the script reports `ALL OK` having checked nothing
446
+ * about the product — it cannot see that a key was used and absent, because the
447
+ * string in the bundle did not exist to be wrong *about* anything.
448
+ *
449
+ * Dynamic keys cannot be resolved statically and are skipped rather than guessed:
450
+ * a computed key that happens to start with a literal is a finding nobody can act
451
+ * on, and one finding nobody can act on trains people to ignore the report.
452
+ */
453
+ function collectCallSites(scope: CallSiteScope, baseKeys: Set<string>, baseBundle: Map<string, unknown>): LocaleProblem[] {
454
+ const problems: LocaleProblem[] = [];
455
+ const walk = (dir: string): void => {
456
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
457
+ const full = path.join(dir, entry.name);
458
+ if (entry.isDirectory()) {
459
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name === 'coverage') continue;
460
+ walk(full);
461
+ continue;
462
+ }
463
+ if (scope.extensions.every((extension) => !entry.name.endsWith(extension))) continue;
464
+ const source = readFileSync(full, 'utf8');
465
+ // `t('…')` / `t("…")` with a string literal first argument. The key is the
466
+ // single source of truth for what is rendered, so anything else is out of scope.
467
+ const pattern = /\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;
468
+ for (const match of source.matchAll(pattern)) {
469
+ const key = match[2];
470
+ if (key.includes('${') || key.includes('{{')) continue;
471
+ const where = path.relative(process.cwd(), full) || full;
472
+ if (!baseKeys.has(key)) {
473
+ problems.push({
474
+ locale: 'call-site',
475
+ problem: `${where}: t('${key}') is not in the bundle — it renders as the inline default and is untranslatable`,
476
+ });
477
+ continue;
478
+ }
479
+ // A default that disagrees with the shipped bundle **fails**: one of the two
480
+ // is a bug, and the default is the one that renders verbatim the day the key
481
+ // goes missing — which is the fallback path the whole check is about.
482
+ if (!match[3]) continue;
483
+ const inline = readDefault(source, match.index + match[0].length);
484
+ if (inline === null) continue;
485
+ const bundled = baseBundle.get(key);
486
+ if (inline !== bundled) {
487
+ problems.push({
488
+ locale: 'call-site',
489
+ problem: `${where}: t('${key}', …) default disagrees with the bundle — bundle=${JSON.stringify(bundled)} default=${JSON.stringify(inline)}`,
490
+ });
491
+ }
492
+ }
493
+ }
494
+ };
495
+ walk(scope.dir);
496
+ return problems;
497
+ }
498
+
499
+ /**
500
+ * The first string literal at `from`, or `null` when the next token is not one.
501
+ *
502
+ * The terminator is the literal's **own** quote character and never the other one.
503
+ * A default that contains an apostrophe is the ordinary case here — these bundles
504
+ * say things like `D1's daily write allowance` — so a scan that accepts either
505
+ * quote stops at the apostrophe and reports `D1` as the whole default, turning a
506
+ * correct file into a "default disagrees" failure on every line that quotes an
507
+ * English possessive.
508
+ */
509
+ function readDefault(source: string, from: number): string | null {
510
+ const rest = source.slice(from).replace(/^\s+/, '');
511
+ const quote = rest[0];
512
+ if (quote !== "'" && quote !== '"') return null;
513
+ const body = rest.slice(1);
514
+ const closer = quote === "'" ? /^(?:[^'\\]|\\.)*'/ : /^(?:[^"\\]|\\.)*"/;
515
+ const match = closer.exec(body);
516
+ if (!match) return null;
517
+ return decodeStringLiteral(body.slice(0, match[0].length - 1));
518
+ }
519
+
520
+ /**
521
+ * Decode a JS string literal as written in source, escapes and all.
522
+ *
523
+ * Only the escapes these bundles use are handled. An unrecognised one is passed
524
+ * through as the backslash plus the character rather than throwing: a validator
525
+ * that crashes on an unfamiliar escape reports nothing at all, which is worse than
526
+ * reporting a value it had to guess at.
527
+ */
528
+ function decodeStringLiteral(raw: string): string {
529
+ return raw.replaceAll(/\\(.)/gs, (whole, char: string) => {
530
+ switch (char) {
531
+ case 'n': {
532
+ return '\n';
533
+ }
534
+ case 't': {
535
+ return '\t';
536
+ }
537
+ case 'r': {
538
+ return '\r';
539
+ }
540
+ case '\\':
541
+ case "'":
542
+ case '"':
543
+ case '`': {
544
+ return char;
545
+ }
546
+ default: {
547
+ return whole;
548
+ }
549
+ }
550
+ });
551
+ }
552
+
553
+ /**
554
+ CLI entry: `validateLocalesCli(['[locales-dir]?', '--shape=auto|dir|file|module'?, '--base=<tag>'?, '--call-sites=<src-dir>'?])`.
555
+
556
+ `--call-sites=<dir>` opts into the application-side checks: every `t('key')` under
557
+ `<dir>` must resolve against the base bundle, and any inline default must equal the
558
+ bundled value. Without the flag the script stays bundle-to-bundle, because that is
559
+ the only part it can answer for a repo whose bundles are consumed by something
560
+ other than `t()` — a backend string table, for instance.
370
561
  */
371
562
  function validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): number {
372
563
  const dir = argv.find((arg) => !arg.startsWith('--')) ?? 'apps/web/src/locales';
373
564
  const shape = (argv.find((arg) => arg.startsWith('--shape='))?.slice('--shape='.length) ?? 'auto') as LocaleShape;
374
565
  const base = argv.find((arg) => arg.startsWith('--base='))?.slice('--base='.length) ?? 'en';
566
+ const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);
375
567
 
376
568
  const report = validateLocales(dir, base, shape);
377
- if (report.problems.length > 0) {
378
- console.error(`Locale validation failed for ${dir} (${report.problems.length} problem(s)):`);
379
- for (const problem of report.problems) console.error(` - ${problem.locale}: ${problem.problem}`);
569
+ const problems = [...report.problems];
570
+
571
+ if (callSiteDir !== undefined && existsSync(callSiteDir)) {
572
+ try {
573
+ const baseBundle = bundleAt(dir, base, shape);
574
+ problems.push(...collectCallSites({ dir: callSiteDir, extensions: ['.ts', '.tsx'] }, new Set(baseBundle.keys()), baseBundle));
575
+ } catch (error: unknown) {
576
+ problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });
577
+ }
578
+ }
579
+
580
+ if (problems.length > 0) {
581
+ console.error(`Locale validation failed for ${dir} (${problems.length} problem(s)):`);
582
+ for (const problem of problems) console.error(` - ${problem.locale}: ${problem.problem}`);
380
583
  return 1;
381
584
  }
382
585
  console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);