@rexezuge/tooling 1.9.1 → 1.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/eslint.d.ts.map +1 -1
- package/dist/eslint.js +1 -1
- package/dist/eslint.js.map +2 -2
- package/dist/scripts/check-god-files.js +2 -2
- package/dist/scripts/check-god-files.js.map +3 -3
- package/dist/scripts/lib/entrypoint.d.ts +27 -0
- package/dist/scripts/lib/entrypoint.d.ts.map +1 -0
- package/dist/scripts/lib/entrypoint.js +1 -0
- package/dist/scripts/lib/entrypoint.js.map +7 -0
- package/dist/scripts/spa-shell.js +2 -2
- package/dist/scripts/spa-shell.js.map +3 -3
- package/dist/scripts/validate-locales.js +5 -5
- package/dist/scripts/validate-locales.js.map +3 -3
- package/dist/scripts/verify-migrations.js +2 -2
- package/dist/scripts/verify-migrations.js.map +3 -3
- package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/patches.js +3 -3
- package/dist/scripts/wrangler-config/patches.js.map +3 -3
- package/dist/scripts/wrangler-config/resources.d.ts +17 -7
- package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/resources.js +1 -1
- package/dist/scripts/wrangler-config/resources.js.map +3 -3
- package/dist/scripts/wrangler-config/types.d.ts +3 -2
- package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
- package/dist/scripts/wrangler-config/types.js.map +2 -2
- package/dist/vite.d.ts +21 -0
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +3 -3
- package/dist/vite.js.map +2 -2
- package/package.json +3 -3
- package/src/eslint.ts +9 -1
- package/src/scripts/check-god-files.ts +2 -2
- package/src/scripts/lib/entrypoint.test.ts +60 -0
- package/src/scripts/lib/entrypoint.ts +39 -0
- package/src/scripts/spa-shell.ts +2 -2
- package/src/scripts/validate-locales.ts +2 -2
- package/src/scripts/verify-migrations.ts +2 -2
- package/src/scripts/wrangler-config/patches.ts +11 -2
- package/src/scripts/wrangler-config/resources.test.ts +49 -0
- package/src/scripts/wrangler-config/resources.ts +38 -16
- package/src/scripts/wrangler-config/types.ts +3 -2
- package/src/vite.ts +31 -1
package/dist/eslint.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eslint.d.ts","sourceRoot":"","sources":["../src/eslint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AASH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAGvD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C;;;OAGG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC;;;;;;;;OAQG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC;CAC5C;AAsCD;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,UAAU,CAAC,WAAW,
|
|
1
|
+
{"version":3,"file":"eslint.d.ts","sourceRoot":"","sources":["../src/eslint.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AASH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAGvD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;;OAIG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C;;;OAGG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC;;;;;;;;OAQG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC;CAC5C;AAsCD;;;;;;;;;;GAUG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,qBAAqB,GAAG,UAAU,CAAC,WAAW,CAoI3F"}
|
package/dist/eslint.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var g=Object.defineProperty;var e=(s,t)=>g(s,"name",{value:t,configurable:!0});import r from"globals";import i from"typescript-eslint";import n from"eslint-plugin-unicorn";import{configs as l}from"eslint-plugin-sonarjs";import d from"eslint-plugin-regexp";import u from"eslint-config-prettier";import x from"eslint-plugin-prettier";import{DEFAULT_PROJECT_DIRS as j,layerBans as R,restrictedDynamicImports as S,restrictedImports as b}from"./eslint-boundaries.js";import{SONARJS_RULES as C,TEST_RULES as E,TYPESCRIPT_RULES as D,UNICORN_RULES as L}from"./eslint-rules.js";function h(s){return s}e(h,"asConfig");function k(s){return s}e(k,"asRules");function A(s){const{scope:t}=s,c=s.projectDirs??j,m=R(t).filter(p=>c.some(f=>p.dir.startsWith(f))),a=s.extraLayers??[],o=[...m,...a];return i.config({ignores:["eslint.config.mjs","eslint.config.js","scripts/**","worker-configuration.d.ts","local/**","app/dist/**","apps/web/dist/**","apps/*/dist/**","src/generated/**","apps/api/src/generated/**","coverage/**","coverage-integration/**","coverage-web/**","node_modules/**",...s.extraIgnores??[]]},{files:["**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}"],languageOptions:{globals:r.node}},{files:["**/*.{ts,mts,cts,tsx}"],extends:i.configs.recommendedTypeChecked,languageOptions:{parserOptions:{projectService:!0,tsconfigRootDir:s.tsconfigRootDir??process.cwd()}}},{files:["**/*.{ts,mts,cts,tsx}"],rules:D},n.configs["flat/recommended"]??n.configs.recommended,l.recommended,{rules:L},{rules:C},d.configs["flat/recommended"],u,{plugins:{prettier:x},rules:{"prettier/prettier":"error"}},...b(o),...S(o),{files:["apps/web/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}"],languageOptions:{globals:{...r.node,...r.browser}}},{files:["test/**/*.{ts,tsx,mts,cts}","**/*.test.{ts,tsx,mts,cts}","**/*.spec.{ts,tsx,mts,cts}"],rules:E})}e(A,"defineRepoLintConfig");export{A as defineRepoLintConfig};
|
package/dist/eslint.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/eslint.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The converged ESLint flat config for a monorepo in the Rexezuge family.\n *\n * Provenance: the base is Durable-DAV's `eslint.config.mjs` (the most\n * elaborate of the nine repos, with the layered `no-restricted-imports` boundary\n * rules). Merged in from the stacks that share the same plugin set:\n *\n * - **Edge-Sonic** — `test/**` is *not* ignored (it is linted like everything else,\n * with a narrow override block for Vitest idioms), and `unicorn/prefer-ternary`\n * is off. Edge-Sonic is also the source for the dynamic-`import()` boundary\n * guard and its `apps/web` layer block.\n * - **Mail-Meow** — `prettier/prettier` is an **error**, not a warning.\n * - **AWS-AccessBridge** — the `apps/api` DAO/service boundary uses\n * `allowTypeImports` where the source repos do not. It is also the source for\n * the anchored skip patterns and the symlink-safe walk that came out of its own\n * backlog.\n * - **CalDAV-Bridge, Mail-Otter, Durable-DAV-Router, Edge-Git, Agent-Router** —\n * the `provider-clients` / `webdav`+`dav-store` / `git-protocol`+`git-service`\n * layers and the per-client `apps/api` alternatives in the boundary table.\n *\n * Canonical decisions, and why each one:\n *\n * 1. **`prettier/prettier: 'error'`.** Three of the four source repos had it at\n * `warn`, which under `eslint --quiet` is unenforceable — a gate nobody can see\n * is a gate that has never run. Formatting drift is therefore a hard failure.\n * 2. **The layered boundary rules are parameterized by `scope`.** Every source\n * repo wrote the same blocks with a different npm scope hardcoded; the\n * factory takes `scope` (`'@myapp'`) and generates the `@myapp/*` patterns.\n * The table itself lives in {@link ./eslint-boundaries.ts} and covers the\n * family superset — a repo without a domain package never triggers its ban,\n * so no repo needs `extraLayers` for a known package.\n * 3. **`test/**` is linted, not ignored.** Durable-DAV/AWS/Mail-Meow ignored it;\n * Edge-Sonic does not, and records why: ~200 KB of test code had accumulated\n * violations that nothing reported.\n * 4. **`apps/web` is a layer in its own right**, banned from every `@scope/*`\n * package. Edge-Sonic is the only source with that block; the others had none,\n * which is how their layer table's \"may import: the browser\" was a convention\n * rather than a gate. A backend package imported by the SPA compiles and then\n * fails at bundle time, with the error pointing at the bundler.\n * 5. **jsdom + node globals for web files.** The sources ran `globals.node` only;\n * `apps/web` needs browser globals as well, and the vitest config for the SPA\n * runs under jsdom, so the lint environment matches the test environment.\n * 6. **`eslint-plugin-react-hooks` is NOT imported here.** The kit stays\n * zero-dependency, and the plugin belongs to the app that has JSX. A consumer\n * appends it — the README shows the four lines.\n *\n * The rule bodies live in {@link ./eslint-rules.ts} and the boundary table in\n * {@link ./eslint-boundaries.ts}; this file is the assembly. A repo that needs a\n * boundary the canonical table does not name passes `extraLayers` — see\n * {@link RepoLintConfigOptions}.\n */\n\nimport globals from 'globals';\nimport tseslint from 'typescript-eslint';\nimport unicorn from 'eslint-plugin-unicorn';\nimport { configs as sonarjsConfigs } from 'eslint-plugin-sonarjs';\nimport pluginRegexp from 'eslint-plugin-regexp';\nimport eslintConfigPrettier from 'eslint-config-prettier';\nimport prettier from 'eslint-plugin-prettier';\nimport type { FlatConfig } from 'typescript-eslint';\nimport { DEFAULT_PROJECT_DIRS, layerBans, restrictedDynamicImports, restrictedImports } from './eslint-boundaries.ts';\nimport type { LayerBan } from './eslint-boundaries.ts';\nimport { SONARJS_RULES, TEST_RULES, TYPESCRIPT_RULES, UNICORN_RULES } from './eslint-rules.ts';\n\n/**\n * What `defineRepoLintConfig` accepts.\n */\nexport interface RepoLintConfigOptions {\n /**\n * The consuming repo's npm scope, e.g. `'@myapp'`. Every `no-restricted-imports`\n * pattern in the boundary rules is derived from it, so the same factory serves\n * all nine repos.\n */\n readonly scope: string;\n /**\n * The workspace directories the layered boundary rules are scoped to, as repo-\n * relative globs. Defaults to the canonical layout the nine repos share.\n */\n readonly projectDirs?: readonly string[];\n /**\n * Extra ignore globs, merged with the canonical set.\n */\n readonly extraIgnores?: readonly string[];\n /**\n * Where `projectService` resolves the tsconfig from. Defaults to the directory\n * ESLint is invoked in, which is the repo root in every CI job.\n */\n readonly tsconfigRootDir?: string;\n /**\n * Extra boundary layers, appended to the canonical table.\n *\n * The escape valve for a repo whose layout has a boundary the canonical table\n * does not name — AWS-AccessBridge's `apps/api/src/endpoints/**` rule (\"route\n * classes must not import DAOs directly\") and its `aws4fetch` ban are the shape.\n * Same {@link LayerBan} form, so `extraLayers` flows through the\n * `no-restricted-imports` and the `no-restricted-syntax` guard alike.\n */\n readonly extraLayers?: readonly LayerBan[];\n}\n\n/**\n * One argument to `tseslint.config()`.\n */\ntype ConfigInput = Parameters<typeof tseslint.config>[number];\n\n/**\n * A plugin preset or config object as the source repos pass it.\n */\ntype MaybeConfig = FlatConfig.Config | readonly FlatConfig.Config[];\n\n/**\n * Bridge a third-party preset into `tseslint.config()`.\n *\n * `sonarjs`' `recommended` preset is typed as a union that includes the legacy\n * config shape, which `tseslint.config()` does not accept — but ESLint accepts it\n * at runtime, which is the only thing that matters here. One checked assertion,\n * rather than forking the plugin's own types.\n */\nfunction asConfig(config: MaybeConfig): ConfigInput {\n return config as ConfigInput;\n}\n\n/**\n * Bridge a rule block onto `tseslint.config()`'s `rules` field.\n *\n * The blocks in `eslint-rules.ts` are written as ESLint expects them —\n * `'off' | 'warn' | 'error' | [level, ...options]` — but spelled as data so a\n * rule's reason comment sits beside the rule itself. ESLint's own `RuleEntry`\n * union is narrower than the data shape, and widening every entry to that union\n * would buy nothing; one assertion here, with the reason, is the cheaper and\n * more honest of the two.\n */\nfunction asRules(block: Readonly<Record<string, unknown>>): FlatConfig.Config['rules'] {\n return block as FlatConfig.Config['rules'];\n}\n\n/**\n * Build the repo's flat config.\n *\n * Consumed from the repo root as three lines:\n *\n * ```js\n * // eslint.config.mjs\n * import { defineRepoLintConfig } from '@rexezuge/tooling/eslint';\n * export default defineRepoLintConfig({ scope: '@myapp' });\n * ```\n */\nexport function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig.ConfigArray {\n const { scope } = options;\n const projectDirs = options.projectDirs ?? DEFAULT_PROJECT_DIRS;\n const canonical = layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)));\n const extra = options.extraLayers ?? [];\n const bans = [...canonical, ...extra];\n\n return tseslint.config(\n {\n ignores: [\n 'eslint.config.mjs',\n 'eslint.config.js',\n 'scripts/**',\n 'worker-configuration.d.ts',\n 'local/**',\n 'app/dist/**',\n 'apps/web/dist/**',\n 'apps/*/dist/**',\n 'src/generated/**',\n 'apps/api/src/generated/**',\n 'coverage/**',\n 'coverage-integration/**',\n 'coverage-web/**',\n 'node_modules/**',\n ...(options.extraIgnores ?? []),\n ],\n },\n\n // Base: globals for all JS/TS source files. Node is the floor because the\n // scripts and the workers both run on it; the web block below adds browser\n // globals rather than replacing them, so a shared file that touches both\n // (there are several in `shared/`) still lints.\n {\n files: ['**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}'],\n languageOptions: {\n globals: globals.node,\n },\n },\n\n // Type-aware TS rules, scoped to TS files only.\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n extends: tseslint.configs.recommendedTypeChecked,\n languageOptions: {\n parserOptions: {\n projectService: true,\n tsconfigRootDir: options.tsconfigRootDir ?? process.cwd(),\n },\n },\n },\n\n // --- typescript-eslint overrides (identical in all four source stacks) ---\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n rules: asRules(TYPESCRIPT_RULES),\n },\n\n // --- Unicorn + SonarJS presets, then the family's off-block ---\n //\n // Both presets come first on purpose: UNICORN_RULES carries `sonarjs/*`\n // offs as well as `unicorn/*` ones (it is the family's single\n // \"deliberately does not follow\" block), and a preset applied after it\n // would re-enable them. That is exactly what shipped — the sonarjs preset\n // sat between the block and the rules it relaxed, so `void-use`,\n // `different-types-comparison`, `use-type-alias`, `redundant-type-aliases`,\n // `no-nested-assignment` and `no-all-duplicated-branches` linted as errors\n // in every consumer. The two presets do not share rule names, so their\n // relative order decides nothing.\n asConfig(unicorn.configs['flat/recommended']),\n asConfig(sonarjsConfigs.recommended),\n {\n rules: asRules(UNICORN_RULES),\n },\n\n // --- SonarJS advisories ---\n {\n rules: asRules(SONARJS_RULES),\n },\n\n // --- Regexp: static analysis for regular expressions ---\n asConfig(pluginRegexp.configs['flat/recommended']),\n\n // --- Prettier: formatting drift is a hard error ---\n //\n // Mail-Meow's decision, adopted repo-wide because the alternative is\n // unenforceable: `pnpm run lint` is `eslint --fix --quiet` in three of the\n // four source repos, and `--quiet` discards every warning, so a\n // `prettier/prettier` *warning* is a silent no-op. 242 files were in that\n // state in Edge-Sonic: the gate had never run.\n asConfig(eslintConfigPrettier),\n {\n plugins: { prettier },\n rules: {\n 'prettier/prettier': 'error',\n },\n },\n\n // --- Import direction guardrails (parameterized by scope) ---\n ...restrictedImports(bans),\n ...restrictedDynamicImports(bans),\n\n // --- Web: browser globals, matching the jsdom test environment ---\n //\n // The sources linted `apps/web` under `globals.node` only, so `window`,\n // `document` and `localStorage` read as undefined globals. The vitest web\n // config runs those suites under jsdom; the lint environment should agree\n // with the environment the code is executed in, or the rule is reporting\n // something untrue about how the file behaves.\n {\n files: ['apps/web/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}'],\n languageOptions: {\n globals: { ...globals.node, ...globals.browser },\n },\n },\n\n // --- Test suite ---\n //\n // `test/**` is deliberately NOT in the ignores list above. See TEST_RULES\n // for the override block and the reasoning behind it.\n {\n files: ['test/**/*.{ts,tsx,mts,cts}', '**/*.test.{ts,tsx,mts,cts}', '**/*.spec.{ts,tsx,mts,cts}'],\n rules: asRules(TEST_RULES),\n },\n );\n}\n"],
|
|
5
|
-
"mappings": "+EAoDA,OAAOA,MAAa,UACpB,OAAOC,MAAc,oBACrB,OAAOC,MAAa,wBACpB,OAAS,WAAWC,MAAsB,wBAC1C,OAAOC,MAAkB,uBACzB,OAAOC,MAA0B,yBACjC,OAAOC,MAAc,yBAErB,OAAS,wBAAAC,EAAsB,aAAAC,EAAW,4BAAAC,EAA0B,qBAAAC,MAAyB,yBAE7F,OAAS,iBAAAC,EAAe,cAAAC,EAAY,oBAAAC,EAAkB,iBAAAC,MAAqB,oBAwD3E,SAASC,EAASC,EAAmB,CACnC,OAAOA,CACT,CAFSC,EAAAF,EAAA,YAcT,SAASG,EAAQC,EAAwC,CACvD,OAAOA,CACT,CAFSF,EAAAC,EAAA,WAeH,SAAUE,EAAqBC,EAA8B,CACjE,KAAM,CAAE,MAAAC,CAAK,EAAKD,EACZE,EAAcF,EAAQ,aAAed,EACrCiB,EAAYhB,EAAUc,CAAK,EAAE,OAAQG,GAAUF,EAAY,KAAMG,GAAQD,EAAM,IAAI,WAAWC,CAAG,CAAC,CAAC,EACnGC,EAAQN,EAAQ,aAAe,CAAA,EAC/BO,EAAO,CAAC,GAAGJ,EAAW,GAAGG,CAAK,EAEpC,OAAO1B,EAAS,OACd,CACE,QAAS,CACP,oBACA,mBACA,aACA,4BACA,WACA,cACA,mBACA,iBACA,mBACA,4BACA,cACA,0BACA,kBACA,kBACA,GAAIoB,EAAQ,cAAgB,CAAA,IAQhC,CACE,MAAO,CAAC,sCAAsC,EAC9C,gBAAiB,CACf,QAASrB,EAAQ,OAKrB,CACE,MAAO,CAAC,uBAAuB,EAC/B,QAASC,EAAS,QAAQ,uBAC1B,gBAAiB,CACf,cAAe,CACb,eAAgB,GAChB,gBAAiBoB,EAAQ,iBAAmB,QAAQ,IAAG,KAM7D,CACE,MAAO,CAAC,uBAAuB,EAC/B,MAAeR,
|
|
4
|
+
"sourcesContent": ["/**\n * The converged ESLint flat config for a monorepo in the Rexezuge family.\n *\n * Provenance: the base is Durable-DAV's `eslint.config.mjs` (the most\n * elaborate of the nine repos, with the layered `no-restricted-imports` boundary\n * rules). Merged in from the stacks that share the same plugin set:\n *\n * - **Edge-Sonic** — `test/**` is *not* ignored (it is linted like everything else,\n * with a narrow override block for Vitest idioms), and `unicorn/prefer-ternary`\n * is off. Edge-Sonic is also the source for the dynamic-`import()` boundary\n * guard and its `apps/web` layer block.\n * - **Mail-Meow** — `prettier/prettier` is an **error**, not a warning.\n * - **AWS-AccessBridge** — the `apps/api` DAO/service boundary uses\n * `allowTypeImports` where the source repos do not. It is also the source for\n * the anchored skip patterns and the symlink-safe walk that came out of its own\n * backlog.\n * - **CalDAV-Bridge, Mail-Otter, Durable-DAV-Router, Edge-Git, Agent-Router** —\n * the `provider-clients` / `webdav`+`dav-store` / `git-protocol`+`git-service`\n * layers and the per-client `apps/api` alternatives in the boundary table.\n *\n * Canonical decisions, and why each one:\n *\n * 1. **`prettier/prettier: 'error'`.** Three of the four source repos had it at\n * `warn`, which under `eslint --quiet` is unenforceable — a gate nobody can see\n * is a gate that has never run. Formatting drift is therefore a hard failure.\n * 2. **The layered boundary rules are parameterized by `scope`.** Every source\n * repo wrote the same blocks with a different npm scope hardcoded; the\n * factory takes `scope` (`'@myapp'`) and generates the `@myapp/*` patterns.\n * The table itself lives in {@link ./eslint-boundaries.ts} and covers the\n * family superset — a repo without a domain package never triggers its ban,\n * so no repo needs `extraLayers` for a known package.\n * 3. **`test/**` is linted, not ignored.** Durable-DAV/AWS/Mail-Meow ignored it;\n * Edge-Sonic does not, and records why: ~200 KB of test code had accumulated\n * violations that nothing reported.\n * 4. **`apps/web` is a layer in its own right**, banned from every `@scope/*`\n * package. Edge-Sonic is the only source with that block; the others had none,\n * which is how their layer table's \"may import: the browser\" was a convention\n * rather than a gate. A backend package imported by the SPA compiles and then\n * fails at bundle time, with the error pointing at the bundler.\n * 5. **jsdom + node globals for web files.** The sources ran `globals.node` only;\n * `apps/web` needs browser globals as well, and the vitest config for the SPA\n * runs under jsdom, so the lint environment matches the test environment.\n * 6. **`eslint-plugin-react-hooks` is NOT imported here.** The kit stays\n * zero-dependency, and the plugin belongs to the app that has JSX. A consumer\n * appends it — the README shows the four lines.\n *\n * The rule bodies live in {@link ./eslint-rules.ts} and the boundary table in\n * {@link ./eslint-boundaries.ts}; this file is the assembly. A repo that needs a\n * boundary the canonical table does not name passes `extraLayers` — see\n * {@link RepoLintConfigOptions}.\n */\n\nimport globals from 'globals';\nimport tseslint from 'typescript-eslint';\nimport unicorn from 'eslint-plugin-unicorn';\nimport { configs as sonarjsConfigs } from 'eslint-plugin-sonarjs';\nimport pluginRegexp from 'eslint-plugin-regexp';\nimport eslintConfigPrettier from 'eslint-config-prettier';\nimport prettier from 'eslint-plugin-prettier';\nimport type { FlatConfig } from 'typescript-eslint';\nimport { DEFAULT_PROJECT_DIRS, layerBans, restrictedDynamicImports, restrictedImports } from './eslint-boundaries.ts';\nimport type { LayerBan } from './eslint-boundaries.ts';\nimport { SONARJS_RULES, TEST_RULES, TYPESCRIPT_RULES, UNICORN_RULES } from './eslint-rules.ts';\n\n/**\n * What `defineRepoLintConfig` accepts.\n */\nexport interface RepoLintConfigOptions {\n /**\n * The consuming repo's npm scope, e.g. `'@myapp'`. Every `no-restricted-imports`\n * pattern in the boundary rules is derived from it, so the same factory serves\n * all nine repos.\n */\n readonly scope: string;\n /**\n * The workspace directories the layered boundary rules are scoped to, as repo-\n * relative globs. Defaults to the canonical layout the nine repos share.\n */\n readonly projectDirs?: readonly string[];\n /**\n * Extra ignore globs, merged with the canonical set.\n */\n readonly extraIgnores?: readonly string[];\n /**\n * Where `projectService` resolves the tsconfig from. Defaults to the directory\n * ESLint is invoked in, which is the repo root in every CI job.\n */\n readonly tsconfigRootDir?: string;\n /**\n * Extra boundary layers, appended to the canonical table.\n *\n * The escape valve for a repo whose layout has a boundary the canonical table\n * does not name — AWS-AccessBridge's `apps/api/src/endpoints/**` rule (\"route\n * classes must not import DAOs directly\") and its `aws4fetch` ban are the shape.\n * Same {@link LayerBan} form, so `extraLayers` flows through the\n * `no-restricted-imports` and the `no-restricted-syntax` guard alike.\n */\n readonly extraLayers?: readonly LayerBan[];\n}\n\n/**\n * One argument to `tseslint.config()`.\n */\ntype ConfigInput = Parameters<typeof tseslint.config>[number];\n\n/**\n * A plugin preset or config object as the source repos pass it.\n */\ntype MaybeConfig = FlatConfig.Config | readonly FlatConfig.Config[];\n\n/**\n * Bridge a third-party preset into `tseslint.config()`.\n *\n * `sonarjs`' `recommended` preset is typed as a union that includes the legacy\n * config shape, which `tseslint.config()` does not accept — but ESLint accepts it\n * at runtime, which is the only thing that matters here. One checked assertion,\n * rather than forking the plugin's own types.\n */\nfunction asConfig(config: MaybeConfig): ConfigInput {\n return config as ConfigInput;\n}\n\n/**\n * Bridge a rule block onto `tseslint.config()`'s `rules` field.\n *\n * The blocks in `eslint-rules.ts` are written as ESLint expects them —\n * `'off' | 'warn' | 'error' | [level, ...options]` — but spelled as data so a\n * rule's reason comment sits beside the rule itself. ESLint's own `RuleEntry`\n * union is narrower than the data shape, and widening every entry to that union\n * would buy nothing; one assertion here, with the reason, is the cheaper and\n * more honest of the two.\n */\nfunction asRules(block: Readonly<Record<string, unknown>>): FlatConfig.Config['rules'] {\n return block as FlatConfig.Config['rules'];\n}\n\n/**\n * Build the repo's flat config.\n *\n * Consumed from the repo root as three lines:\n *\n * ```js\n * // eslint.config.mjs\n * import { defineRepoLintConfig } from '@rexezuge/tooling/eslint';\n * export default defineRepoLintConfig({ scope: '@myapp' });\n * ```\n */\nexport function defineRepoLintConfig(options: RepoLintConfigOptions): FlatConfig.ConfigArray {\n const { scope } = options;\n const projectDirs = options.projectDirs ?? DEFAULT_PROJECT_DIRS;\n const canonical = layerBans(scope).filter((layer) => projectDirs.some((dir) => layer.dir.startsWith(dir)));\n const extra = options.extraLayers ?? [];\n const bans = [...canonical, ...extra];\n\n return tseslint.config(\n {\n ignores: [\n 'eslint.config.mjs',\n 'eslint.config.js',\n 'scripts/**',\n 'worker-configuration.d.ts',\n 'local/**',\n 'app/dist/**',\n 'apps/web/dist/**',\n 'apps/*/dist/**',\n 'src/generated/**',\n 'apps/api/src/generated/**',\n 'coverage/**',\n 'coverage-integration/**',\n 'coverage-web/**',\n 'node_modules/**',\n ...(options.extraIgnores ?? []),\n ],\n },\n\n // Base: globals for all JS/TS source files. Node is the floor because the\n // scripts and the workers both run on it; the web block below adds browser\n // globals rather than replacing them, so a shared file that touches both\n // (there are several in `shared/`) still lints.\n {\n files: ['**/*.{js,mjs,cjs,ts,mts,cts,tsx,jsx}'],\n languageOptions: {\n globals: globals.node,\n },\n },\n\n // Type-aware TS rules, scoped to TS files only.\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n extends: tseslint.configs.recommendedTypeChecked,\n languageOptions: {\n parserOptions: {\n projectService: true,\n tsconfigRootDir: options.tsconfigRootDir ?? process.cwd(),\n },\n },\n },\n\n // --- typescript-eslint overrides (identical in all four source stacks) ---\n {\n files: ['**/*.{ts,mts,cts,tsx}'],\n rules: asRules(TYPESCRIPT_RULES),\n },\n\n // --- Unicorn + SonarJS presets, then the family's off-block ---\n //\n // Both presets come first on purpose: UNICORN_RULES carries `sonarjs/*`\n // offs as well as `unicorn/*` ones (it is the family's single\n // \"deliberately does not follow\" block), and a preset applied after it\n // would re-enable them. That is exactly what shipped — the sonarjs preset\n // sat between the block and the rules it relaxed, so `void-use`,\n // `different-types-comparison`, `use-type-alias`, `redundant-type-aliases`,\n // `no-nested-assignment` and `no-all-duplicated-branches` linted as errors\n // in every consumer. The two presets do not share rule names, so their\n // relative order decides nothing.\n //\n // The unicorn preset is read from whichever spelling the installed major\n // publishes. v78 dropped the `flat/`-prefixed aliases and exports the flat\n // configs directly, so `configs['flat/recommended']` is `undefined` there —\n // and a config object built around it is `undefined` too, which ESLint\n // rejects outright with \"Unexpected undefined config\". The fallback is\n // what makes the factory work on both majors rather than only the one the\n // kit was written against.\n asConfig(unicorn.configs['flat/recommended'] ?? unicorn.configs.recommended),\n asConfig(sonarjsConfigs.recommended),\n {\n rules: asRules(UNICORN_RULES),\n },\n\n // --- SonarJS advisories ---\n {\n rules: asRules(SONARJS_RULES),\n },\n\n // --- Regexp: static analysis for regular expressions ---\n asConfig(pluginRegexp.configs['flat/recommended']),\n\n // --- Prettier: formatting drift is a hard error ---\n //\n // Mail-Meow's decision, adopted repo-wide because the alternative is\n // unenforceable: `pnpm run lint` is `eslint --fix --quiet` in three of the\n // four source repos, and `--quiet` discards every warning, so a\n // `prettier/prettier` *warning* is a silent no-op. 242 files were in that\n // state in Edge-Sonic: the gate had never run.\n asConfig(eslintConfigPrettier),\n {\n plugins: { prettier },\n rules: {\n 'prettier/prettier': 'error',\n },\n },\n\n // --- Import direction guardrails (parameterized by scope) ---\n ...restrictedImports(bans),\n ...restrictedDynamicImports(bans),\n\n // --- Web: browser globals, matching the jsdom test environment ---\n //\n // The sources linted `apps/web` under `globals.node` only, so `window`,\n // `document` and `localStorage` read as undefined globals. The vitest web\n // config runs those suites under jsdom; the lint environment should agree\n // with the environment the code is executed in, or the rule is reporting\n // something untrue about how the file behaves.\n {\n files: ['apps/web/**/*.{ts,tsx,js,jsx,mts,cts,mjs,cjs}'],\n languageOptions: {\n globals: { ...globals.node, ...globals.browser },\n },\n },\n\n // --- Test suite ---\n //\n // `test/**` is deliberately NOT in the ignores list above. See TEST_RULES\n // for the override block and the reasoning behind it.\n {\n files: ['test/**/*.{ts,tsx,mts,cts}', '**/*.test.{ts,tsx,mts,cts}', '**/*.spec.{ts,tsx,mts,cts}'],\n rules: asRules(TEST_RULES),\n },\n );\n}\n"],
|
|
5
|
+
"mappings": "+EAoDA,OAAOA,MAAa,UACpB,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ASvCC,EACT,CACE,QAAS,CAAE,SAAAC,CAAQ,EACnB,MAAO,CACL,oBAAqB,UAKzB,GAAGI,EAAkBkB,CAAI,EACzB,GAAGnB,EAAyBmB,CAAI,EAShC,CACE,MAAO,CAAC,+CAA+C,EACvD,gBAAiB,CACf,QAAS,CAAE,GAAG5B,EAAQ,KAAM,GAAGA,EAAQ,OAAO,IAQlD,CACE,MAAO,CAAC,6BAA8B,6BAA8B,4BAA4B,EAChG,MAAeY,EAChB,CAEL,CApIgBK,EAAAG,EAAA",
|
|
6
6
|
"names": ["globals", "tseslint", "unicorn", "sonarjsConfigs", "pluginRegexp", "eslintConfigPrettier", "prettier", "DEFAULT_PROJECT_DIRS", "layerBans", "restrictedDynamicImports", "restrictedImports", "SONARJS_RULES", "TEST_RULES", "TYPESCRIPT_RULES", "UNICORN_RULES", "asConfig", "config", "__name", "asRules", "block", "defineRepoLintConfig", "options", "scope", "projectDirs", "canonical", "layer", "dir", "extra", "bans"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var w=Object.defineProperty;var a=(t,s)=>w(t,"name",{value:s,configurable:!0});import{readdirSync as S,readFileSync as
|
|
2
|
-
`).length;if(f<=s)continue;const p={file:l,lines:f,level:f>e?"critical":"warn"};
|
|
1
|
+
var w=Object.defineProperty;var a=(t,s)=>w(t,"name",{value:s,configurable:!0});import{readdirSync as S,readFileSync as u,statSync as $}from"node:fs";import d from"node:path";import{fail as v}from"./lib/github-actions.js";import{isEntrypoint as j}from"./lib/entrypoint.js";import{isSet as _,parseFlags as x,splitPositional as E,valueOf as g}from"./lib/cli-args.js";const y=300,O=400,I=new Set(["node_modules","dist",".wrangler","coverage","coverage-integration","coverage-web",".git"]),W=/\.(?:ts|tsx|js|mjs|cjs|css)$/,k=["test","spec"].flatMap(t=>[".ts",".tsx",".js",".jsx",".mjs",".cjs"].map(s=>`.${t}${s}`));function A(t){return/(?:^|\/)(?:locales|generated)\//.test(t)||/(?:^|\/)__(?:tests|mocks)__(?:\/|$)/.test(t)||/(?:^|\/)scripts\//.test(t)||/(?:^|\/)(?:test|tests|__tests__)\//.test(t)||/\.config\.(?:m?[jt]s|cjs)$/.test(t)||t.endsWith(".d.ts")||t.endsWith(".json")||t.endsWith(".sql")||t.endsWith(".md")?!0:k.some(s=>t.endsWith(s))}a(A,"shouldSkip");function L(t,s){return s.some(e=>e.endsWith("/")?t.startsWith(e):t===e)}a(L,"isAllowlisted");function T(t){const s=[],e=a(o=>{for(const n of S(o)){const r=d.join(o,n);let i;try{i=$(r)}catch{continue}if(i.isDirectory()){if(I.has(n))continue;e(r)}else W.test(n)&&s.push(d.relative(t,r))}},"visit");return e(t),s}a(T,"walk");function F(t){const s=t.soft??y,e=t.hard??O,o=t.allowlist??[],n=T(t.root).filter(l=>!A(l)),r=[],i=[];for(const l of n){const f=u(d.join(t.root,l),"utf8").split(`
|
|
2
|
+
`).length;if(f<=s)continue;const p={file:l,lines:f,level:f>e?"critical":"warn"};L(l,o)?i.push(p):r.push(p)}r.sort((l,f)=>f.lines-l.lines),i.sort((l,f)=>f.lines-l.lines);const c=r.filter(l=>l.level==="critical"),h=t.failOnHard!==!0||c.length===0,m=h?`God-file check passed (${n.length} files, ${r.length} over soft limit ${s}, ${i.length} allowlisted).`:`God-file check failed: ${c.length} file(s) exceed ${e} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;return{findings:r,allowlisted:i,scanned:n.length,passed:h,reported:m}}a(F,"checkGodFiles");function C(t){let s;try{s=u(t,"utf8")}catch{return[]}let e;try{e=JSON.parse(s)}catch(o){throw new Error(`${t} is not valid JSON: ${o instanceof Error?o.message:String(o)}`,{cause:o})}if(!Array.isArray(e)||e.some(o=>typeof o!="string"))throw new Error(`${t} must be a JSON array of repo-relative path strings.`);return e}a(C,"readAllowlist");function N(t=process.argv.slice(2)){const{positional:s,rest:e}=E(t,["root","allowlist"]),o=x(e,{value:["root","allowlist"],boolean:["fail-on-hard"]}),n=g(o,"root")??s[0]??".",r=g(o,"allowlist")??d.join(n,"scripts/god-files.allowlist.json"),i=F({root:n,allowlist:C(r),failOnHard:_(o,"fail-on-hard")});console.log(i.reported);for(const c of i.findings)console.log(`${c.level==="critical"?"CRITICAL":"WARN"} ${c.lines} ${c.file}`);for(const c of i.allowlisted)console.log(`ALLOWLISTED ${c.lines} ${c.file}`);return i.passed||v(`God-file check failed: run with --root ${n} to see the report.`),0}a(N,"checkGodFilesCli"),j(import.meta.url)&&process.exit(N(process.argv.slice(2)));export{O as HARD_LIMIT,y as SOFT_LIMIT,F as checkGodFiles,N as checkGodFilesCli,L as isAllowlisted,C as readAllowlist,A as shouldSkip,T as walk};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/check-god-files.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The rules behind `scripts/check-god-files.ts`.\n *\n * Provenance: converged from the seven `.mjs` copies (AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow, Mail-Otter) and the typed ratchet in Edge-Sonic.\n *\n * All seven `.mjs` copies are one script with two constants: soft 300 (warn),\n * hard 400 (error). The typed variant is not a different rule so much as a\n * different answer to \"what does the gate enforce\", and that is the decision this\n * module has to take once for the whole family.\n *\n * ### The convergence: warn-only, with an allowlist\n *\n * The two source designs:\n *\n * - **Ceiling** (six repos) — 300 warn, 400 error, `exit 1` on 400. Durable-DAV's\n * own `AGENTS.md` records what that measures: **ten** files sit just over 300\n * and none is a god file, so `WARN` reports every run and `HARD` has never\n * fired. A ceiling set above the largest file in the tree cannot tell a\n * repository getting worse from one that never got better, and raising it is\n * always available.\n * - **Ratchet** (Edge-Sonic) — a committed baseline records every file's size; a\n * file may shrink freely and grow only to its recorded size. It cannot be\n * satisfied by raising a number, which is its whole strength.\n *\n * The ratchet is the better *rule*, and the ceiling is the better *gate*: the\n * ratchet needs a baseline maintained per file and fails the first time somebody\n * writes a legitimate 320-line module, which is the failure mode that trains\n * everyone to ignore a report. So the converged script keeps the 300/400\n * thresholds — every repo's CI already prints them — and makes the verdict\n * **warn-only by default**, with two escape valves that are both visible in a\n * diff:\n *\n * 1. `--fail-on-hard` turns the 400 line back into a failing gate, for a repo\n * that has paid its debt and wants the ceiling enforced.\n * 2. An **allowlist** records the files that are over the line and known, so the\n * report names only the ones that are *new*. That is the ratchet's\n * \"recorded size\" idea without its per-file bookkeeping: the allowlist is\n * reviewed by the same commit that grows the file, because the diff shows what\n * was added to it.\n *\n * Tests are excluded, as every source does. A double modelling the platform grows\n * with the platform's surface, not with the complexity of the code it stands in\n * for — Edge-Sonic's ratchet holds them too, and its own notes record a 4,343-line\n * fixture, so this is a documented disagreement rather than an oversight.\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\nimport path from 'node:path';\nimport { fail } from './lib/github-actions.ts';\nimport { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';\n\n/**\n * A file past a size the guard reports on.\n */\nexport interface GodFileFinding {\n /**\n Path relative to the root the check ran against.\n */\n readonly file: string;\n /**\n Lines it has.\n */\n readonly lines: number;\n /**\n `warn` past the soft limit, `critical` past the hard one.\n */\n readonly level: 'warn' | 'critical';\n}\n\n/**\n * The outcome of one run.\n */\nexport interface GodFileReport {\n /**\n Files over a limit, worst first, minus the allowlisted.\n */\n readonly findings: readonly GodFileFinding[];\n /**\n How many files the walk measured.\n */\n readonly scanned: number;\n /**\n Allowlisted files that are over a limit — reported, never counted.\n */\n readonly allowlisted: readonly GodFileFinding[];\n /**\n * Whether the tree may be committed as it stands.\n *\n * `true` in warn-only mode, which is the default; a `critical` finding fails\n * only when the caller asked for the gate.\n */\n readonly passed: boolean;\n /**\n The message to print, either way.\n */\n readonly reported: string;\n}\n\n/**\n * What `checkGodFiles` accepts.\n */\nexport interface GodFileOptions {\n /**\n Directory to walk.\n */\n readonly root: string;\n /**\n * Repo-relative paths (or directory prefixes ending in `/`) exempt from the\n * report. Defaults to `god-files.allowlist.json` beside the caller's script\n * when that file exists — see `readAllowlist`.\n */\n readonly allowlist?: readonly string[];\n /**\n Soft limit, past which a file is reported as `warn`.\n */\n readonly soft?: number;\n /**\n Hard limit, past which a file is reported as `critical`.\n */\n readonly hard?: number;\n /**\n Make a `critical` finding fail the run.\n */\n readonly failOnHard?: boolean;\n}\n\n/**\nDefault soft limit, as every source repo uses.\n*/\nexport const SOFT_LIMIT = 300;\n/**\nDefault hard limit, as every source repo uses.\n*/\nexport const HARD_LIMIT = 400;\n\n/**\n * Directories the walker never enters.\n *\n * Build output and VCS state; `coverage` is here because a generated HTML report\n * is thousands of \"lines\" of nothing.\n */\nconst EXCLUDE_DIRS = new Set(['node_modules', 'dist', '.wrangler', 'coverage', 'coverage-integration', 'coverage-web', '.git']);\n\n/**\n * Source extensions the guard counts.\n *\n * `css` is in the set because every source repo counts it, and a 400-line\n * stylesheet is the same reading problem as a 400-line module.\n */\nconst SOURCE_EXTENSIONS = /\\.(?:ts|tsx|js|mjs|cjs|css)$/;\n\n/**\n * The test-file suffixes the guard skips.\n *\n * `.test.tsx` matter as much as `.test.ts`: the walker collects both, so a list\n * that only named the `.ts` forms let every React test file through the guard and\n * reported them as god files — which is how Durable-DAV-Router discovered it.\n * Built from the kinds and extensions rather than enumerated, so a new test\n * extension cannot silently escape.\n */\nconst TEST_SUFFIXES: readonly string[] = ['test', 'spec'].flatMap((kind) =>\n ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `.${kind}${ext}`),\n);\n\n/**\n * Whether a repo-relative path is exempt from the guard.\n *\n * Provenance: AWS-AccessBridge's version is the canonical one, because it\n * documents and fixes two live bugs in the others.\n *\n * Every directory pattern is anchored with `(?:^|/)` rather than a bare leading\n * `/`. `relative()` yields `test/helpers/x.ts` for a top-level test directory and\n * `scripts/lib/x.ts` for the scripts directory — **no leading separator** — so a\n * pattern written as `/\\/(?:test|tests|__tests__)\\//` never matches either one.\n * It looks right, it does match when handed an absolute path, and against these\n * layouts it is silently a no-op. Durable-DAV and ChordDHT-Tracker ship exactly\n * that dead pattern.\n */\nexport function shouldSkip(rel: string): boolean {\n if (\n /(?:^|\\/)(?:locales|generated)\\//.test(rel) ||\n /(?:^|\\/)__(?:tests|mocks)__(?:\\/|$)/.test(rel) ||\n /(?:^|\\/)scripts\\//.test(rel) ||\n /(?:^|\\/)(?:test|tests|__tests__)\\//.test(rel) ||\n /\\.config\\.(?:m?[jt]s|cjs)$/.test(rel) ||\n rel.endsWith('.d.ts') ||\n rel.endsWith('.json') ||\n rel.endsWith('.sql') ||\n rel.endsWith('.md')\n )\n return true;\n return TEST_SUFFIXES.some((suffix) => rel.endsWith(suffix));\n}\n\n/**\n * Whether a repo-relative path is on the allowlist.\n *\n * An entry ending in `/` exempts a whole directory; any other entry is matched\n * exactly, so `apps/api/src/index.ts` does not exempt `apps/api/src/index.util.ts`.\n */\nexport function isAllowlisted(rel: string, allowlist: readonly string[]): boolean {\n return allowlist.some((entry) => (entry.endsWith('/') ? rel.startsWith(entry) : rel === entry));\n}\n\n/**\n * Every source file under `root`, as repo-relative paths.\n *\n * Symlink-safe: a dangling symlink or a file removed mid-walk is skipped rather\n * than thrown, because neither is a god-file problem.\n */\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = path.join(dir, entry);\n let stat;\n try {\n stat = statSync(full);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n if (EXCLUDE_DIRS.has(entry)) continue;\n visit(full);\n } else if (SOURCE_EXTENSIONS.test(entry)) {\n out.push(path.relative(root, full));\n }\n }\n };\n visit(root);\n return out;\n}\n\n/**\n * Run the guard over a tree.\n *\n * Pure with respect to the verdict — the only I/O is the walk and a line count —\n * so a test drives it against a temporary directory.\n */\nexport function checkGodFiles(options: GodFileOptions): GodFileReport {\n const soft = options.soft ?? SOFT_LIMIT;\n const hard = options.hard ?? HARD_LIMIT;\n const allowlist = options.allowlist ?? [];\n\n const scanned = walk(options.root).filter((rel) => !shouldSkip(rel));\n const findings: GodFileFinding[] = [];\n const allowlisted: GodFileFinding[] = [];\n\n for (const rel of scanned) {\n const lines = readFileSync(path.join(options.root, rel), 'utf8').split('\\n').length;\n if (lines <= soft) continue;\n const finding: GodFileFinding = { file: rel, lines, level: lines > hard ? 'critical' : 'warn' };\n if (isAllowlisted(rel, allowlist)) {\n allowlisted.push(finding);\n } else {\n findings.push(finding);\n }\n }\n\n findings.sort((left, right) => right.lines - left.lines);\n allowlisted.sort((left, right) => right.lines - left.lines);\n\n const critical = findings.filter((finding) => finding.level === 'critical');\n const passed = options.failOnHard !== true || critical.length === 0;\n\n const reported = passed\n ? `God-file check passed (${scanned.length} files, ${findings.length} over soft limit ${soft}, ${allowlisted.length} allowlisted).`\n : `God-file check failed: ${critical.length} file(s) exceed ${hard} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;\n\n return { findings, allowlisted, scanned: scanned.length, passed, reported };\n}\n\n/**\n * Read an allowlist file, or `[]` when it is absent.\n *\n * The file is `scripts/god-files.allowlist.json`: a JSON array of repo-relative\n * paths. Absence is the normal case for a repo with no known offenders, so it is\n * not an error — a guard that fails on a first run nobody has filled in yet is a\n * guard that gets disabled.\n *\n * A malformed file is an error rather than an empty list, because \"the allowlist\n * is empty\" silently un-reports every known offender.\n */\nexport function readAllowlist(file: string): string[] {\n let raw: string;\n try {\n raw = readFileSync(file, 'utf8');\n } catch {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error: unknown) {\n throw new Error(`${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== 'string')) {\n throw new Error(`${file} must be a JSON array of repo-relative path strings.`);\n }\n return parsed as string[];\n}\n\n/**\n * CLI entry: `checkGodFilesCli(['.', '--fail-on-hard'])`.\n *\n * The directory is a positional argument **or** `--root <dir>`, because every other\n * script in this tree takes its target positionally and a gate that has to be\n * invoked one way in one script and another way in the next is a gate somebody\n * invokes wrong. A second positional is an error.\n *\n * Flags (see FlagSpec): `--root <dir>` (default `.`), `--allowlist <file>`\n * (default `scripts/god-files.allowlist.json` beside the root, absent = none),\n * `--fail-on-hard` (default off, matching every source repo's warn-only gate).\n * Returns 0 unless `--fail-on-hard` is set and a critical file is found.\n */\nexport function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)): number {\n // Split before parsing, because parseFlags rejects anything that is not a declared\n // flag and a positional directory is neither a mistake nor a flag.\n const { positional, rest } = splitPositional(argv, ['root', 'allowlist']);\n const flags = parseFlags(rest, {\n value: ['root', 'allowlist'],\n boolean: ['fail-on-hard'],\n });\n const root = valueOf(flags, 'root') ?? positional[0] ?? '.';\n const allowlistPath = valueOf(flags, 'allowlist') ?? path.join(root, 'scripts/god-files.allowlist.json');\n const report = checkGodFiles({\n root,\n allowlist: readAllowlist(allowlistPath),\n failOnHard: isSet(flags, 'fail-on-hard'),\n });\n console.log(report.reported);\n for (const finding of report.findings) {\n console.log(`${finding.level === 'critical' ? 'CRITICAL' : 'WARN'} ${finding.lines} ${finding.file}`);\n }\n for (const finding of report.allowlisted) {\n console.log(`ALLOWLISTED ${finding.lines} ${finding.file}`);\n }\n if (!report.passed) {\n fail(`God-file check failed: run with --root ${root} to see the report.`);\n }\n return 0;\n}\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(checkGodFilesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
-
"mappings": "+EAgDA,OAAS,eAAAA,EAAa,gBAAAC,EAAc,YAAAC,MAAgB,UACpD,
|
|
6
|
-
"names": ["readdirSync", "readFileSync", "statSync", "
|
|
4
|
+
"sourcesContent": ["/**\n * The rules behind `scripts/check-god-files.ts`.\n *\n * Provenance: converged from the seven `.mjs` copies (AWS-AccessBridge,\n * CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Durable-DAV-Router, Edge-Git,\n * Mail-Meow, Mail-Otter) and the typed ratchet in Edge-Sonic.\n *\n * All seven `.mjs` copies are one script with two constants: soft 300 (warn),\n * hard 400 (error). The typed variant is not a different rule so much as a\n * different answer to \"what does the gate enforce\", and that is the decision this\n * module has to take once for the whole family.\n *\n * ### The convergence: warn-only, with an allowlist\n *\n * The two source designs:\n *\n * - **Ceiling** (six repos) — 300 warn, 400 error, `exit 1` on 400. Durable-DAV's\n * own `AGENTS.md` records what that measures: **ten** files sit just over 300\n * and none is a god file, so `WARN` reports every run and `HARD` has never\n * fired. A ceiling set above the largest file in the tree cannot tell a\n * repository getting worse from one that never got better, and raising it is\n * always available.\n * - **Ratchet** (Edge-Sonic) — a committed baseline records every file's size; a\n * file may shrink freely and grow only to its recorded size. It cannot be\n * satisfied by raising a number, which is its whole strength.\n *\n * The ratchet is the better *rule*, and the ceiling is the better *gate*: the\n * ratchet needs a baseline maintained per file and fails the first time somebody\n * writes a legitimate 320-line module, which is the failure mode that trains\n * everyone to ignore a report. So the converged script keeps the 300/400\n * thresholds — every repo's CI already prints them — and makes the verdict\n * **warn-only by default**, with two escape valves that are both visible in a\n * diff:\n *\n * 1. `--fail-on-hard` turns the 400 line back into a failing gate, for a repo\n * that has paid its debt and wants the ceiling enforced.\n * 2. An **allowlist** records the files that are over the line and known, so the\n * report names only the ones that are *new*. That is the ratchet's\n * \"recorded size\" idea without its per-file bookkeeping: the allowlist is\n * reviewed by the same commit that grows the file, because the diff shows what\n * was added to it.\n *\n * Tests are excluded, as every source does. A double modelling the platform grows\n * with the platform's surface, not with the complexity of the code it stands in\n * for — Edge-Sonic's ratchet holds them too, and its own notes record a 4,343-line\n * fixture, so this is a documented disagreement rather than an oversight.\n */\n\nimport { readdirSync, readFileSync, statSync } from 'node:fs';\nimport path from 'node:path';\nimport { fail } from './lib/github-actions.ts';\nimport { isEntrypoint } from './lib/entrypoint.ts';\nimport { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';\n\n/**\n * A file past a size the guard reports on.\n */\nexport interface GodFileFinding {\n /**\n Path relative to the root the check ran against.\n */\n readonly file: string;\n /**\n Lines it has.\n */\n readonly lines: number;\n /**\n `warn` past the soft limit, `critical` past the hard one.\n */\n readonly level: 'warn' | 'critical';\n}\n\n/**\n * The outcome of one run.\n */\nexport interface GodFileReport {\n /**\n Files over a limit, worst first, minus the allowlisted.\n */\n readonly findings: readonly GodFileFinding[];\n /**\n How many files the walk measured.\n */\n readonly scanned: number;\n /**\n Allowlisted files that are over a limit — reported, never counted.\n */\n readonly allowlisted: readonly GodFileFinding[];\n /**\n * Whether the tree may be committed as it stands.\n *\n * `true` in warn-only mode, which is the default; a `critical` finding fails\n * only when the caller asked for the gate.\n */\n readonly passed: boolean;\n /**\n The message to print, either way.\n */\n readonly reported: string;\n}\n\n/**\n * What `checkGodFiles` accepts.\n */\nexport interface GodFileOptions {\n /**\n Directory to walk.\n */\n readonly root: string;\n /**\n * Repo-relative paths (or directory prefixes ending in `/`) exempt from the\n * report. Defaults to `god-files.allowlist.json` beside the caller's script\n * when that file exists — see `readAllowlist`.\n */\n readonly allowlist?: readonly string[];\n /**\n Soft limit, past which a file is reported as `warn`.\n */\n readonly soft?: number;\n /**\n Hard limit, past which a file is reported as `critical`.\n */\n readonly hard?: number;\n /**\n Make a `critical` finding fail the run.\n */\n readonly failOnHard?: boolean;\n}\n\n/**\nDefault soft limit, as every source repo uses.\n*/\nexport const SOFT_LIMIT = 300;\n/**\nDefault hard limit, as every source repo uses.\n*/\nexport const HARD_LIMIT = 400;\n\n/**\n * Directories the walker never enters.\n *\n * Build output and VCS state; `coverage` is here because a generated HTML report\n * is thousands of \"lines\" of nothing.\n */\nconst EXCLUDE_DIRS = new Set(['node_modules', 'dist', '.wrangler', 'coverage', 'coverage-integration', 'coverage-web', '.git']);\n\n/**\n * Source extensions the guard counts.\n *\n * `css` is in the set because every source repo counts it, and a 400-line\n * stylesheet is the same reading problem as a 400-line module.\n */\nconst SOURCE_EXTENSIONS = /\\.(?:ts|tsx|js|mjs|cjs|css)$/;\n\n/**\n * The test-file suffixes the guard skips.\n *\n * `.test.tsx` matter as much as `.test.ts`: the walker collects both, so a list\n * that only named the `.ts` forms let every React test file through the guard and\n * reported them as god files — which is how Durable-DAV-Router discovered it.\n * Built from the kinds and extensions rather than enumerated, so a new test\n * extension cannot silently escape.\n */\nconst TEST_SUFFIXES: readonly string[] = ['test', 'spec'].flatMap((kind) =>\n ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].map((ext) => `.${kind}${ext}`),\n);\n\n/**\n * Whether a repo-relative path is exempt from the guard.\n *\n * Provenance: AWS-AccessBridge's version is the canonical one, because it\n * documents and fixes two live bugs in the others.\n *\n * Every directory pattern is anchored with `(?:^|/)` rather than a bare leading\n * `/`. `relative()` yields `test/helpers/x.ts` for a top-level test directory and\n * `scripts/lib/x.ts` for the scripts directory — **no leading separator** — so a\n * pattern written as `/\\/(?:test|tests|__tests__)\\//` never matches either one.\n * It looks right, it does match when handed an absolute path, and against these\n * layouts it is silently a no-op. Durable-DAV and ChordDHT-Tracker ship exactly\n * that dead pattern.\n */\nexport function shouldSkip(rel: string): boolean {\n if (\n /(?:^|\\/)(?:locales|generated)\\//.test(rel) ||\n /(?:^|\\/)__(?:tests|mocks)__(?:\\/|$)/.test(rel) ||\n /(?:^|\\/)scripts\\//.test(rel) ||\n /(?:^|\\/)(?:test|tests|__tests__)\\//.test(rel) ||\n /\\.config\\.(?:m?[jt]s|cjs)$/.test(rel) ||\n rel.endsWith('.d.ts') ||\n rel.endsWith('.json') ||\n rel.endsWith('.sql') ||\n rel.endsWith('.md')\n )\n return true;\n return TEST_SUFFIXES.some((suffix) => rel.endsWith(suffix));\n}\n\n/**\n * Whether a repo-relative path is on the allowlist.\n *\n * An entry ending in `/` exempts a whole directory; any other entry is matched\n * exactly, so `apps/api/src/index.ts` does not exempt `apps/api/src/index.util.ts`.\n */\nexport function isAllowlisted(rel: string, allowlist: readonly string[]): boolean {\n return allowlist.some((entry) => (entry.endsWith('/') ? rel.startsWith(entry) : rel === entry));\n}\n\n/**\n * Every source file under `root`, as repo-relative paths.\n *\n * Symlink-safe: a dangling symlink or a file removed mid-walk is skipped rather\n * than thrown, because neither is a god-file problem.\n */\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (dir: string): void => {\n for (const entry of readdirSync(dir)) {\n const full = path.join(dir, entry);\n let stat;\n try {\n stat = statSync(full);\n } catch {\n continue;\n }\n if (stat.isDirectory()) {\n if (EXCLUDE_DIRS.has(entry)) continue;\n visit(full);\n } else if (SOURCE_EXTENSIONS.test(entry)) {\n out.push(path.relative(root, full));\n }\n }\n };\n visit(root);\n return out;\n}\n\n/**\n * Run the guard over a tree.\n *\n * Pure with respect to the verdict — the only I/O is the walk and a line count —\n * so a test drives it against a temporary directory.\n */\nexport function checkGodFiles(options: GodFileOptions): GodFileReport {\n const soft = options.soft ?? SOFT_LIMIT;\n const hard = options.hard ?? HARD_LIMIT;\n const allowlist = options.allowlist ?? [];\n\n const scanned = walk(options.root).filter((rel) => !shouldSkip(rel));\n const findings: GodFileFinding[] = [];\n const allowlisted: GodFileFinding[] = [];\n\n for (const rel of scanned) {\n const lines = readFileSync(path.join(options.root, rel), 'utf8').split('\\n').length;\n if (lines <= soft) continue;\n const finding: GodFileFinding = { file: rel, lines, level: lines > hard ? 'critical' : 'warn' };\n if (isAllowlisted(rel, allowlist)) {\n allowlisted.push(finding);\n } else {\n findings.push(finding);\n }\n }\n\n findings.sort((left, right) => right.lines - left.lines);\n allowlisted.sort((left, right) => right.lines - left.lines);\n\n const critical = findings.filter((finding) => finding.level === 'critical');\n const passed = options.failOnHard !== true || critical.length === 0;\n\n const reported = passed\n ? `God-file check passed (${scanned.length} files, ${findings.length} over soft limit ${soft}, ${allowlisted.length} allowlisted).`\n : `God-file check failed: ${critical.length} file(s) exceed ${hard} LOC. Split them, or add them to the allowlist in the same commit that grows them.`;\n\n return { findings, allowlisted, scanned: scanned.length, passed, reported };\n}\n\n/**\n * Read an allowlist file, or `[]` when it is absent.\n *\n * The file is `scripts/god-files.allowlist.json`: a JSON array of repo-relative\n * paths. Absence is the normal case for a repo with no known offenders, so it is\n * not an error — a guard that fails on a first run nobody has filled in yet is a\n * guard that gets disabled.\n *\n * A malformed file is an error rather than an empty list, because \"the allowlist\n * is empty\" silently un-reports every known offender.\n */\nexport function readAllowlist(file: string): string[] {\n let raw: string;\n try {\n raw = readFileSync(file, 'utf8');\n } catch {\n return [];\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error: unknown) {\n throw new Error(`${file} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`, { cause: error });\n }\n if (!Array.isArray(parsed) || parsed.some((entry) => typeof entry !== 'string')) {\n throw new Error(`${file} must be a JSON array of repo-relative path strings.`);\n }\n return parsed as string[];\n}\n\n/**\n * CLI entry: `checkGodFilesCli(['.', '--fail-on-hard'])`.\n *\n * The directory is a positional argument **or** `--root <dir>`, because every other\n * script in this tree takes its target positionally and a gate that has to be\n * invoked one way in one script and another way in the next is a gate somebody\n * invokes wrong. A second positional is an error.\n *\n * Flags (see FlagSpec): `--root <dir>` (default `.`), `--allowlist <file>`\n * (default `scripts/god-files.allowlist.json` beside the root, absent = none),\n * `--fail-on-hard` (default off, matching every source repo's warn-only gate).\n * Returns 0 unless `--fail-on-hard` is set and a critical file is found.\n */\nexport function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)): number {\n // Split before parsing, because parseFlags rejects anything that is not a declared\n // flag and a positional directory is neither a mistake nor a flag.\n const { positional, rest } = splitPositional(argv, ['root', 'allowlist']);\n const flags = parseFlags(rest, {\n value: ['root', 'allowlist'],\n boolean: ['fail-on-hard'],\n });\n const root = valueOf(flags, 'root') ?? positional[0] ?? '.';\n const allowlistPath = valueOf(flags, 'allowlist') ?? path.join(root, 'scripts/god-files.allowlist.json');\n const report = checkGodFiles({\n root,\n allowlist: readAllowlist(allowlistPath),\n failOnHard: isSet(flags, 'fail-on-hard'),\n });\n console.log(report.reported);\n for (const finding of report.findings) {\n console.log(`${finding.level === 'critical' ? 'CRITICAL' : 'WARN'} ${finding.lines} ${finding.file}`);\n }\n for (const finding of report.allowlisted) {\n console.log(`ALLOWLISTED ${finding.lines} ${finding.file}`);\n }\n if (!report.passed) {\n fail(`God-file check failed: run with --root ${root} to see the report.`);\n }\n return 0;\n}\n\n// Run only when this file is the entrypoint.\n//\n// The rules above are pure and the tests import them directly, so a module-level\n// call would shell out (and exit) during a test run. The URL comparison rather than\n// an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and\n// it is what keeps the rule modules importable — which is the whole reason they are\n// separate modules in the first place.\nif (isEntrypoint(import.meta.url)) {\n process.exit(checkGodFilesCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAgDA,OAAS,eAAAA,EAAa,gBAAAC,EAAc,YAAAC,MAAgB,UACpD,OAAOC,MAAU,YACjB,OAAS,QAAAC,MAAY,0BACrB,OAAS,gBAAAC,MAAoB,sBAC7B,OAAS,SAAAC,EAAO,cAAAC,EAAY,mBAAAC,EAAiB,WAAAC,MAAe,oBAgFrD,MAAMC,EAAa,IAIbC,EAAa,IAQpBC,EAAe,IAAI,IAAI,CAAC,eAAgB,OAAQ,YAAa,WAAY,uBAAwB,eAAgB,MAAM,CAAC,EAQxHC,EAAoB,+BAWpBC,EAAmC,CAAC,OAAQ,MAAM,EAAE,QAASC,GACjE,CAAC,MAAO,OAAQ,MAAO,OAAQ,OAAQ,MAAM,EAAE,IAAKC,GAAQ,IAAID,CAAI,GAAGC,CAAG,EAAE,CAAC,EAiBzE,SAAUC,EAAWC,EAAW,CACpC,MACE,kCAAkC,KAAKA,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"TEST_SUFFIXES", "kind", "ext", "shouldSkip", "rel", "suffix", "__name", "isAllowlisted", "allowlist", "entry", "walk", "root", "out", "visit", "dir", "full", "stat", "checkGodFiles", "options", "soft", "hard", "scanned", "findings", "allowlisted", "lines", "finding", "left", "right", "critical", "passed", "reported", "readAllowlist", "file", "raw", "parsed", "error", "checkGodFilesCli", "argv", "positional", "rest", "flags", "allowlistPath", "report"]
|
|
7
7
|
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether this module is the process's entrypoint.
|
|
3
|
+
*
|
|
4
|
+
* The comparison needs **both** sides resolved through `realpathSync`, and that
|
|
5
|
+
* is not a detail. `process.argv[1]` is whatever the caller typed — under pnpm
|
|
6
|
+
* that is `node_modules/@rexezuge/tooling/dist/scripts/…`, a **symlink** into the
|
|
7
|
+
* store — while `import.meta.url` is always the realpath, because the ESM
|
|
8
|
+
* resolver follows links. So the two never matched, the guard never fired, and
|
|
9
|
+
* every script below exited 0 having printed nothing.
|
|
10
|
+
*
|
|
11
|
+
* That is the worst shape a gate can fail in: it looks green. `check-god-files`
|
|
12
|
+
* reported no file over the limit for every repository that adopted it,
|
|
13
|
+
* `validate-locales` passed with a key missing from eleven bundles, and neither
|
|
14
|
+
* said a word. Found by AWS-AccessBridge swapping in its own `validate_locales`
|
|
15
|
+
* and finding that the replacement stopped catching the defect the old one
|
|
16
|
+
* reported on the same tree.
|
|
17
|
+
*
|
|
18
|
+
* It is worth a function rather than an inline comparison because four scripts
|
|
19
|
+
* carry the same guard, and a shared helper is what makes the fifth correct
|
|
20
|
+
* instead of a fourth copy of the same mistake.
|
|
21
|
+
*
|
|
22
|
+
* A missing or unreadable entrypoint is not the entrypoint, and the caller
|
|
23
|
+
* exports the rule functions precisely so the module stays importable — a suite
|
|
24
|
+
* imports these to test the rules, and there `process.argv[1]` is the test file.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isEntrypoint(moduleUrl: string, argv1?: string | undefined): boolean;
|
|
27
|
+
//# sourceMappingURL=entrypoint.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entrypoint.d.ts","sourceRoot":"","sources":["../../../src/scripts/lib/entrypoint.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,GAAE,MAAM,GAAG,SAA2B,GAAG,OAAO,CAUpG"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n=Object.defineProperty;var e=(t,r)=>n(t,"name",{value:r,configurable:!0});import{realpathSync as o}from"node:fs";import{pathToFileURL as f}from"node:url";function c(t,r=process.argv[1]){if(r===void 0)return!1;try{return t===f(o(r)).href}catch{return!1}}e(c,"isEntrypoint");export{c as isEntrypoint};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../src/scripts/lib/entrypoint.ts"],
|
|
4
|
+
"sourcesContent": ["import { realpathSync } from 'node:fs';\nimport { pathToFileURL } from 'node:url';\n\n/**\n * Whether this module is the process's entrypoint.\n *\n * The comparison needs **both** sides resolved through `realpathSync`, and that\n * is not a detail. `process.argv[1]` is whatever the caller typed — under pnpm\n * that is `node_modules/@rexezuge/tooling/dist/scripts/…`, a **symlink** into the\n * store — while `import.meta.url` is always the realpath, because the ESM\n * resolver follows links. So the two never matched, the guard never fired, and\n * every script below exited 0 having printed nothing.\n *\n * That is the worst shape a gate can fail in: it looks green. `check-god-files`\n * reported no file over the limit for every repository that adopted it,\n * `validate-locales` passed with a key missing from eleven bundles, and neither\n * said a word. Found by AWS-AccessBridge swapping in its own `validate_locales`\n * and finding that the replacement stopped catching the defect the old one\n * reported on the same tree.\n *\n * It is worth a function rather than an inline comparison because four scripts\n * carry the same guard, and a shared helper is what makes the fifth correct\n * instead of a fourth copy of the same mistake.\n *\n * A missing or unreadable entrypoint is not the entrypoint, and the caller\n * exports the rule functions precisely so the module stays importable — a suite\n * imports these to test the rules, and there `process.argv[1]` is the test file.\n */\nexport function isEntrypoint(moduleUrl: string, argv1: string | undefined = process.argv[1]): boolean {\n if (argv1 === undefined) {\n return false;\n }\n try {\n return moduleUrl === pathToFileURL(realpathSync(argv1)).href;\n } catch {\n // A path that does not resolve cannot be the file that is running.\n return false;\n }\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,UAC7B,OAAS,iBAAAC,MAAqB,WA2BxB,SAAUC,EAAaC,EAAmBC,EAA4B,QAAQ,KAAK,CAAC,EAAC,CACzF,GAAIA,IAAU,OACZ,MAAO,GAET,GAAI,CACF,OAAOD,IAAcF,EAAcD,EAAaI,CAAK,CAAC,EAAE,IAC1D,MAAQ,CAEN,MAAO,EACT,CACF,CAVgBC,EAAAH,EAAA",
|
|
6
|
+
"names": ["realpathSync", "pathToFileURL", "isEntrypoint", "moduleUrl", "argv1", "__name"]
|
|
7
|
+
}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import{existsSync as
|
|
1
|
+
var m=Object.defineProperty;var u=(t,e)=>m(t,"name",{value:e,configurable:!0});import{isEntrypoint as S}from"./lib/entrypoint.js";import{existsSync as a,mkdirSync as y,readFileSync as h,writeFileSync as $}from"node:fs";import l from"node:path";const A="apps/api/src/generated/spa-shell.ts",T="apps/web/dist/index.html",v=`// Auto-generated stub - real content is produced by the build step via the Vite plugin.
|
|
2
2
|
export const SPA_HTML: string = '';
|
|
3
|
-
`,x=200;function d(t){const e=l.resolve(t.root),
|
|
3
|
+
`,x=200;function d(t){const e=l.resolve(t.root),n=l.join(e,t.shellPath??A),r=l.join(e,t.distIndexPath??T);return{shell:n,distIndex:r,distAssets:l.join(l.dirname(r),"assets")}}u(d,"resolvePaths");function p(t){const{shell:e}=d(t);y(l.dirname(e),{recursive:!0});try{$(e,v,{encoding:"utf8",flag:"wx"})}catch(n){if(n?.code==="EEXIST")return{created:!1,path:e};throw n}return{created:!0,path:e}}u(p,"ensureSpaShellStub");function w(t,e){if(!a(t))return e.push(`${t} is missing \u2014 run the build (only apps/web has a build step).`),null;const n=h(t,"utf8"),r="export const SPA_HTML: string = ",s=n.indexOf(r);if(s===-1)return e.push(`${t} does not export SPA_HTML \u2014 regenerate it with the build.`),null;const o=n.slice(s+r.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:n,distAssets:r}=d(t),s=[],o=w(e,s);if(o===null)return{problems:s};const i=[...o.matchAll(/(?:src|href)="\/assets\/([^"]+)"/g)].map(c=>c[1]);i.length===0&&s.push("The embedded shell references no /assets/ bundles \u2014 it is not a real build output.");for(const c of new Set(i))a(l.join(r,c))||s.push(`The embedded shell references /assets/${c}, which is not in ${r} \u2014 run the build.`);return a(n)?h(n,"utf8")!==o&&s.push(`${e} does not match ${n} \u2014 run the build.`):s.push(`${n} 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 n={root:t[1]??process.cwd()};if(e==="ensure"){const s=p(n);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:r}=f(n);if(r.length>0){console.error("SPA shell check failed:");for(const s of r)console.error(` - ${s}`);return 1}return console.log("SPA shell check passed."),0}u(g,"spaShellCli");S(import.meta.url)&&process.exit(g(process.argv.slice(2)));export{p as ensureSpaShellStub,g as spaShellCli,f as verifySpaShell};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scripts/spa-shell.ts"],
|
|
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
|
|
5
|
-
"mappings": "+
|
|
6
|
-
"names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "
|
|
4
|
+
"sourcesContent": ["import { isEntrypoint } from './lib/entrypoint.ts';\n/**\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 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 (isEntrypoint(import.meta.url)) {\n process.exit(spaShellCli(process.argv.slice(2)));\n}\n"],
|
|
5
|
+
"mappings": "+EAAA,OAAS,gBAAAA,MAAoB,sBAgB7B,OAAS,cAAAC,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,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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,CACA,KAAM,CAAE,SAAAf,CAAQ,EAAKM,EAAed,CAAO,EAC3C,GAAIQ,EAAS,OAAS,EAAG,CACvB,QAAQ,MAAM,yBAAyB,EACvC,UAAWgB,KAAWhB,EAAU,QAAQ,MAAM,OAAOgB,CAAO,EAAE,EAC9D,MAAO,EACT,CACA,eAAQ,IAAI,yBAAyB,EAC9B,CACT,CAxBSpB,EAAAgB,EAAA,eAoCL/B,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAK+B,EAAY,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
|
|
6
|
+
"names": ["isEntrypoint", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "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,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
`&&(o=!1);continue}const c=e[s+1];if(n){r==="*"&&c==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&c==="-"){o=!0;continue}if(r==="/"&&c==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&c!=="="&&c!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const l=e.indexOf("{",s);return l===-1?-1:l}}return-1}f(
|
|
3
|
-
`&&(c=!1);continue}const m=e[h+1];if(a){d==="*"&&m==="/"&&(a=!1,h+=1);continue}if(r!==""){if(d==="\\"){h+=1;continue}d===r&&(r="");continue}if(d==="-"&&m==="-"){c=!0;continue}if(d==="/"&&m==="*"){a=!0;continue}if(d==="'"||d==='"'||d==="`"){r=d;continue}if(d==="{")n+=1;else if(d==="}"&&(n-=1,n===0)){s=h;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const u=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(h,d)=>JSON.stringify(
|
|
4
|
-
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}f(
|
|
5
|
-
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}f(q,"decodeStringLiteral");function B(e){const t=new Set;for(const o of
|
|
1
|
+
var v=Object.defineProperty;var f=(e,t)=>v(e,"name",{value:t,configurable:!0});import{isEntrypoint as L}from"./lib/entrypoint.js";import{existsSync as $,readdirSync as w,readFileSync as g}from"node:fs";import y from"node:path";function b(e,t="",o=new Map){if(e===null||typeof e!="object"||Array.isArray(e))return t&&o.set(t,e),o;const n=Object.entries(e);if(n.length===0)return t&&o.set(t,e),o;for(const[s,r]of n)b(r,t?`${t}.${s}`:s,o);return o}f(b,"flatten");function x(e){return typeof e!="string"?[]:[...new Set(e.match(/\{\{[^{}]+\}\}/g))].sort((t,o)=>t.localeCompare(o))}f(x,"placeholdersOf");function A(e){const t=g(e,"utf8");return e.endsWith(".ts")?O(t,e):JSON.parse(t)}f(A,"readBundle");function _(e){let t="",o=!1,n=!1;for(let s=0;s<e.length;s+=1){const r=e[s];if(o){r===`
|
|
2
|
+
`&&(o=!1);continue}const c=e[s+1];if(n){r==="*"&&c==="/"&&(n=!1,s+=1);continue}if(t!==""){if(r==="\\"){s+=1;continue}r===t&&(t="");continue}if(r==="-"&&c==="-"){o=!0;continue}if(r==="/"&&c==="*"){n=!0;continue}if(r==="'"||r==='"'||r==="`"){t=r;continue}const a=e[s-1];if(r==="="&&c!=="="&&c!==">"&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"){const l=e.indexOf("{",s);return l===-1?-1:l}}return-1}f(_,"objectLiteralStart");function O(e,t){const o=_(e);if(o===-1)throw new Error(`${t} has no object literal`);let n=0,s=-1,r="",c=!1,a=!1;for(let h=o;h<e.length;h+=1){const d=e[h];if(c){d===`
|
|
3
|
+
`&&(c=!1);continue}const m=e[h+1];if(a){d==="*"&&m==="/"&&(a=!1,h+=1);continue}if(r!==""){if(d==="\\"){h+=1;continue}d===r&&(r="");continue}if(d==="-"&&m==="-"){c=!0;continue}if(d==="/"&&m==="*"){a=!0;continue}if(d==="'"||d==='"'||d==="`"){r=d;continue}if(d==="{")n+=1;else if(d==="}"&&(n-=1,n===0)){s=h;break}}if(s===-1)throw new Error(`${t} has an unterminated object literal`);const u=e.slice(o,s+1).replaceAll(/'((?:[^'\\]|\\.)*)'/g,(h,d)=>JSON.stringify(J(d))).replaceAll(/([{,]\s*)([A-Z_$][\w$]*)(\s*:)/gi,'$1"$2"$3').replaceAll(/,(\s*[}\]])/g,"$1");try{return JSON.parse(u)}catch(h){throw new Error(`${t} object literal could not be parsed: ${h instanceof Error?h.message:String(h)}`)}}f(O,"parseObjectLiteral");function J(e){return e.replaceAll(String.raw`\'`,"'").replaceAll(String.raw`\"`,'"').replaceAll(String.raw`\n`,`
|
|
4
|
+
`).replaceAll(String.raw`\t`," ").replaceAll(String.raw`\\`,"\\")}f(J,"unescapeLiteral");const j={file:"json",module:"ts"};function S(e){return e==="auto"?["dir","file","module"]:[e]}f(S,"layouts");function C(e,t){const o=[];S(t).includes("dir")&&o.push(...w(e,{withFileTypes:!0}).filter(n=>n.isDirectory()).map(n=>n.name));for(const n of S(t)){if(n==="dir")continue;const s=j[n];o.push(...w(e).filter(r=>r.endsWith(`.${s}`)).map(r=>r.slice(0,-s.length-1)))}return o}f(C,"tagsOnDisk");function k(e,t,o){const n=[];S(o).includes("dir")&&n.push(y.join(e,t,"translation.json"));for(const s of S(o))s!=="dir"&&n.push(y.join(e,`${t}.${j[s]}`));return n.find(s=>$(s))}f(k,"bundleFor");function U(e,t,o){const n=k(e,t,o);if(n===void 0)throw new Error(`no bundle found for the base locale (expected ${t}/translation.json)`);return b(A(n))}f(U,"bundleAt");function N(e,t="en",o="auto"){const n=[];if(!$(e))return n.push({locale:t,problem:`${e} does not exist`}),{locales:[],keys:0,problems:n};const s=k(e,t,o);if(s===void 0)return n.push({locale:t,problem:`no bundle found for the base locale (expected ${t}/translation.json)`}),{locales:[],keys:0,problems:n};let r;try{r=b(A(s))}catch(l){return n.push({locale:t,problem:`${s}: ${l instanceof Error?l.message:String(l)}`}),{locales:[],keys:0,problems:n}}const c=new Set(r.keys());if(c.size===0)return n.push({locale:t,problem:`${s} has no keys \u2014 the base bundle is empty or unreadable`}),{locales:[t],keys:0,problems:n};const a=[...new Set([...C(e,o),t])].sort((l,p)=>l.localeCompare(p));for(const l of a){const p=k(e,l,o);if(p===void 0){n.push({locale:l,problem:"no bundle found"});continue}let i;try{i=b(A(p))}catch(u){n.push({locale:l,problem:`${p}: ${u instanceof Error?u.message:String(u)}`});continue}for(const u of c)i.has(u)||n.push({locale:l,problem:`missing key: ${u}`});for(const[u,h]of i){if(!c.has(u)){n.push({locale:l,problem:`extra key not in ${t}: ${u}`});continue}if(typeof h!="string"||h===""){n.push({locale:l,problem:`empty value: ${u} \u2014 indistinguishable from a missing key at runtime`});continue}const d=x(r.get(u));if(d.length===0)continue;const m=x(h);(d.length!==m.length||d.some((P,W)=>P!==m[W]))&&n.push({locale:l,problem:`placeholder mismatch at ${u}: ${l} has ${JSON.stringify(m)}, ${t} has ${JSON.stringify(d)}`})}}return{locales:a,keys:c.size,problems:n}}f(N,"validateLocales");function F(e,t,o){const n=[];for(const s of E(e)){const r=g(s,"utf8"),c=/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1\s*(,)?/g;for(const a of r.matchAll(c)){const l=a[2];if(l.includes("${")||l.includes("{{"))continue;const p=y.relative(process.cwd(),s)||s;if(!t.has(l)){n.push({locale:"call-site",problem:`${p}: t('${l}') is not in the bundle \u2014 it renders as the inline default and is untranslatable`});continue}if(!a[3])continue;const i=K(r,a.index+a[0].length);if(i===null)continue;const u=o.get(l);i!==u&&n.push({locale:"call-site",problem:`${p}: t('${l}', \u2026) default disagrees with the bundle \u2014 bundle=${JSON.stringify(u)} default=${JSON.stringify(i)}`})}}return n}f(F,"collectCallSites");function K(e,t){const o=e.slice(t).replace(/^\s+/,""),n=o[0];if(n!=="'"&&n!=='"')return null;const s=o.slice(1),c=(n==="'"?/^(?:[^'\\]|\\.)*'/:/^(?:[^"\\]|\\.)*"/).exec(s);return c?q(s.slice(0,c[0].length-1)):null}f(K,"readDefault");function q(e){return e.replaceAll(/\\(.)/gs,(t,o)=>{switch(o){case"n":return`
|
|
5
|
+
`;case"t":return" ";case"r":return"\r";case"\\":case"'":case'"':case"`":return o;default:return t}})}f(q,"decodeStringLiteral");function B(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*(['"])((?:[^'"\\]|\\.)*)\1/g)){const s=n[2];!s.includes("${")&&!s.includes("{{")&&t.add(s)}return t}f(B,"usedKeys");function E(e){const t=[],o=f(n=>{for(const s of w(n,{withFileTypes:!0})){const r=y.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules"||s.name==="dist"||s.name==="coverage")continue;o(r);continue}e.extensions.some(c=>s.name.endsWith(c))&&t.push(r)}},"walk");return o(e.dir),t}f(E,"sourceFiles");function G(e,t,o){const n=R(t),s=e.filter(r=>!o.has(r)&&[...n].every(c=>!(r===c||r.startsWith(`${c}.`))));return s.length===0?[]:[{locale:"call-site",problem:`${s.length} base key(s) are not reached by any t() call site: ${s.slice(0,20).join(", ")}${s.length>20?", \u2026":""}`,advisory:!0}]}f(G,"collectUnusedKeys");function R(e){const t=new Set;for(const o of E(e))for(const n of g(o,"utf8").matchAll(/\bt\(\s*`([^`$]*)\$\{/g)){const s=n[1].replace(/\.$/,"");s&&t.add(s)}return t}f(R,"dynamicKeyPrefixes");function z(e){const t=g(e,"utf8"),o=/(?:export\s+)?const\s+(?:SUPPORTED_LANGUAGES|SUPPORTED_LOCALES)\s*=\s*\[([^\]]*)\]/.exec(t);if(!o)throw new Error(`${e} declares no SUPPORTED_LANGUAGES/SUPPORTED_LOCALES array literal`);return[...(o[1]??"").matchAll(/['"]([^'"]+)['"]/g)].map(n=>n[1])}f(z,"declaredTags");function D(e,t,o){const n=z(t),s=[];for(const r of n)o.includes(r)||s.push({locale:"tags",problem:`${t} declares '${r}' but ${e}/${r} does not exist \u2014 selecting that language throws`});for(const r of o)n.includes(r)||s.push({locale:"tags",problem:`${e}/${r} exists but ${t} does not declare it \u2014 the selector cannot offer it`});return s}f(D,"checkDeclaredTags");function T(e=process.argv.slice(2)){const t=e.find(i=>!i.startsWith("--"))??"apps/web/src/locales",o=e.find(i=>i.startsWith("--shape="))?.slice(8)??"auto",n=e.find(i=>i.startsWith("--base="))?.slice(7)??"en",s=e.find(i=>i.startsWith("--call-sites="))?.slice(13),r=e.find(i=>i.startsWith("--tags="))?.slice(7),c=N(t,n,o),a=[...c.problems];if(r!==void 0&&$(r))try{a.push(...D(t,r,C(t,o)))}catch(i){a.push({locale:"tags",problem:`${r}: ${i instanceof Error?i.message:String(i)}`})}if(s!==void 0&&$(s))try{const i=U(t,n,o),u={dir:s,extensions:[".ts",".tsx"]},h=B(u);a.push(...F(u,new Set(i.keys()),i),...G([...i.keys()],u,h))}catch(i){a.push({locale:"call-site",problem:`${s}: ${i instanceof Error?i.message:String(i)}`})}const l=a.filter(i=>i.advisory!==!0),p=a.filter(i=>i.advisory===!0);if(l.length>0){console.error(`Locale validation failed for ${t} (${l.length} problem(s)):`);for(const i of l)console.error(` - ${i.locale}: ${i.problem}`);return 1}if(p.length>0){console.warn(`Locale validation passed for ${t} with ${p.length} advisory finding(s):`);for(const i of p)console.warn(` - ${i.locale}: ${i.problem}`)}return console.log(`Locale validation passed (${c.locales.length} locales, ${c.keys} keys each, shape ${o}).`),0}f(T,"validateLocalesCli");L(import.meta.url)&&process.exit(T(process.argv.slice(2)));export{O as parseObjectLiteral,N as validateLocales,T as validateLocalesCli};
|