@rexezuge/tooling 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +124 -14
  2. package/dist/eslint-manifest.d.ts +25 -0
  3. package/dist/eslint-manifest.d.ts.map +1 -0
  4. package/dist/eslint-manifest.js +1 -0
  5. package/dist/eslint-manifest.js.map +7 -0
  6. package/dist/eslint-strict.d.ts +45 -0
  7. package/dist/eslint-strict.d.ts.map +1 -0
  8. package/dist/eslint-strict.js +1 -0
  9. package/dist/eslint-strict.js.map +7 -0
  10. package/dist/eslint.d.ts +20 -3
  11. package/dist/eslint.d.ts.map +1 -1
  12. package/dist/eslint.js +1 -1
  13. package/dist/eslint.js.map +3 -3
  14. package/dist/index.d.ts +5 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/index.js.map +3 -3
  18. package/dist/manifest-validate.d.ts +14 -0
  19. package/dist/manifest-validate.d.ts.map +1 -0
  20. package/dist/manifest-validate.js +1 -0
  21. package/dist/manifest-validate.js.map +7 -0
  22. package/dist/manifest.d.ts +159 -0
  23. package/dist/manifest.d.ts.map +1 -0
  24. package/dist/manifest.js +3 -0
  25. package/dist/manifest.js.map +7 -0
  26. package/dist/scripts/check-god-files.d.ts.map +1 -1
  27. package/dist/scripts/check-god-files.js +2 -2
  28. package/dist/scripts/check-god-files.js.map +3 -3
  29. package/dist/test/mocks/cloudflare-workers.d.ts +6 -103
  30. package/dist/test/mocks/cloudflare-workers.d.ts.map +1 -1
  31. package/dist/test/mocks/cloudflare-workers.js +1 -1
  32. package/dist/test/mocks/cloudflare-workers.js.map +3 -3
  33. package/dist/vite.d.ts.map +1 -1
  34. package/dist/vite.js.map +2 -2
  35. package/dist/vitest-aliases.d.ts +3 -0
  36. package/dist/vitest-aliases.d.ts.map +1 -1
  37. package/dist/vitest-aliases.js +1 -1
  38. package/dist/vitest-aliases.js.map +3 -3
  39. package/dist/vitest-repo.d.ts +2 -1
  40. package/dist/vitest-repo.d.ts.map +1 -1
  41. package/dist/vitest-repo.js +1 -1
  42. package/dist/vitest-repo.js.map +3 -3
  43. package/dist/vitest.d.ts +2 -1
  44. package/dist/vitest.d.ts.map +1 -1
  45. package/dist/vitest.js +1 -1
  46. package/dist/vitest.js.map +3 -3
  47. package/package.json +14 -3
  48. package/presets/prettier.d.mts +4 -0
  49. package/presets/prettier.mjs +16 -0
  50. package/presets/tsconfig/base.json +19 -0
  51. package/presets/tsconfig/web.json +10 -0
  52. package/presets/tsconfig/worker.json +9 -0
  53. package/schema/manifest.schema.json +105 -0
  54. package/src/eslint-manifest.ts +71 -0
  55. package/src/eslint-strict.test.ts +106 -0
  56. package/src/eslint-strict.ts +191 -0
  57. package/src/eslint.ts +36 -8
  58. package/src/index.ts +15 -2
  59. package/src/manifest-validate.ts +202 -0
  60. package/src/manifest.test.ts +228 -0
  61. package/src/manifest.ts +194 -0
  62. package/src/presets.test.ts +63 -0
  63. package/src/scripts/check-god-files.ts +3 -0
  64. package/src/test/mocks/cloudflare-workers.ts +6 -113
  65. package/src/vite.ts +1 -0
  66. package/src/vitest-aliases.test.ts +23 -0
  67. package/src/vitest-aliases.ts +22 -1
  68. package/src/vitest-factories.test.ts +30 -1
  69. package/src/vitest-repo.ts +5 -2
  70. package/src/vitest.ts +5 -2
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/manifest-validate.ts"],
4
+ "sourcesContent": ["import type { FamilyManifest, ManifestValidation } from './manifest.ts';\n\n/**\nFamily default god-file limits: a manifest may only lower them.\n*/\nexport const FAMILY_GOD_FILE_LIMITS = { soft: 300, hard: 400 } as const;\n\ntype Obj = Record<string, unknown>;\n\nconst isObj = (value: unknown): value is Obj => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst SCOPE_RE = /^@[a-z0-9][a-z0-9-]*$/;\nconst NAME_RE = /^[a-z][a-z0-9-]*$/;\nconst COVERAGE_KEYS = ['lines', 'branches', 'functions', 'statements'] as const;\n\n/**\nCollects errors under a dotted path so every message names its field.\n*/\nclass Check {\n readonly errors: string[] = [];\n fail(at: string, message: string): void {\n this.errors.push(`${at}: ${message}`);\n }\n /**\n Refuse unknown keys: the closed side.\n */\n keys(at: string, value: Obj, allowed: readonly string[]): void {\n for (const key of Object.keys(value)) {\n if (!allowed.includes(key)) this.fail(`${at}.${key}`, `unknown key (allowed: ${allowed.join(', ')})`);\n }\n }\n obj(at: string, value: unknown): Obj | null {\n if (isObj(value)) return value;\n this.fail(at, 'must be an object');\n return null;\n }\n str(at: string, value: unknown, pattern?: RegExp, hint?: string): value is string {\n if (typeof value !== 'string' || value === '') {\n this.fail(at, 'must be a non-empty string');\n return false;\n }\n if (pattern && !pattern.test(value)) {\n this.fail(at, `${JSON.stringify(value)} is invalid${hint ? ` (${hint})` : ''}`);\n return false;\n }\n return true;\n }\n bool(at: string, value: unknown): void {\n if (typeof value !== 'boolean') this.fail(at, 'must be a boolean');\n }\n strings(at: string, value: unknown): value is string[] {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || item === '')) {\n this.fail(at, 'must be an array of non-empty strings');\n return false;\n }\n return true;\n }\n}\n\nfunction checkFeatures(c: Check, value: unknown): void {\n const features = c.obj('features', value);\n if (!features) return;\n c.keys('features', features, ['d1', 'web', 'background', 'backupD1', 'durableObjects', 'queues', 'workflows', 'email', 'android']);\n if (features.d1 !== undefined) {\n const d1 = c.obj('features.d1', features.d1);\n if (d1) {\n c.keys('features.d1', d1, ['binding', 'database', 'migrationsDir']);\n c.str('features.d1.binding', d1.binding, /^[A-Z][A-Z0-9_]*$/, 'an UPPER_SNAKE binding name');\n c.str('features.d1.database', d1.database);\n if (d1.migrationsDir !== undefined) c.str('features.d1.migrationsDir', d1.migrationsDir);\n }\n }\n if (features.web !== undefined) {\n const web = c.obj('features.web', features.web);\n if (web) {\n c.keys('features.web', web, ['pages', 'spaShell']);\n c.bool('features.web.pages', web.pages);\n c.bool('features.web.spaShell', web.spaShell);\n }\n }\n for (const flag of ['background', 'backupD1', 'email', 'android'] as const) {\n if (features[flag] !== undefined) c.bool(`features.${flag}`, features[flag]);\n }\n for (const list of ['durableObjects', 'queues', 'workflows'] as const) {\n if (features[list] !== undefined) c.strings(`features.${list}`, features[list]);\n }\n}\n\nfunction checkLayer(c: Check, at: string, layer: Obj): void {\n c.keys(at, layer, ['name', 'dir', 'package', 'mayImport', 'typeOnly', 'forbid', 'forbidMessage', 'http', 'browser']);\n c.str(`${at}.name`, layer.name, NAME_RE, 'lower-case letters, digits and hyphens');\n if (c.str(`${at}.dir`, layer.dir) && (/[*?{}]/.test(layer.dir) || layer.dir.startsWith('/') || layer.dir.split('/').includes('..'))) {\n c.fail(`${at}.dir`, `${JSON.stringify(layer.dir)} must be a repo-relative directory without globs`);\n }\n if (layer.package !== undefined) c.str(`${at}.package`, layer.package);\n if (layer.forbidMessage !== undefined) c.str(`${at}.forbidMessage`, layer.forbidMessage);\n for (const list of ['mayImport', 'typeOnly', 'forbid'] as const) {\n if (layer[list] !== undefined || list === 'mayImport') c.strings(`${at}.${list}`, layer[list]);\n }\n for (const flag of ['http', 'browser'] as const) if (layer[flag] !== undefined) c.bool(`${at}.${flag}`, layer[flag]);\n}\n\nfunction checkLayers(c: Check, value: unknown): void {\n if (!Array.isArray(value)) {\n c.fail('layers', 'must be an array of layers');\n return;\n }\n const names = new Set<string>();\n const dirs = new Set<string>();\n value.forEach((entry: unknown, index) => {\n const at = `layers[${index}]`;\n const layer = c.obj(at, entry);\n if (!layer) return;\n checkLayer(c, at, layer);\n if (typeof layer.name === 'string') {\n if (names.has(layer.name)) c.fail(`${at}.name`, `duplicate layer name ${JSON.stringify(layer.name)}`);\n names.add(layer.name);\n }\n if (typeof layer.dir !== 'string') {\n return;\n }\n\n if (dirs.has(layer.dir)) c.fail(`${at}.dir`, `duplicate layer dir ${JSON.stringify(layer.dir)}`);\n dirs.add(layer.dir);\n });\n value.forEach((entry: unknown, index) => {\n if (!isObj(entry)) return;\n for (const list of ['mayImport', 'typeOnly'] as const) {\n const refs = entry[list];\n if (!Array.isArray(refs)) continue;\n for (const ref of refs) {\n if (typeof ref === 'string' && !names.has(ref)) c.fail(`layers[${index}].${list}`, `unknown layer ${JSON.stringify(ref)}`);\n if (list === 'typeOnly' && Array.isArray(entry.mayImport) && entry.mayImport.includes(ref)) {\n c.fail(`layers[${index}].typeOnly`, `${JSON.stringify(ref)} is already in mayImport`);\n }\n }\n }\n });\n}\n\nfunction checkQuality(c: Check, value: unknown): void {\n const quality = c.obj('quality', value);\n if (!quality) return;\n c.keys('quality', quality, ['coverage', 'godFiles']);\n if (quality.coverage !== undefined) checkCoverage(c, quality.coverage);\n if (quality.godFiles !== undefined) checkGodFiles(c, quality.godFiles);\n}\n\nfunction checkGodFiles(c: Check, value: unknown): void {\n const god = c.obj('quality.godFiles', value);\n if (!god) return;\n c.keys('quality.godFiles', god, ['soft', 'hard']);\n for (const key of ['soft', 'hard'] as const) {\n const limit = god[key];\n const ceiling = FAMILY_GOD_FILE_LIMITS[key];\n if (!Number.isInteger(limit) || (limit as number) < 1) c.fail(`quality.godFiles.${key}`, 'must be a positive integer');\n else if ((limit as number) > ceiling) {\n c.fail(`quality.godFiles.${key}`, `${String(limit)} is above the family limit ${ceiling}: god-file limits may only be lowered`);\n }\n }\n if (typeof god.soft === 'number' && typeof god.hard === 'number' && god.soft > god.hard) {\n c.fail('quality.godFiles.soft', 'must not exceed quality.godFiles.hard');\n }\n}\n\nfunction checkCoverage(c: Check, value: unknown): void {\n const coverage = c.obj('quality.coverage', value);\n if (!coverage) return;\n c.keys('quality.coverage', coverage, COVERAGE_KEYS);\n for (const key of COVERAGE_KEYS) {\n const figure = coverage[key];\n if (typeof figure !== 'number' || !(figure >= 0 && figure <= 100)) c.fail(`quality.coverage.${key}`, 'must be a number from 0 to 100');\n }\n}\n\nfunction checkExtensions(c: Check, value: unknown): void {\n const extensions = c.obj('extensions', value);\n if (!extensions) return;\n for (const [key, entry] of Object.entries(extensions)) {\n if (!NAME_RE.test(key)) c.fail(`extensions.${key}`, 'namespace must be lower-case letters, digits and hyphens');\n if (!isObj(entry)) c.fail(`extensions.${key}`, 'must be an object (extensions are namespaced: one object per owner)');\n }\n}\n\n/**\n * Validate an already-parsed value. Returns every problem found, not just the\n * first, so one edit can fix them all.\n */\nexport function validateManifest(input: unknown): ManifestValidation {\n const c = new Check();\n const root = c.obj('manifest', input);\n if (root) {\n c.keys('manifest', root, ['$schema', 'name', 'scope', 'features', 'layers', 'quality', 'extensions']);\n if (root.$schema !== undefined) c.str('$schema', root.$schema);\n c.str('name', root.name);\n c.str('scope', root.scope, SCOPE_RE, 'an npm scope such as \"@mail-meow\"');\n if (root.features !== undefined) checkFeatures(c, root.features);\n if (root.layers !== undefined) checkLayers(c, root.layers);\n if (root.quality !== undefined) checkQuality(c, root.quality);\n if (root.extensions !== undefined) checkExtensions(c, root.extensions);\n }\n return c.errors.length > 0 ? { ok: false, errors: c.errors } : { ok: true, manifest: input as FamilyManifest };\n}\n"],
5
+ "mappings": "+EAKO,MAAMA,EAAyB,CAAE,KAAM,IAAK,KAAM,GAAG,EAItDC,EAAQC,EAACC,GAAiC,OAAOA,GAAU,UAAYA,IAAU,MAAQ,CAAC,MAAM,QAAQA,CAAK,EAArG,SACRC,EAAW,wBACXC,EAAU,oBACVC,EAAgB,CAAC,QAAS,WAAY,YAAa,YAAY,EAKrE,MAAMC,CAAK,CAfX,MAeW,CAAAL,EAAA,cACA,OAAmB,CAAA,EAC5B,KAAKM,EAAYC,EAAe,CAC9B,KAAK,OAAO,KAAK,GAAGD,CAAE,KAAKC,CAAO,EAAE,CACtC,CAIA,KAAKD,EAAYL,EAAYO,EAA0B,CACrD,UAAWC,KAAO,OAAO,KAAKR,CAAK,EAC5BO,EAAQ,SAASC,CAAG,GAAG,KAAK,KAAK,GAAGH,CAAE,IAAIG,CAAG,GAAI,yBAAyBD,EAAQ,KAAK,IAAI,CAAC,GAAG,CAEx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CAAE,GAAI,GAAM,SAAU2B,CAAuB,CAC9G,CAdgBzC,EAAAwC,EAAA",
6
+ "names": ["FAMILY_GOD_FILE_LIMITS", "isObj", "__name", "value", "SCOPE_RE", "NAME_RE", "COVERAGE_KEYS", "Check", "at", "message", "allowed", "key", "pattern", "hint", "item", "checkFeatures", "c", "features", "d1", "web", "flag", "list", "checkLayer", "layer", "checkLayers", "names", "dirs", "entry", "index", "refs", "ref", "checkQuality", "quality", "checkCoverage", "checkGodFiles", "god", "limit", "ceiling", "coverage", "figure", "checkExtensions", "extensions", "validateManifest", "input", "root"]
7
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The family manifest: `.rexezuge.jsonc` at a repo root.
3
+ *
4
+ * One declarative file states what a repo *is* (its scope, the platform features
5
+ * it uses, its dependency layers) and how strict it holds itself (coverage
6
+ * floors, god-file limits). The tooling factories read it instead of each
7
+ * encoding consumer directory names, so the kit stays free of repo layouts and a
8
+ * repo's layout stays out of its lint config.
9
+ *
10
+ * The charter applies to the file itself. The **closed** side is the schema:
11
+ * unknown keys are refused (a typo is an error, not a silent no-op), and
12
+ * `quality.godFiles` may only be lowered below the family default, never raised.
13
+ * The **open** side is `extensions`: a free-form object, namespaced by the key
14
+ * that owns it, that the kit never reads.
15
+ *
16
+ * `manifest.schema.json` (shipped beside this module) describes the same shape
17
+ * for editor completion via `$schema`; a test keeps the two in step.
18
+ */
19
+ export { FAMILY_GOD_FILE_LIMITS, validateManifest } from './manifest-validate.ts';
20
+ /**
21
+ The file name, resolved against a repo root.
22
+ */
23
+ export declare const MANIFEST_FILENAME = ".rexezuge.jsonc";
24
+ export interface ManifestD1 {
25
+ readonly binding: string;
26
+ readonly database: string;
27
+ readonly migrationsDir?: string;
28
+ }
29
+ export interface ManifestWeb {
30
+ /**
31
+ The SPA is served by Cloudflare Pages.
32
+ */
33
+ readonly pages: boolean;
34
+ /**
35
+ The SPA shell is embedded into the worker (`spa-shell` scripts).
36
+ */
37
+ readonly spaShell: boolean;
38
+ }
39
+ export interface ManifestFeatures {
40
+ readonly d1?: ManifestD1;
41
+ readonly web?: ManifestWeb;
42
+ readonly background?: boolean;
43
+ readonly backupD1?: boolean;
44
+ /**
45
+ Durable Object class names.
46
+ */
47
+ readonly durableObjects?: readonly string[];
48
+ /**
49
+ Queue names.
50
+ */
51
+ readonly queues?: readonly string[];
52
+ /**
53
+ Workflow class names.
54
+ */
55
+ readonly workflows?: readonly string[];
56
+ readonly email?: boolean;
57
+ readonly android?: boolean;
58
+ }
59
+ /**
60
+ * One dependency layer: a directory, and the other layers it may import.
61
+ *
62
+ * Everything not named in `mayImport` / `typeOnly` is banned, by package name
63
+ * (`<scope>/<basename of dir>`, or `package`). `mayImport: []` isolates the layer
64
+ * from the whole scope (`<scope>/*`).
65
+ */
66
+ export interface ManifestLayer {
67
+ readonly name: string;
68
+ /**
69
+ Repo-relative directory, no globs: `packages/backend-data`.
70
+ */
71
+ readonly dir: string;
72
+ /**
73
+ Package suffix when it is not the directory's basename.
74
+ */
75
+ readonly package?: string;
76
+ /**
77
+ Names of layers this layer may import.
78
+ */
79
+ readonly mayImport: readonly string[];
80
+ /**
81
+ Names of layers importable as `import type` only.
82
+ */
83
+ readonly typeOnly?: readonly string[];
84
+ /**
85
+ Extra external specifiers this layer may not import, e.g. `aws4fetch`.
86
+ */
87
+ readonly forbid?: readonly string[];
88
+ /**
89
+ Message for `forbid`; defaults to a generic one.
90
+ */
91
+ readonly forbidMessage?: string;
92
+ /**
93
+ May import `hono`/`chanfana` (and hand-build error envelopes).
94
+ */
95
+ readonly http?: boolean;
96
+ /**
97
+ Browser code: may use `console`, and lints with browser globals.
98
+ */
99
+ readonly browser?: boolean;
100
+ }
101
+ export interface ManifestCoverage {
102
+ readonly lines: number;
103
+ readonly branches: number;
104
+ readonly functions: number;
105
+ readonly statements: number;
106
+ }
107
+ export interface ManifestQuality {
108
+ readonly coverage?: ManifestCoverage;
109
+ readonly godFiles?: {
110
+ readonly soft: number;
111
+ readonly hard: number;
112
+ };
113
+ }
114
+ export interface FamilyManifest {
115
+ readonly $schema?: string;
116
+ readonly name: string;
117
+ /**
118
+ npm scope with the `@`, e.g. `@mail-meow`.
119
+ */
120
+ readonly scope: string;
121
+ readonly features?: ManifestFeatures;
122
+ readonly layers?: readonly ManifestLayer[];
123
+ readonly quality?: ManifestQuality;
124
+ /**
125
+ Repo-specific settings, namespaced by key. Never read by the kit.
126
+ */
127
+ readonly extensions?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
128
+ }
129
+ export type ManifestValidation = {
130
+ readonly ok: true;
131
+ readonly manifest: FamilyManifest;
132
+ } | {
133
+ readonly ok: false;
134
+ readonly errors: string[];
135
+ };
136
+ /**
137
+ Thrown by {@link loadManifest} and {@link parseManifest}; `errors` has one line per problem.
138
+ */
139
+ export declare class ManifestError extends Error {
140
+ readonly errors: readonly string[];
141
+ constructor(source: string, errors: readonly string[]);
142
+ }
143
+ /**
144
+ Parse JSONC text and validate it. Throws {@link ManifestError}.
145
+ */
146
+ export declare function parseManifest(text: string, source?: string): FamilyManifest;
147
+ /**
148
+ * Load `<root>/.rexezuge.jsonc`. Returns `null` when the file is absent (the
149
+ * repo has not adopted a manifest) and throws {@link ManifestError} when it is
150
+ * present but invalid: a broken manifest must fail the gate, not fall back.
151
+ */
152
+ export declare function loadManifest(root: string): FamilyManifest | null;
153
+ /**
154
+ * The manifest's coverage floor for a vitest config, or `undefined` when the
155
+ * repo has no manifest or declares none. `root` is what the factories take: a
156
+ * directory path or a `file:` URL (`new URL('.', import.meta.url).href`).
157
+ */
158
+ export declare function manifestCoverageThresholds(root: string): ManifestCoverage | undefined;
159
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AASH,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAElF;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MAAM,MAAM,kBAAkB,GAC5B;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAA;CAAE,GAAG;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE/G;;EAEE;AACF,qBAAa,aAAc,SAAQ,KAAK;IACtC,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;gBACvB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,MAAM,EAAE;CAKtD;AAED;;EAEE;AACF,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,GAAE,MAA0B,GAAG,cAAc,CAY9F;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,IAAI,CAIhE;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAGrF"}
@@ -0,0 +1,3 @@
1
+ var l=Object.defineProperty;var o=(t,r)=>l(t,"name",{value:r,configurable:!0});import{existsSync as m,readFileSync as p}from"node:fs";import c from"node:path";import{fileURLToPath as u}from"node:url";import{parse as x,printParseErrorCode as h}from"jsonc-parser";import{validateManifest as M}from"./manifest-validate.js";import{FAMILY_GOD_FILE_LIMITS as S,validateManifest as _}from"./manifest-validate.js";const i=".rexezuge.jsonc";class f extends Error{static{o(this,"ManifestError")}errors;constructor(r,e){super(`${r} is not a valid family manifest:
2
+ ${e.map(n=>` - ${n}`).join(`
3
+ `)}`),this.name="ManifestError",this.errors=e}}function d(t,r=i){const e=[],n=x(t,e,{allowTrailingComma:!0});if(e.length>0)throw new f(r,e.map(a=>`syntax error at offset ${a.offset}: ${h(a.error)}`));const s=M(n);if(!s.ok)throw new f(r,s.errors);return s.manifest}o(d,"parseManifest");function E(t){const r=c.join(t,i);return m(r)?d(p(r,"utf8"),r):null}o(E,"loadManifest");function L(t){const r=t.startsWith("file:")?u(t):t;return E(r)?.quality?.coverage}o(L,"manifestCoverageThresholds");export{S as FAMILY_GOD_FILE_LIMITS,i as MANIFEST_FILENAME,f as ManifestError,E as loadManifest,L as manifestCoverageThresholds,d as parseManifest,_ as validateManifest};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/manifest.ts"],
4
+ "sourcesContent": ["/**\n * The family manifest: `.rexezuge.jsonc` at a repo root.\n *\n * One declarative file states what a repo *is* (its scope, the platform features\n * it uses, its dependency layers) and how strict it holds itself (coverage\n * floors, god-file limits). The tooling factories read it instead of each\n * encoding consumer directory names, so the kit stays free of repo layouts and a\n * repo's layout stays out of its lint config.\n *\n * The charter applies to the file itself. The **closed** side is the schema:\n * unknown keys are refused (a typo is an error, not a silent no-op), and\n * `quality.godFiles` may only be lowered below the family default, never raised.\n * The **open** side is `extensions`: a free-form object, namespaced by the key\n * that owns it, that the kit never reads.\n *\n * `manifest.schema.json` (shipped beside this module) describes the same shape\n * for editor completion via `$schema`; a test keeps the two in step.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';\nimport type { ParseError } from 'jsonc-parser';\nimport { validateManifest } from './manifest-validate.ts';\n\nexport { FAMILY_GOD_FILE_LIMITS, validateManifest } from './manifest-validate.ts';\n\n/**\nThe file name, resolved against a repo root.\n*/\nexport const MANIFEST_FILENAME = '.rexezuge.jsonc';\n\nexport interface ManifestD1 {\n readonly binding: string;\n readonly database: string;\n readonly migrationsDir?: string;\n}\n\nexport interface ManifestWeb {\n /**\n The SPA is served by Cloudflare Pages.\n */\n readonly pages: boolean;\n /**\n The SPA shell is embedded into the worker (`spa-shell` scripts).\n */\n readonly spaShell: boolean;\n}\n\nexport interface ManifestFeatures {\n readonly d1?: ManifestD1;\n readonly web?: ManifestWeb;\n readonly background?: boolean;\n readonly backupD1?: boolean;\n /**\n Durable Object class names.\n */\n readonly durableObjects?: readonly string[];\n /**\n Queue names.\n */\n readonly queues?: readonly string[];\n /**\n Workflow class names.\n */\n readonly workflows?: readonly string[];\n readonly email?: boolean;\n readonly android?: boolean;\n}\n\n/**\n * One dependency layer: a directory, and the other layers it may import.\n *\n * Everything not named in `mayImport` / `typeOnly` is banned, by package name\n * (`<scope>/<basename of dir>`, or `package`). `mayImport: []` isolates the layer\n * from the whole scope (`<scope>/*`).\n */\nexport interface ManifestLayer {\n readonly name: string;\n /**\n Repo-relative directory, no globs: `packages/backend-data`.\n */\n readonly dir: string;\n /**\n Package suffix when it is not the directory's basename.\n */\n readonly package?: string;\n /**\n Names of layers this layer may import.\n */\n readonly mayImport: readonly string[];\n /**\n Names of layers importable as `import type` only.\n */\n readonly typeOnly?: readonly string[];\n /**\n Extra external specifiers this layer may not import, e.g. `aws4fetch`.\n */\n readonly forbid?: readonly string[];\n /**\n Message for `forbid`; defaults to a generic one.\n */\n readonly forbidMessage?: string;\n /**\n May import `hono`/`chanfana` (and hand-build error envelopes).\n */\n readonly http?: boolean;\n /**\n Browser code: may use `console`, and lints with browser globals.\n */\n readonly browser?: boolean;\n}\n\nexport interface ManifestCoverage {\n readonly lines: number;\n readonly branches: number;\n readonly functions: number;\n readonly statements: number;\n}\n\nexport interface ManifestQuality {\n readonly coverage?: ManifestCoverage;\n readonly godFiles?: { readonly soft: number; readonly hard: number };\n}\n\nexport interface FamilyManifest {\n readonly $schema?: string;\n readonly name: string;\n /**\n npm scope with the `@`, e.g. `@mail-meow`.\n */\n readonly scope: string;\n readonly features?: ManifestFeatures;\n readonly layers?: readonly ManifestLayer[];\n readonly quality?: ManifestQuality;\n /**\n Repo-specific settings, namespaced by key. Never read by the kit.\n */\n readonly extensions?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n}\n\nexport type ManifestValidation =\n { readonly ok: true; readonly manifest: FamilyManifest } | { readonly ok: false; readonly errors: string[] };\n\n/**\nThrown by {@link loadManifest} and {@link parseManifest}; `errors` has one line per problem.\n*/\nexport class ManifestError extends Error {\n readonly errors: readonly string[];\n constructor(source: string, errors: readonly string[]) {\n super(`${source} is not a valid family manifest:\\n${errors.map((line) => ` - ${line}`).join('\\n')}`);\n this.name = 'ManifestError';\n this.errors = errors;\n }\n}\n\n/**\nParse JSONC text and validate it. Throws {@link ManifestError}.\n*/\nexport function parseManifest(text: string, source: string = MANIFEST_FILENAME): FamilyManifest {\n const syntax: ParseError[] = [];\n const value: unknown = parseJsonc(text, syntax, { allowTrailingComma: true });\n if (syntax.length > 0) {\n throw new ManifestError(\n source,\n syntax.map((error) => `syntax error at offset ${error.offset}: ${printParseErrorCode(error.error)}`),\n );\n }\n const result = validateManifest(value);\n if (!result.ok) throw new ManifestError(source, result.errors);\n return result.manifest;\n}\n\n/**\n * Load `<root>/.rexezuge.jsonc`. Returns `null` when the file is absent (the\n * repo has not adopted a manifest) and throws {@link ManifestError} when it is\n * present but invalid: a broken manifest must fail the gate, not fall back.\n */\nexport function loadManifest(root: string): FamilyManifest | null {\n const file = path.join(root, MANIFEST_FILENAME);\n if (!existsSync(file)) return null;\n return parseManifest(readFileSync(file, 'utf8'), file);\n}\n\n/**\n * The manifest's coverage floor for a vitest config, or `undefined` when the\n * repo has no manifest or declares none. `root` is what the factories take: a\n * directory path or a `file:` URL (`new URL('.', import.meta.url).href`).\n */\nexport function manifestCoverageThresholds(root: string): ManifestCoverage | undefined {\n const dir = root.startsWith('file:') ? fileURLToPath(root) : root;\n return loadManifest(dir)?.quality?.coverage;\n}\n"],
5
+ "mappings": "+EAmBA,OAAS,cAAAA,EAAY,gBAAAC,MAAoB,UACzC,OAAOC,MAAU,YACjB,OAAS,iBAAAC,MAAqB,WAC9B,OAAS,SAASC,EAAY,uBAAAC,MAA2B,eAEzD,OAAS,oBAAAC,MAAwB,yBAEjC,OAAS,0BAAAC,EAAwB,oBAAAD,MAAwB,yBAKlD,MAAME,EAAoB,kBAqH3B,MAAOC,UAAsB,KAAK,CApJxC,MAoJwC,CAAAC,EAAA,sBAC7B,OACT,YAAYC,EAAgBC,EAAyB,CACnD,MAAM,GAAGD,CAAM;EAAqCC,EAAO,IAAKC,GAAS,OAAOA,CAAI,EAAE,EAAE,KAAK;CAAI,CAAC,EAAE,EACpG,KAAK,KAAO,gBACZ,KAAK,OAASD,CAChB,EAMI,SAAUE,EAAcC,EAAcJ,EAAiBH,EAAiB,CAC5E,MAAMQ,EAAuB,CAAA,EACvBC,EAAiBb,EAAWW,EAAMC,EAAQ,CAAE,mBAAoB,EAAI,CAAE,EAC5E,GAAIA,EAAO,OAAS,EAClB,MAAM,IAAIP,EACRE,EACAK,EAAO,IAAKE,GAAU,0BAA0BA,EAAM,MAAM,KAAKb,EAAoBa,EAAM,KAAK,CAAC,EAAE,CAAC,EAGxG,MAAMC,EAASb,EAAiBW,CAAK,EACrC,GAAI,CAACE,EAAO,GAAI,MAAM,IAAIV,EAAcE,EAAQQ,EAAO,MAAM,EAC7D,OAAOA,EAAO,QAChB,CAZgBT,EAAAI,EAAA,iBAmBV,SAAUM,EAAaC,EAAY,CACvC,MAAMC,EAAOpB,EAAK,KAAKmB,EAAMb,CAAiB,EAC9C,OAAKR,EAAWsB,CAAI,EACbR,EAAcb,EAAaqB,EAAM,MAAM,EAAGA,CAAI,EADvB,IAEhC,CAJgBZ,EAAAU,EAAA,gBAWV,SAAUG,EAA2BF,EAAY,CACrD,MAAMG,EAAMH,EAAK,WAAW,OAAO,EAAIlB,EAAckB,CAAI,EAAIA,EAC7D,OAAOD,EAAaI,CAAG,GAAG,SAAS,QACrC,CAHgBd,EAAAa,EAAA",
6
+ "names": ["existsSync", "readFileSync", "path", "fileURLToPath", "parseJsonc", "printParseErrorCode", "validateManifest", "FAMILY_GOD_FILE_LIMITS", "MANIFEST_FILENAME", "ManifestError", "__name", "source", "errors", "line", "parseManifest", "text", "syntax", "value", "error", "result", "loadManifest", "root", "file", "manifestCoverageThresholds", "dir"]
7
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"check-god-files.d.ts","sourceRoot":"","sources":["../../src/scripts/check-god-files.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AAQH;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;MAEE;IACF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;MAEE;IACF,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;MAEE;IACF,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B;;MAEE;IACF,QAAQ,CAAC,QAAQ,EAAE,SAAS,cAAc,EAAE,CAAC;IAC7C;;MAEE;IACF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB;;MAEE;IACF,QAAQ,CAAC,WAAW,EAAE,SAAS,cAAc,EAAE,CAAC;IAChD;;;;;OAKG;IACH,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB;;MAEE;IACF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;MAEE;IACF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC;;MAEE;IACF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;MAEE;IACF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;MAEE;IACF,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED;;EAEE;AACF,eAAO,MAAM,UAAU,MAAM,CAAC;AAC9B;;EAEE;AACF,eAAO,MAAM,UAAU,MAAM,CAAC;AA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E;IACF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;MAEE;IACF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC;;MAEE;IACF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;MAEE;IACF,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB;;MAEE;IACF,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED;;EAEE;AACF,eAAO,MAAM,UAAU,MAAM,CAAC;AAC9B;;EAEE;AACF,eAAO,MAAM,UAAU,MAAM,CAAC;AA+B9B;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAc/C;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAEhF;AAED;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAqB3C;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,cAAc,GAAG,aAAa,CA+BpE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAiBpD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,GAAE,SAAS,MAAM,EAA0B,GAAG,MAAM,CA4BxF"}
@@ -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 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
+ 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 y,valueOf as g}from"./lib/cli-args.js";import{loadManifest as E}from"../manifest.js";const O=300,I=400,W=new Set(["node_modules","dist",".wrangler","coverage","coverage-integration","coverage-web",".git"]),k=/\.(?:ts|tsx|js|mjs|cjs|css)$/,A=["test","spec"].flatMap(t=>[".ts",".tsx",".js",".jsx",".mjs",".cjs"].map(s=>`.${t}${s}`));function F(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:A.some(s=>t.endsWith(s))}a(F,"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 i of S(o)){const r=d.join(o,i);let n;try{n=$(r)}catch{continue}if(n.isDirectory()){if(W.has(i))continue;e(r)}else k.test(i)&&s.push(d.relative(t,r))}},"visit");return e(t),s}a(T,"walk");function C(t){const s=t.soft??O,e=t.hard??I,o=t.allowlist??[],i=T(t.root).filter(l=>!F(l)),r=[],n=[];for(const l of i){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)?n.push(p):r.push(p)}r.sort((l,f)=>f.lines-l.lines),n.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 (${i.length} files, ${r.length} over soft limit ${s}, ${n.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:n,scanned:i.length,passed:h,reported:m}}a(C,"checkGodFiles");function N(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(N,"readAllowlist");function D(t=process.argv.slice(2)){const{positional:s,rest:e}=y(t,["root","allowlist"]),o=x(e,{value:["root","allowlist"],boolean:["fail-on-hard"]}),i=g(o,"root")??s[0]??".",r=g(o,"allowlist")??d.join(i,"scripts/god-files.allowlist.json"),n=C({root:i,allowlist:N(r),...E(i)?.quality?.godFiles,failOnHard:_(o,"fail-on-hard")});console.log(n.reported);for(const c of n.findings)console.log(`${c.level==="critical"?"CRITICAL":"WARN"} ${c.lines} ${c.file}`);for(const c of n.allowlisted)console.log(`ALLOWLISTED ${c.lines} ${c.file}`);return n.passed||v(`God-file check failed: run with --root ${i} to see the report.`),0}a(D,"checkGodFilesCli"),j(import.meta.url)&&process.exit(D(process.argv.slice(2)));export{I as HARD_LIMIT,O as SOFT_LIMIT,C as checkGodFiles,D as checkGodFilesCli,L as isAllowlisted,N as readAllowlist,F 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 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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AAI,EAAE,EAE5D,OAAKiB,EAAO,QACVpD,EAAK,0CAA0CqB,CAAI,qBAAqB,EAEnE,CACT,CA1BgBL,EAAA8B,EAAA,oBAmCZ7C,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAK6C,EAAiB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
- "names": ["readdirSync", "readFileSync", "statSync", "path", "fail", "isEntrypoint", "isSet", "parseFlags", "splitPositional", "valueOf", "SOFT_LIMIT", "HARD_LIMIT", "EXCLUDE_DIRS", "SOURCE_EXTENSIONS", "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"]
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';\nimport { loadManifest } from '../manifest.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 // A manifest may only lower the family limits (the validator refuses more).\n ...loadManifest(root)?.quality?.godFiles,\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.\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AAa,EAEtC,GAAG9C,EAAagB,CAAI,GAAG,SAAS,SAChC,WAAYpB,EAAMiD,EAAO,cAAc,EACxC,EACD,QAAQ,IAAIE,EAAO,QAAQ,EAC3B,UAAWjB,KAAWiB,EAAO,SAC3B,QAAQ,IAAI,GAAGjB,EAAQ,QAAU,WAAa,WAAa,MAAM,IAAIA,EAAQ,KAAK,IAAIA,EAAQ,IAAI,EAAE,EAEtG,UAAWA,KAAWiB,EAAO,YAC3B,QAAQ,IAAI,eAAejB,EAAQ,KAAK,IAAIA,EAAQ,IAAI,EAAE,EAE5D,OAAKiB,EAAO,QACVrD,EAAK,0CAA0CsB,CAAI,qBAAqB,EAEnE,CACT,CA5BgBL,EAAA8B,EAAA,oBAqCZ9C,EAAa,YAAY,GAAG,GAC9B,QAAQ,KAAK8C,EAAiB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC",
6
+ "names": ["readdirSync", "readFileSync", "statSync", "path", "fail", "isEntrypoint", "isSet", "parseFlags", "splitPositional", "valueOf", "loadManifest", "SOFT_LIMIT", "HARD_LIMIT", "EXCLUDE_DIRS", "SOURCE_EXTENSIONS", "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
  }
@@ -1,106 +1,9 @@
1
1
  /**
2
- * Stand-in for the `cloudflare:workers` module, which has no Node equivalent.
3
- *
4
- * Provenance: converged from the eight copies at `test/mocks/cloudflare-workers.ts`
5
- * (AWS-AccessBridge, CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Edge-Git,
6
- * Edge-Sonic, Mail-Meow, Mail-Otter). All eight are the same twenty lines; the
7
- * union is three base classes and the union exists because each repo discovered a
8
- * missing one the hard way.
9
- *
10
- * ### What each source contributes
11
- *
12
- * - **DurableObject** — every copy. Stores `ctx` and `env` so a real DO class can
13
- * be constructed and its lifecycle RPCs driven directly, without Miniflare.
14
- * - **`RpcTarget`** — Durable-DAV's, and the reason is load-bearing rather than
15
- * tidy: `dofs`' `Fs` class `extends RpcTarget`, so the module fails to evaluate
16
- * with *"Class extends value undefined"* when the base is missing. That is a
17
- * module-load error, not a test failure, so it surfaces as an unimportable
18
- * `dav-store` barrel and no unit test can reach `DavRepository`. Deliberately
19
- * empty: on the platform it marks which methods are callable across an RPC
20
- * boundary, and nothing in a Node suite calls those through RPC. An empty base
21
- * keeps the fake honest instead of pretending to implement dispatch.
22
- * - **`WorkflowEntrypoint`** — Edge-Git, Edge-Sonic, Mail-Meow, Mail-Otter. A
23
- * Workflow class extends it, so the mock must provide it or the module fails the
24
- * same way — a **startup** error, which therefore takes down every suite that
25
- * reaches `apps/background` for an unrelated reason. Edge-Sonic's is the shape
26
- * kept: it stores `ctx` as well as `env`, because the failure policy under test
27
- * in `runWorkflow` lives in a plain function precisely so it can be exercised
28
- * without workerd, and that policy reads the execution context.
29
- *
30
- * ### Why the ambient types are declared here rather than imported
31
- *
32
- * The source repos name `DurableObjectState`, `ExecutionContext` and `Env`
33
- * unqualified, which resolves only because `worker-configuration.d.ts` and
34
- * `@cloudflare/workers-types` are ambient inside a Wrangler project. This copy is
35
- * imported by the kit's own typecheck, where neither exists, so the two state
36
- * shapes are declared locally and `TEnv` defaults to `unknown` instead of `Env`
37
- * (Edge-Sonic's form). A local declaration shadows the ambient one inside this
38
- * file only, so a consumer's copy typechecks against their generated types
39
- * exactly as the original did.
40
- *
41
- * ### Usage in a consumer
42
- *
43
- * Copy this file to `<repo>/test/mocks/cloudflare-workers.ts` and alias the
44
- * specifier in the Vitest config — `defineUnitVitestConfig()` already does:
45
- *
46
- * ```jsonc
47
- * // wrangler.jsonc / vitest alias
48
- * "cloudflare:workers": "test/mocks/cloudflare-workers.ts"
49
- * ```
50
- *
51
- * Only what a test actually imports is exported. A symbol here that nothing
52
- * imports is not a safety net; it is a claim that something depends on it.
2
+ * @deprecated Moved to `@rexezuge/testing/cloudflare-workers`. This module stays
3
+ * as a re-export so `@rexezuge/tooling/test/mocks/cloudflare-workers` (the shim
4
+ * path consumers copied) keeps resolving; delete the shim and let the Vitest
5
+ * factories alias the kit's mock instead.
53
6
  */
54
- /**
55
- * The subset of `DurableObjectState` a Node test reaches.
56
- *
57
- * Declared structurally rather than imported: `id`, `storage` and `waitUntil` are
58
- * the three a hand-driven lifecycle touches, and nothing here needs the rest.
59
- */
60
- export interface DurableObjectState {
61
- readonly id: {
62
- toString(): string;
63
- readonly name?: string;
64
- };
65
- }
66
- /**
67
- * The subset of `ExecutionContext` a Node test reaches.
68
- *
69
- * `waitUntil` is present because a Workflow's `run()` is driven through it, and
70
- * `passThroughOnException` is absent on purpose — nothing in a Node suite wires a
71
- * request through it.
72
- */
73
- export interface ExecutionContext {
74
- waitUntil(promise: Promise<unknown>): void;
75
- }
76
- /**
77
- * The base class every Durable Object extends.
78
- *
79
- * `protected`, exactly as on the platform: a DO subclass reads `this.env` and
80
- * `this.ctx`, and nothing outside it may.
81
- */
82
- declare class DurableObject<TEnv = unknown> {
83
- protected ctx: DurableObjectState;
84
- protected env: TEnv;
85
- constructor(ctx: DurableObjectState, env: TEnv);
86
- }
87
- /**
88
- * The base class `dofs`' `Fs` extends. See the header: an empty body is the
89
- * whole point, and a missing class is a module-load failure.
90
- */
91
- declare class RpcTarget {
92
- }
93
- /**
94
- * The base class every Workflow extends.
95
- *
96
- * `ctx` is `ExecutionContext` rather than `unknown` (Mail-Meow/Mail-Otter's
97
- * form) because a Workflow's step code reads it; `void ctx` to silence the unused
98
- * warning would be a lie about which of the two a subclass uses.
99
- */
100
- declare class WorkflowEntrypoint<TEnv = unknown> {
101
- protected ctx: ExecutionContext;
102
- protected env: TEnv;
103
- constructor(ctx: ExecutionContext, env: TEnv);
104
- }
105
- export { DurableObject, RpcTarget, WorkflowEntrypoint };
7
+ export { DurableObject, RpcTarget, WorkflowEntrypoint } from '@rexezuge/testing/cloudflare-workers';
8
+ export type { DurableObjectState, ExecutionContext } from '@rexezuge/testing/cloudflare-workers';
106
9
  //# sourceMappingURL=cloudflare-workers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-workers.d.ts","sourceRoot":"","sources":["../../../src/test/mocks/cloudflare-workers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAEH;;;;;GAKG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,EAAE,EAAE;QAAE,QAAQ,IAAI,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC7D;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;CAC5C;AAED;;;;;GAKG;AACH,cAAM,aAAa,CAAC,IAAI,GAAG,OAAO;IAChC,SAAS,CAAC,GAAG,EAAE,kBAAkB,CAAC;IAClC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC;gBAER,GAAG,EAAE,kBAAkB,EAAE,GAAG,EAAE,IAAI;CAI/C;AAED;;;GAGG;AACH,cAAM,SAAS;CAAG;AAElB;;;;;;GAMG;AACH,cAAM,kBAAkB,CAAC,IAAI,GAAG,OAAO;IACrC,SAAS,CAAC,GAAG,EAAE,gBAAgB,CAAC;IAChC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC;gBAER,GAAG,EAAE,gBAAgB,EAAE,GAAG,EAAE,IAAI;CAI7C;AAED,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC"}
1
+ {"version":3,"file":"cloudflare-workers.d.ts","sourceRoot":"","sources":["../../../src/test/mocks/cloudflare-workers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAC;AACpG,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC"}
@@ -1 +1 @@
1
- var e=Object.defineProperty;var s=(c,t)=>e(c,"name",{value:t,configurable:!0});class n{static{s(this,"DurableObject")}ctx;env;constructor(t,r){this.ctx=t,this.env=r}}class o{static{s(this,"RpcTarget")}}class a{static{s(this,"WorkflowEntrypoint")}ctx;env;constructor(t,r){this.ctx=t,this.env=r}}export{n as DurableObject,o as RpcTarget,a as WorkflowEntrypoint};
1
+ import{DurableObject as t,RpcTarget as e,WorkflowEntrypoint as p}from"@rexezuge/testing/cloudflare-workers";export{t as DurableObject,e as RpcTarget,p as WorkflowEntrypoint};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/test/mocks/cloudflare-workers.ts"],
4
- "sourcesContent": ["/**\n * Stand-in for the `cloudflare:workers` module, which has no Node equivalent.\n *\n * Provenance: converged from the eight copies at `test/mocks/cloudflare-workers.ts`\n * (AWS-AccessBridge, CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Edge-Git,\n * Edge-Sonic, Mail-Meow, Mail-Otter). All eight are the same twenty lines; the\n * union is three base classes and the union exists because each repo discovered a\n * missing one the hard way.\n *\n * ### What each source contributes\n *\n * - **DurableObject** — every copy. Stores `ctx` and `env` so a real DO class can\n * be constructed and its lifecycle RPCs driven directly, without Miniflare.\n * - **`RpcTarget`** — Durable-DAV's, and the reason is load-bearing rather than\n * tidy: `dofs`' `Fs` class `extends RpcTarget`, so the module fails to evaluate\n * with *\"Class extends value undefined\"* when the base is missing. That is a\n * module-load error, not a test failure, so it surfaces as an unimportable\n * `dav-store` barrel and no unit test can reach `DavRepository`. Deliberately\n * empty: on the platform it marks which methods are callable across an RPC\n * boundary, and nothing in a Node suite calls those through RPC. An empty base\n * keeps the fake honest instead of pretending to implement dispatch.\n * - **`WorkflowEntrypoint`** — Edge-Git, Edge-Sonic, Mail-Meow, Mail-Otter. A\n * Workflow class extends it, so the mock must provide it or the module fails the\n * same way — a **startup** error, which therefore takes down every suite that\n * reaches `apps/background` for an unrelated reason. Edge-Sonic's is the shape\n * kept: it stores `ctx` as well as `env`, because the failure policy under test\n * in `runWorkflow` lives in a plain function precisely so it can be exercised\n * without workerd, and that policy reads the execution context.\n *\n * ### Why the ambient types are declared here rather than imported\n *\n * The source repos name `DurableObjectState`, `ExecutionContext` and `Env`\n * unqualified, which resolves only because `worker-configuration.d.ts` and\n * `@cloudflare/workers-types` are ambient inside a Wrangler project. This copy is\n * imported by the kit's own typecheck, where neither exists, so the two state\n * shapes are declared locally and `TEnv` defaults to `unknown` instead of `Env`\n * (Edge-Sonic's form). A local declaration shadows the ambient one inside this\n * file only, so a consumer's copy typechecks against their generated types\n * exactly as the original did.\n *\n * ### Usage in a consumer\n *\n * Copy this file to `<repo>/test/mocks/cloudflare-workers.ts` and alias the\n * specifier in the Vitest config — `defineUnitVitestConfig()` already does:\n *\n * ```jsonc\n * // wrangler.jsonc / vitest alias\n * \"cloudflare:workers\": \"test/mocks/cloudflare-workers.ts\"\n * ```\n *\n * Only what a test actually imports is exported. A symbol here that nothing\n * imports is not a safety net; it is a claim that something depends on it.\n */\n\n/**\n * The subset of `DurableObjectState` a Node test reaches.\n *\n * Declared structurally rather than imported: `id`, `storage` and `waitUntil` are\n * the three a hand-driven lifecycle touches, and nothing here needs the rest.\n */\nexport interface DurableObjectState {\n readonly id: { toString(): string; readonly name?: string };\n}\n\n/**\n * The subset of `ExecutionContext` a Node test reaches.\n *\n * `waitUntil` is present because a Workflow's `run()` is driven through it, and\n * `passThroughOnException` is absent on purpose — nothing in a Node suite wires a\n * request through it.\n */\nexport interface ExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/**\n * The base class every Durable Object extends.\n *\n * `protected`, exactly as on the platform: a DO subclass reads `this.env` and\n * `this.ctx`, and nothing outside it may.\n */\nclass DurableObject<TEnv = unknown> {\n protected ctx: DurableObjectState;\n protected env: TEnv;\n\n constructor(ctx: DurableObjectState, env: TEnv) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\n/**\n * The base class `dofs`' `Fs` extends. See the header: an empty body is the\n * whole point, and a missing class is a module-load failure.\n */\nclass RpcTarget {}\n\n/**\n * The base class every Workflow extends.\n *\n * `ctx` is `ExecutionContext` rather than `unknown` (Mail-Meow/Mail-Otter's\n * form) because a Workflow's step code reads it; `void ctx` to silence the unused\n * warning would be a lie about which of the two a subclass uses.\n */\nclass WorkflowEntrypoint<TEnv = unknown> {\n protected ctx: ExecutionContext;\n protected env: TEnv;\n\n constructor(ctx: ExecutionContext, env: TEnv) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\nexport { DurableObject, RpcTarget, WorkflowEntrypoint };\n"],
5
- "mappings": "+EAiFA,MAAMA,CAAa,CAjFnB,MAiFmB,CAAAC,EAAA,sBACP,IACA,IAEV,YAAYC,EAAyBC,EAAS,CAC5C,KAAK,IAAMD,EACX,KAAK,IAAMC,CACb,EAOF,MAAMC,CAAS,CA/Ff,MA+Fe,CAAAH,EAAA,mBASf,MAAMI,CAAkB,CAxGxB,MAwGwB,CAAAJ,EAAA,2BACZ,IACA,IAEV,YAAYC,EAAuBC,EAAS,CAC1C,KAAK,IAAMD,EACX,KAAK,IAAMC,CACb",
6
- "names": ["DurableObject", "__name", "ctx", "env", "RpcTarget", "WorkflowEntrypoint"]
4
+ "sourcesContent": ["/**\n * @deprecated Moved to `@rexezuge/testing/cloudflare-workers`. This module stays\n * as a re-export so `@rexezuge/tooling/test/mocks/cloudflare-workers` (the shim\n * path consumers copied) keeps resolving; delete the shim and let the Vitest\n * factories alias the kit's mock instead.\n */\nexport { DurableObject, RpcTarget, WorkflowEntrypoint } from '@rexezuge/testing/cloudflare-workers';\nexport type { DurableObjectState, ExecutionContext } from '@rexezuge/testing/cloudflare-workers';\n"],
5
+ "mappings": "AAMA,OAAS,iBAAAA,EAAe,aAAAC,EAAW,sBAAAC,MAA0B",
6
+ "names": ["DurableObject", "RpcTarget", "WorkflowEntrypoint"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,EAAgB,KAAK,MAAM,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/E;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,YAAY,CAAC,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAA;KAAE,KAAK,MAAM,GAAG,SAAS,CAAC;IAC9G;;;;;;;;OAQG;IACH,QAAQ,CAAC,EAAE,CAAC,EAAE,OAAO,CAAC;CACvB;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;;;;;;OASG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IAC7B;;;;;;;;;;;;;;;;OAgBG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CACnC;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,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,GAAG,GAAG,CAAC;CACnC;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC;;OAEG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,CAAC,CAAC;IACtD;;OAEG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,cAAc,CAAC;IACnC;;OAEG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACxB;AA4DD,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,GAAG;IAAE,WAAW,EAAE,MAAM,IAAI,CAAA;CAAE,CAoChG;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,oBAAyB,GAAG,cAAc,CActF"}
package/dist/vite.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/vite.ts"],
4
- "sourcesContent": ["/**\n * The SPA's Vite config.\n *\n * Provenance: converged from the `apps/web/vite.config.ts` of the eight repos\n * that build a Vite SPA. They are one file with three variables: the plugin list\n * (`@vitejs/plugin-react` + `@tailwindcss/vite`), the dev-server proxy target,\n * and the `spa-shell-embed` plugin that copies `dist/index.html` into\n * `apps/api/src/generated/spa-shell.ts`.\n *\n * Canonical decisions:\n *\n * 1. **The plugins are passed in, not imported.** The kit stays zero-dependency:\n * `react`, `@vitejs/plugin-react` and `@tailwindcss/vite` belong to the app\n * that uses them, and importing them here would make the tooling package\n * undownloadable for a consumer without a React SPA.\n * 2. **The `spa-shell-embed` hook stays per-repo, and is passed in.** It is the\n * one genuinely repo-specific piece: each repo names its own worker and its\n * own generated-module path. What the kit provides is the *contract* — see\n * `spaShellEmbedPlugin`, which is the converged body of all eight copies.\n * 3. **`server.proxy` is data, not code.** The paths differ per repo\n * (`/user` + `/rest` in Edge-Sonic, `/api` in CalDAV-Bridge, `/tracker` in\n * ChordDHT-Tracker) but the shape never does, so it is an option with a\n * default.\n * 4. **`build.emptyOutDir: true`** is the default, because a stale asset in\n * `dist/` is served as a live bundle — the same half-refreshed build\n * `scripts/verify-spa-shell.ts` rejects.\n *\n * The consumer's `apps/web/vite.config.ts` becomes a handful of lines — see the\n * README.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';\n\n/**\n * One dev-server proxy entry, as Vite's `server.proxy` accepts it.\n */\nexport interface ProxyEntry {\n readonly target: string;\n readonly changeOrigin?: boolean;\n readonly bypass?: (request: { headers: Record<string, string | string[] | undefined> }) => string | undefined;\n /**\n * Proxy WebSocket upgrades on this path.\n *\n * Vite's `server.proxy` needs `ws: true` for an entry that carries a\n * WebSocket, and the entry has no other way to say so: without it the\n * handshake is proxied as an ordinary request and the socket never opens.\n * A consumer with a live-update or realtime endpoint therefore could not\n * express its dev proxy through this table at all.\n */\n readonly ws?: boolean;\n}\n\n/**\n * Where the SPA's built `index.html` is copied to, and under what module name.\n */\nexport interface SpaShellTarget {\n /**\n * Path of the generated module, relative to the repository root.\n *\n * `apps/api/src/generated/spa-shell.ts` in every repo that embeds a shell; the\n * parameter exists because the path is the one thing that genuinely differs.\n */\n readonly path: string;\n /**\n * The repository root the path is resolved against, as a file URL or a path.\n *\n * Defaults to the directory the build runs in (`process.cwd()`), which is the\n * repo root when the build is `pnpm --filter @scope/web build`. Passed in by the\n * Vite config, not derived from `import.meta.url`: this plugin object is created\n * inside the kit's own module, so a URL relative to it points into\n * `node_modules/@rexezuge/tooling` and writes the shell somewhere no compiler\n * will ever look.\n */\n readonly root?: string | URL;\n /**\n * The built `index.html`, as a path or file URL.\n *\n * Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs\n * after the bundle is written, so this is the file the build just produced.\n *\n * A **relative** path resolves against {@link SpaShellTarget.root}, exactly as\n * {@link SpaShellTarget.path} does. It used to resolve against the process's\n * working directory, which under `pnpm --filter … build` is the *package*\n * directory rather than the repository root — so a consumer naming the file\n * relative to the root it had just been given wrote nowhere, and the plugin\n * reported \"dist/index.html not found, skipping\". That message is also what a\n * genuinely fresh checkout prints on its first build, so the two are\n * indistinguishable in the log, and the worker keeps serving the *previous*\n * shell: the SPA ships yesterday's JavaScript with nothing in the build log\n * to explain it.\n */\n readonly distIndex?: string | URL;\n}\n\n/**\n * What `defineWebViteConfig` accepts.\n */\nexport interface WebViteConfigOptions {\n /**\n * The SPA's plugins — `react()`, `tailwindcss()`, and anything else the app\n * needs. Applied before the spa-shell plugin so the shell is written after the\n * bundle exists.\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Dev-server proxy entries. Keyed by path prefix.\n */\n readonly proxy?: Readonly<Record<string, ProxyEntry>>;\n /**\n * Where the built shell is embedded. Omit to skip the embedding entirely.\n */\n readonly spaShell?: SpaShellTarget;\n /**\n * The build output directory.\n */\n readonly outDir?: string;\n /**\n * The directory this config is resolved from, as a file URL. Defaults to the\n * caller's location.\n */\n readonly root?: string;\n}\n\n/**\n * The `spa-shell-embed` plugin, converged from all eight copies.\n *\n * It exists because the API worker serves `SPA_HTML` from a module in its own\n * source tree, and both that module and `dist/` are gitignored — so a fresh\n * clone gets an empty stub from `postinstall` and every `GET /` returns a blank\n * page until someone runs a build. This plugin is what makes the build write the\n * real artefact, and `scripts/verify-spa-shell.ts` is what refuses to deploy\n * without it.\n *\n * Written as a factory rather than inlined so the exit conditions are in one\n * place: the `closeBundle` hook runs on every build, including the ones where\n * `dist/index.html` was never produced, and a plugin that throws there fails\n * builds that legitimately emit nothing.\n */\n/**\n * Normalise a path-or-URL option to a URL, so `new URL(...)` can be used on it.\n *\n * Small, and here because two options accept either form: a path is what a consumer\n * naturally writes in a config, and a URL is what `import.meta.url` hands them.\n * Accepting both is one line and saves a `fileURLToPath` at every call site.\n */\n/**\n * Normalise `string | URL` to a `URL`.\n *\n * A string that is **already a file URL** must be parsed, not converted:\n * `pathToFileURL('file:///srv/app')` treats its argument as a filesystem path\n * and produces `file:///<cwd>/file:/srv/app`, so every path built on top of it\n * silently resolves into a directory named after the scheme.\n *\n * The failure this prevented is not loud. `spaShellEmbedPlugin` then reports\n * \"dist/index.html not found, skipping\" — which is also what a genuinely fresh\n * checkout prints on its first build — and the consumer's worker keeps serving\n * the *previous* shell, so the SPA ships yesterday's JavaScript with no error\n * anywhere in the build log. Both `root` and `distIndex` are documented as\n * \"a file URL or a path\", and `new URL('.', import.meta.url).href` — the shape\n * every config file reaches for first — is a file-URL string, so this is the\n * path most callers take.\n */\nfunction toUrl(value: string | URL): URL {\n if (value instanceof URL) return value;\n return value.startsWith('file:') ? new URL(value) : pathToFileURL(value);\n}\n\n/**\n * The same, as a **directory** URL — with the trailing separator `new URL(rel, base)`\n * needs.\n *\n * `new URL('apps/api/x.ts', 'file:///repo')` resolves to `/apps/api/x.ts`, silently\n * dropping the base. The base has to end in a separator, and a path from\n * `process.cwd()` never does, so this is where the plugin would otherwise write the\n * shell into the filesystem root.\n */\nfunction toDirUrl(value: string | URL): URL {\n const url = toUrl(value);\n return url.href.endsWith('/') ? url : new URL(`${url.href}/`);\n}\n\nexport function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBundle: () => void } {\n return {\n name: 'spa-shell-embed',\n closeBundle() {\n // Resolved from the directory the build runs in, never from this module's own\n // URL: the plugin object is created here but executes in the consumer's Vite\n // process, and `new URL(path, import.meta.url)` would resolve against\n // `node_modules/@rexezuge/tooling`. `process.cwd()` is the repo root for\n // `pnpm --filter @scope/web build`, which is how every consumer runs it.\n const root = toDirUrl(target.root ?? process.cwd());\n const outputPath = fileURLToPath(new URL(target.path, root));\n // A relative `distIndex` resolves against the root, like `path` does —\n // not against the process's working directory, which under\n // `pnpm --filter … build` is the package directory.\n const indexPath =\n target.distIndex === undefined\n ? fileURLToPath(new URL('dist/index.html', root))\n : fileURLToPath(\n typeof target.distIndex === 'string' && !/^[a-z][a-z\\d+\\-.]*:/i.test(target.distIndex)\n ? new URL(target.distIndex, root)\n : toUrl(target.distIndex),\n );\n\n if (!existsSync(indexPath)) {\n console.warn('spa-shell-embed: dist/index.html not found, skipping');\n return;\n }\n\n const html = readFileSync(indexPath, 'utf8');\n const output = `// Auto-generated by Vite build plugin - DO NOT EDIT.\\nexport const SPA_HTML: string = ${JSON.stringify(html)};\\n`;\n\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n },\n };\n}\n\n/**\n * Build the SPA's Vite config.\n *\n * ```ts\n * // apps/web/vite.config.ts\n * import react from '@vitejs/plugin-react';\n * import { defineWebViteConfig, spaShellEmbedPlugin } from '@rexezuge/tooling/vite';\n *\n * export default defineWebViteConfig({\n * plugins: [react()],\n * proxy: { '/user': { target: 'http://localhost:8787', changeOrigin: true } },\n * spaShell: { path: '../../apps/api/src/generated/spa-shell.ts' },\n * });\n * ```\n */\nexport function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {\n const plugins: Plugin[] = [...(options.plugins ?? [])];\n if (options.spaShell !== undefined) {\n plugins.push(spaShellEmbedPlugin(options.spaShell));\n }\n\n return defineConfig({\n ...(plugins.length > 0 && { plugins }),\n ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),\n build: {\n outDir: options.outDir ?? 'dist',\n emptyOutDir: true,\n },\n });\n}\n"],
5
- "mappings": "+EA+BA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAOC,MAAU,YACjB,OAAS,iBAAAC,EAAe,iBAAAC,MAAqB,WAC7C,OAAS,gBAAAC,MAAsD,gBAmI/D,SAASC,EAAMC,EAAmB,CAChC,OAAIA,aAAiB,IAAYA,EAC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,QAAU,QAAa,CAAE,OAAQ,CAAE,MAAO,CAAE,GAAGA,EAAQ,KAAK,CAAE,CAAE,EAC5E,MAAO,CACL,OAAQA,EAAQ,QAAU,OAC1B,YAAa,IAEhB,CACH,CAdgBX,EAAAU,EAAA",
4
+ "sourcesContent": ["/**\n * The SPA's Vite config.\n *\n * Provenance: converged from the `apps/web/vite.config.ts` of the eight repos\n * that build a Vite SPA. They are one file with three variables: the plugin list\n * (`@vitejs/plugin-react` + `@tailwindcss/vite`), the dev-server proxy target,\n * and the `spa-shell-embed` plugin that copies `dist/index.html` into\n * `apps/api/src/generated/spa-shell.ts`.\n *\n * Canonical decisions:\n *\n * 1. **The plugins are passed in, not imported.** The kit stays zero-dependency:\n * `react`, `@vitejs/plugin-react` and `@tailwindcss/vite` belong to the app\n * that uses them, and importing them here would make the tooling package\n * undownloadable for a consumer without a React SPA.\n * 2. **The `spa-shell-embed` hook stays per-repo, and is passed in.** It is the\n * one genuinely repo-specific piece: each repo names its own worker and its\n * own generated-module path. What the kit provides is the *contract* — see\n * `spaShellEmbedPlugin`, which is the converged body of all eight copies.\n * 3. **`server.proxy` is data, not code.** The paths differ per repo\n * (`/user` + `/rest` in Edge-Sonic, `/api` in CalDAV-Bridge, `/tracker` in\n * ChordDHT-Tracker) but the shape never does, so it is an option with a\n * default.\n * 4. **`build.emptyOutDir: true`** is the default, because a stale asset in\n * `dist/` is served as a live bundle — the same half-refreshed build\n * `scripts/verify-spa-shell.ts` rejects.\n *\n * The consumer's `apps/web/vite.config.ts` becomes a handful of lines — see the\n * README.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';\n\n/**\n * One dev-server proxy entry, as Vite's `server.proxy` accepts it.\n */\nexport interface ProxyEntry {\n readonly target: string;\n readonly changeOrigin?: boolean;\n readonly bypass?: (request: { headers: Record<string, string | string[] | undefined> }) => string | undefined;\n /**\n * Proxy WebSocket upgrades on this path.\n *\n * Vite's `server.proxy` needs `ws: true` for an entry that carries a\n * WebSocket, and the entry has no other way to say so: without it the\n * handshake is proxied as an ordinary request and the socket never opens.\n * A consumer with a live-update or realtime endpoint therefore could not\n * express its dev proxy through this table at all.\n */\n readonly ws?: boolean;\n}\n\n/**\n * Where the SPA's built `index.html` is copied to, and under what module name.\n */\nexport interface SpaShellTarget {\n /**\n * Path of the generated module, relative to the repository root.\n *\n * `apps/api/src/generated/spa-shell.ts` in every repo that embeds a shell; the\n * parameter exists because the path is the one thing that genuinely differs.\n */\n readonly path: string;\n /**\n * The repository root the path is resolved against, as a file URL or a path.\n *\n * Defaults to the directory the build runs in (`process.cwd()`), which is the\n * repo root when the build is `pnpm --filter @scope/web build`. Passed in by the\n * Vite config, not derived from `import.meta.url`: this plugin object is created\n * inside the kit's own module, so a URL relative to it points into\n * `node_modules/@rexezuge/tooling` and writes the shell somewhere no compiler\n * will ever look.\n */\n readonly root?: string | URL;\n /**\n * The built `index.html`, as a path or file URL.\n *\n * Defaults to `dist/index.html` under the same root. Vite's `closeBundle` runs\n * after the bundle is written, so this is the file the build just produced.\n *\n * A **relative** path resolves against {@link SpaShellTarget.root}, exactly as\n * {@link SpaShellTarget.path} does. It used to resolve against the process's\n * working directory, which under `pnpm --filter … build` is the *package*\n * directory rather than the repository root — so a consumer naming the file\n * relative to the root it had just been given wrote nowhere, and the plugin\n * reported \"dist/index.html not found, skipping\". That message is also what a\n * genuinely fresh checkout prints on its first build, so the two are\n * indistinguishable in the log, and the worker keeps serving the *previous*\n * shell: the SPA ships yesterday's JavaScript with nothing in the build log\n * to explain it.\n */\n readonly distIndex?: string | URL;\n}\n\n/**\n * What `defineWebViteConfig` accepts.\n */\nexport interface WebViteConfigOptions {\n /**\n * The SPA's plugins — `react()`, `tailwindcss()`, and anything else the app\n * needs. Applied before the spa-shell plugin so the shell is written after the\n * bundle exists.\n */\n readonly plugins?: readonly Plugin[];\n /**\n * Dev-server proxy entries. Keyed by path prefix.\n */\n readonly proxy?: Readonly<Record<string, ProxyEntry>>;\n /**\n * Where the built shell is embedded. Omit to skip the embedding entirely.\n */\n readonly spaShell?: SpaShellTarget;\n /**\n * The build output directory.\n */\n readonly outDir?: string;\n /**\n * The directory this config is resolved from, as a file URL. Defaults to the\n * caller's location.\n */\n readonly root?: string;\n}\n\n/**\n * The `spa-shell-embed` plugin, converged from all eight copies.\n *\n * It exists because the API worker serves `SPA_HTML` from a module in its own\n * source tree, and both that module and `dist/` are gitignored — so a fresh\n * clone gets an empty stub from `postinstall` and every `GET /` returns a blank\n * page until someone runs a build. This plugin is what makes the build write the\n * real artefact, and `scripts/verify-spa-shell.ts` is what refuses to deploy\n * without it.\n *\n * Written as a factory rather than inlined so the exit conditions are in one\n * place: the `closeBundle` hook runs on every build, including the ones where\n * `dist/index.html` was never produced, and a plugin that throws there fails\n * builds that legitimately emit nothing.\n */\n/**\n * Normalise a path-or-URL option to a URL, so `new URL(...)` can be used on it.\n *\n * Small, and here because two options accept either form: a path is what a consumer\n * naturally writes in a config, and a URL is what `import.meta.url` hands them.\n * Accepting both is one line and saves a `fileURLToPath` at every call site.\n */\n/**\n * Normalise `string | URL` to a `URL`.\n *\n * A string that is **already a file URL** must be parsed, not converted:\n * `pathToFileURL('file:///srv/app')` treats its argument as a filesystem path\n * and produces `file:///<cwd>/file:/srv/app`, so every path built on top of it\n * silently resolves into a directory named after the scheme.\n *\n * The failure this prevented is not loud. `spaShellEmbedPlugin` then reports\n * \"dist/index.html not found, skipping\" — which is also what a genuinely fresh\n * checkout prints on its first build — and the consumer's worker keeps serving\n * the *previous* shell, so the SPA ships yesterday's JavaScript with no error\n * anywhere in the build log. Both `root` and `distIndex` are documented as\n * \"a file URL or a path\", and `new URL('.', import.meta.url).href` — the shape\n * every config file reaches for first — is a file-URL string, so this is the\n * path most callers take.\n */\nfunction toUrl(value: string | URL): URL {\n if (value instanceof URL) return value;\n return value.startsWith('file:') ? new URL(value) : pathToFileURL(value);\n}\n\n/**\n * The same, as a **directory** URL — with the trailing separator `new URL(rel, base)`\n * needs.\n *\n * `new URL('apps/api/x.ts', 'file:///repo')` resolves to `/apps/api/x.ts`, silently\n * dropping the base. The base has to end in a separator, and a path from\n * `process.cwd()` never does, so this is where the plugin would otherwise write the\n * shell into the filesystem root.\n */\nfunction toDirUrl(value: string | URL): URL {\n const url = toUrl(value);\n return url.href.endsWith('/') ? url : new URL(`${url.href}/`);\n}\n\nexport function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBundle: () => void } {\n return {\n name: 'spa-shell-embed',\n closeBundle() {\n // Resolved from the directory the build runs in, never from this module's own\n // URL: the plugin object is created here but executes in the consumer's Vite\n // process, and `new URL(path, import.meta.url)` would resolve against\n // `node_modules/@rexezuge/tooling`. `process.cwd()` is the repo root for\n // `pnpm --filter @scope/web build`, which is how every consumer runs it.\n const root = toDirUrl(target.root ?? process.cwd());\n const outputPath = fileURLToPath(new URL(target.path, root));\n // A relative `distIndex` resolves against the root, like `path` does —\n // not against the process's working directory, which under\n // `pnpm --filter … build` is the package directory.\n const indexPath =\n target.distIndex === undefined\n ? fileURLToPath(new URL('dist/index.html', root))\n : fileURLToPath(\n typeof target.distIndex === 'string' && !/^[a-z][a-z\\d+\\-.]*:/i.test(target.distIndex)\n ? new URL(target.distIndex, root)\n : toUrl(target.distIndex),\n );\n\n if (!existsSync(indexPath)) {\n // eslint-disable-next-line no-restricted-globals -- build-time Vite plugin, not worker code: there is no logger to inject\n console.warn('spa-shell-embed: dist/index.html not found, skipping');\n return;\n }\n\n const html = readFileSync(indexPath, 'utf8');\n const output = `// Auto-generated by Vite build plugin - DO NOT EDIT.\\nexport const SPA_HTML: string = ${JSON.stringify(html)};\\n`;\n\n mkdirSync(path.dirname(outputPath), { recursive: true });\n writeFileSync(outputPath, output);\n },\n };\n}\n\n/**\n * Build the SPA's Vite config.\n *\n * ```ts\n * // apps/web/vite.config.ts\n * import react from '@vitejs/plugin-react';\n * import { defineWebViteConfig, spaShellEmbedPlugin } from '@rexezuge/tooling/vite';\n *\n * export default defineWebViteConfig({\n * plugins: [react()],\n * proxy: { '/user': { target: 'http://localhost:8787', changeOrigin: true } },\n * spaShell: { path: '../../apps/api/src/generated/spa-shell.ts' },\n * });\n * ```\n */\nexport function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {\n const plugins: Plugin[] = [...(options.plugins ?? [])];\n if (options.spaShell !== undefined) {\n plugins.push(spaShellEmbedPlugin(options.spaShell));\n }\n\n return defineConfig({\n ...(plugins.length > 0 && { plugins }),\n ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),\n build: {\n outDir: options.outDir ?? 'dist',\n emptyOutDir: true,\n },\n });\n}\n"],
5
+ "mappings": "+EA+BA,OAAS,cAAAA,EAAY,aAAAC,EAAW,gBAAAC,EAAc,iBAAAC,MAAqB,UACnE,OAAOC,MAAU,YACjB,OAAS,iBAAAC,EAAe,iBAAAC,MAAqB,WAC7C,OAAS,gBAAAC,MAAsD,gBAmI/D,SAASC,EAAMC,EAAmB,CAChC,OAAIA,aAAiB,IAAYA,EAC1BA,EAAM,WAAW,OAAO,EAAI,IAAI,IAAIA,CAAK,EAAIH,EAAcG,CAAK,CACzE,CAHSC,EAAAF,EAAA,SAcT,SAASG,EAASF,EAAmB,CACnC,MAAMG,EAAMJ,EAAMC,CAAK,EACvB,OAAOG,EAAI,KAAK,SAAS,GAAG,EAAIA,EAAM,IAAI,IAAI,GAAGA,EAAI,IAAI,GAAG,CAC9D,CAHSF,EAAAC,EAAA,YAKH,SAAUE,EAAoBC,EAAsB,CACxD,MAAO,CACL,KAAM,kBACN,aAAW,CAMT,MAAMC,EAAOJ,EAASG,EAAO,MAAQ,QAAQ,IAAG,CAAE,EAC5CE,EAAaX,EAAc,IAAI,IAAIS,EAAO,KAAMC,CAAI,CAAC,EAIrDE,EACJH,EAAO,YAAc,OACjBT,EAAc,IAAI,IAAI,kBAAmBU,CAAI,CAAC,EAC9CV,EACE,OAAOS,EAAO,WAAc,UAAY,CAAC,uBAAuB,KAAKA,EAAO,SAAS,EACjF,IAAI,IAAIA,EAAO,UAAWC,CAAI,EAC9BP,EAAMM,EAAO,SAAS,CAAC,EAGnC,GAAI,CAACd,EAAWiB,CAAS,EAAG,CAE1B,QAAQ,KAAK,sDAAsD,EACnE,MACF,CAEA,MAAMC,EAAOhB,EAAae,EAAW,MAAM,EACrCE,EAAS;kCAA0F,KAAK,UAAUD,CAAI,CAAC;EAE7HjB,EAAUG,EAAK,QAAQY,CAAU,EAAG,CAAE,UAAW,EAAI,CAAE,EACvDb,EAAca,EAAYG,CAAM,CAClC,EAEJ,CApCgBT,EAAAG,EAAA,uBAqDV,SAAUO,EAAoBC,EAAgC,CAAA,EAAE,CACpE,MAAMC,EAAoB,CAAC,GAAID,EAAQ,SAAW,CAAA,CAAG,EACrD,OAAIA,EAAQ,WAAa,QACvBC,EAAQ,KAAKT,EAAoBQ,EAAQ,QAAQ,CAAC,EAG7Cd,EAAa,CAClB,GAAIe,EAAQ,OAAS,GAAK,CAAE,QAAAA,CAAO,EACnC,GAAID,EAAQ,QAAU,QAAa,CAAE,OAAQ,CAAE,MAAO,CAAE,GAAGA,EAAQ,KAAK,CAAE,CAAE,EAC5E,MAAO,CACL,OAAQA,EAAQ,QAAU,OAC1B,YAAa,IAEhB,CACH,CAdgBX,EAAAU,EAAA",
6
6
  "names": ["existsSync", "mkdirSync", "readFileSync", "writeFileSync", "path", "fileURLToPath", "pathToFileURL", "defineConfig", "toUrl", "value", "__name", "toDirUrl", "url", "spaShellEmbedPlugin", "target", "root", "outputPath", "indexPath", "html", "output", "defineWebViteConfig", "options", "plugins"]
7
7
  }