@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,228 @@
1
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { loadManifest, ManifestError, MANIFEST_FILENAME, manifestCoverageThresholds, parseManifest, validateManifest } from './manifest.ts';
7
+ import { manifestBrowserDirs, manifestHttpDirs, manifestLayerBans } from './eslint-manifest.ts';
8
+
9
+ const MINIMAL = { name: 'mail-meow', scope: '@mail-meow' };
10
+
11
+ const LAYERED = {
12
+ ...MINIMAL,
13
+ layers: [
14
+ { name: 'shared', dir: 'packages/shared', mayImport: [] },
15
+ { name: 'data', dir: 'packages/backend-data', mayImport: ['shared'] },
16
+ { name: 'services', dir: 'packages/backend-services', mayImport: ['shared', 'data'] },
17
+ { name: 'api', dir: 'apps/api', mayImport: ['services', 'shared'], typeOnly: ['data'], http: true, forbid: ['aws4fetch'] },
18
+ { name: 'web', dir: 'apps/web', mayImport: [], browser: true },
19
+ ],
20
+ };
21
+
22
+ function errorsOf(input: unknown): string[] {
23
+ const result = validateManifest(input);
24
+ return result.ok ? [] : result.errors;
25
+ }
26
+
27
+ describe('validateManifest', () => {
28
+ it('accepts the minimal manifest and a full one', () => {
29
+ expect(validateManifest(MINIMAL).ok).toBe(true);
30
+ const full = {
31
+ $schema: './node_modules/@rexezuge/tooling/schema/manifest.schema.json',
32
+ ...LAYERED,
33
+ features: {
34
+ d1: { binding: 'DB', database: 'mail-meow', migrationsDir: 'migrations' },
35
+ web: { pages: true, spaShell: false },
36
+ background: true,
37
+ backupD1: true,
38
+ durableObjects: ['MailboxDO'],
39
+ queues: ['mail'],
40
+ workflows: ['SyncWorkflow'],
41
+ email: true,
42
+ android: false,
43
+ },
44
+ quality: { coverage: { lines: 80, branches: 70, functions: 80, statements: 80 }, godFiles: { soft: 250, hard: 350 } },
45
+ extensions: { 'mail-meow': { anything: [1, 2, 3] } },
46
+ };
47
+ expect(errorsOf(full)).toEqual([]);
48
+ });
49
+
50
+ it('names the field of every problem, all at once', () => {
51
+ const errors = errorsOf({ name: '', scope: 'mail-meow', features: { d1: { binding: 'db' }, bogus: 1 }, extra: true });
52
+ expect(errors).toEqual(
53
+ expect.arrayContaining([
54
+ expect.stringContaining('name: must be a non-empty string'),
55
+ expect.stringContaining('scope: "mail-meow" is invalid'),
56
+ expect.stringContaining('features.d1.binding: "db" is invalid'),
57
+ expect.stringContaining('features.d1.database: must be a non-empty string'),
58
+ expect.stringContaining('features.bogus: unknown key'),
59
+ expect.stringContaining('manifest.extra: unknown key'),
60
+ ]),
61
+ );
62
+ });
63
+
64
+ it('rejects a non-object manifest', () => {
65
+ expect(errorsOf([])).toEqual(['manifest: must be an object']);
66
+ expect(errorsOf(null)).toEqual(['manifest: must be an object']);
67
+ });
68
+
69
+ it('only lets god-file limits be lowered', () => {
70
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 350, hard: 400 } } })).toEqual([
71
+ 'quality.godFiles.soft: 350 is above the family limit 300: god-file limits may only be lowered',
72
+ ]);
73
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 300, hard: 500 } } })[0]).toContain('may only be lowered');
74
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 300, hard: 400 } } })).toEqual([]);
75
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 200, hard: 100 } } })).toEqual([
76
+ 'quality.godFiles.soft: must not exceed quality.godFiles.hard',
77
+ ]);
78
+ expect(errorsOf({ ...MINIMAL, quality: { godFiles: { soft: 0.5, hard: 'x' } } })).toHaveLength(2);
79
+ });
80
+
81
+ it('checks coverage figures', () => {
82
+ expect(errorsOf({ ...MINIMAL, quality: { coverage: { lines: 101, branches: 1, functions: 1, statements: 1 } } })).toEqual([
83
+ 'quality.coverage.lines: must be a number from 0 to 100',
84
+ ]);
85
+ expect(errorsOf({ ...MINIMAL, quality: { coverage: { lines: 1 } } })).toHaveLength(3);
86
+ });
87
+
88
+ it('checks layers: names, dirs, references and the type-only overlap', () => {
89
+ const errors = errorsOf({
90
+ ...MINIMAL,
91
+ layers: [
92
+ { name: 'a', dir: 'packages/a', mayImport: ['ghost'], typeOnly: ['b'] },
93
+ { name: 'a', dir: '../b', mayImport: ['b'], typeOnly: ['b'] },
94
+ { name: 'B', dir: 'packages/*', mayImport: 'nope' },
95
+ 'text',
96
+ ],
97
+ });
98
+ expect(errors).toEqual(
99
+ expect.arrayContaining([
100
+ expect.stringContaining('layers[0].mayImport: unknown layer "ghost"'),
101
+ expect.stringContaining('layers[1].name: duplicate layer name "a"'),
102
+ expect.stringContaining('layers[1].dir: "../b" must be a repo-relative directory'),
103
+ expect.stringContaining('layers[2].dir: "packages/*" must be a repo-relative directory'),
104
+ expect.stringContaining('layers[2].mayImport: must be an array'),
105
+ expect.stringContaining('layers[3]: must be an object'),
106
+ ]),
107
+ );
108
+ expect(errorsOf({ ...MINIMAL, layers: {} })).toEqual(['layers: must be an array of layers']);
109
+ expect(
110
+ errorsOf({
111
+ ...MINIMAL,
112
+ layers: [
113
+ { name: 'a', dir: 'a', mayImport: [], http: 'yes' },
114
+ { name: 'b', dir: 'a', mayImport: ['a'], typeOnly: ['a'] },
115
+ ],
116
+ }),
117
+ ).toEqual(
118
+ expect.arrayContaining([
119
+ expect.stringContaining('layers[0].http: must be a boolean'),
120
+ expect.stringContaining('duplicate layer dir "a"'),
121
+ expect.stringContaining('already in mayImport'),
122
+ ]),
123
+ );
124
+ });
125
+
126
+ it('keeps extensions namespaced objects', () => {
127
+ expect(errorsOf({ ...MINIMAL, extensions: { Bad_Key: {}, ok: 3 } })).toEqual([
128
+ 'extensions.Bad_Key: namespace must be lower-case letters, digits and hyphens',
129
+ 'extensions.ok: must be an object (extensions are namespaced: one object per owner)',
130
+ ]);
131
+ expect(errorsOf({ ...MINIMAL, extensions: [] })).toEqual(['extensions: must be an object']);
132
+ });
133
+
134
+ it('checks feature value types', () => {
135
+ const errors = errorsOf({
136
+ ...MINIMAL,
137
+ features: { web: { pages: 1, spaShell: true, x: 1 }, background: 'yes', queues: [1], d1: [], durableObjects: 'X' },
138
+ });
139
+ expect(errors).toHaveLength(6);
140
+ });
141
+ });
142
+
143
+ describe('parseManifest and loadManifest', () => {
144
+ const dirs: string[] = [];
145
+ afterEach(() => {
146
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
147
+ });
148
+ const repoWith = (text?: string): string => {
149
+ const dir = mkdtempSync(path.join(tmpdir(), 'manifest-'));
150
+ dirs.push(dir);
151
+ if (text !== undefined) writeFileSync(path.join(dir, MANIFEST_FILENAME), text);
152
+ return dir;
153
+ };
154
+
155
+ it('parses JSONC with comments and trailing commas', () => {
156
+ const manifest = parseManifest('{\n // the repo\n "name": "x", "scope": "@x",\n}');
157
+ expect(manifest.scope).toBe('@x');
158
+ });
159
+
160
+ it('reports syntax errors and validation errors as ManifestError', () => {
161
+ expect(() => parseManifest('{ "name": ', 'm.jsonc')).toThrow(/m\.jsonc is not a valid family manifest[\s\S]*syntax error/);
162
+ const failure = (() => {
163
+ try {
164
+ parseManifest('{"name":"x"}');
165
+ } catch (error) {
166
+ return error as ManifestError;
167
+ }
168
+ return null;
169
+ })();
170
+ expect(failure).toBeInstanceOf(ManifestError);
171
+ expect(failure?.errors).toEqual(['scope: must be a non-empty string']);
172
+ });
173
+
174
+ it('loads null when absent, the manifest when present, and throws when invalid', () => {
175
+ expect(loadManifest(repoWith())).toBeNull();
176
+ expect(loadManifest(repoWith('{"name":"x","scope":"@x"}'))?.name).toBe('x');
177
+ expect(() => loadManifest(repoWith('{"name":"x"}'))).toThrow(ManifestError);
178
+ });
179
+
180
+ it('resolves coverage thresholds from a path or a file URL root', () => {
181
+ const dir = repoWith('{"name":"x","scope":"@x","quality":{"coverage":{"lines":1,"branches":2,"functions":3,"statements":4}}}');
182
+ const expected = { lines: 1, branches: 2, functions: 3, statements: 4 };
183
+ expect(manifestCoverageThresholds(dir)).toEqual(expected);
184
+ expect(manifestCoverageThresholds(pathToFileURL(`${dir}/`).href)).toEqual(expected);
185
+ expect(manifestCoverageThresholds(repoWith('{"name":"x","scope":"@x"}'))).toBeUndefined();
186
+ });
187
+ });
188
+
189
+ describe('the shipped JSON Schema', () => {
190
+ const schema = JSON.parse(readFileSync(new URL('../schema/manifest.schema.json', import.meta.url), 'utf8')) as {
191
+ properties: Record<string, { properties?: Record<string, unknown>; items?: { properties: Record<string, unknown> } }>;
192
+ };
193
+
194
+ it('names exactly the keys the validator accepts', () => {
195
+ const validator = (input: unknown): string[] => errorsOf(input).filter((line) => line.includes('unknown key'));
196
+ for (const key of Object.keys(schema.properties)) expect(validator({ ...MINIMAL, [key]: undefined })).toEqual([]);
197
+ expect(validator({ ...MINIMAL, nope: 1 })).toHaveLength(1);
198
+ const unknownIn = (section: string, keys: string[]): string[] =>
199
+ validator({ ...MINIMAL, [section]: Object.fromEntries(keys.map((key) => [key, undefined])) });
200
+ expect(unknownIn('features', Object.keys(schema.properties['features']?.properties ?? {}))).toEqual([]);
201
+ expect(unknownIn('quality', Object.keys(schema.properties['quality']?.properties ?? {}))).toEqual([]);
202
+ const layerKeys = Object.keys(schema.properties['layers']?.items?.properties ?? {});
203
+ expect(validator({ ...MINIMAL, layers: [Object.fromEntries(layerKeys.map((key) => [key, undefined]))] })).toEqual([]);
204
+ });
205
+ });
206
+
207
+ describe('manifest layers as lint boundaries', () => {
208
+ it('derives bans from what each layer may not import', () => {
209
+ const bans = manifestLayerBans(LAYERED as never);
210
+ const of = (dir: string) => bans.filter((ban) => ban.dir === dir);
211
+ expect(of('packages/shared')[0]?.ban).toEqual(['@mail-meow/*']);
212
+ expect(of('packages/backend-data')[0]?.ban).toEqual(['@mail-meow/backend-services', '@mail-meow/api', '@mail-meow/web']);
213
+ const api = of('apps/api');
214
+ expect(api[0]?.ban).toEqual(['@mail-meow/web']);
215
+ expect(api.find((ban) => ban.allowTypeImports === true)?.ban).toEqual(['@mail-meow/backend-data']);
216
+ expect(api.find((ban) => ban.ban.includes('aws4fetch'))?.message).toBe('api may not import this package');
217
+ expect(of('apps/web')[0]?.ban).toEqual(['@mail-meow/*']);
218
+ });
219
+
220
+ it('lists http and browser dirs', () => {
221
+ expect(manifestHttpDirs(LAYERED as never)).toEqual(['apps/api']);
222
+ expect(manifestHttpDirs(null)).toEqual([]);
223
+ expect(manifestBrowserDirs(null)).toEqual(['apps/web']);
224
+ expect(manifestBrowserDirs(LAYERED as never)).toEqual(['apps/web']);
225
+ expect(manifestBrowserDirs(MINIMAL as never)).toEqual([]);
226
+ expect(manifestBrowserDirs({ ...MINIMAL, features: { web: { pages: true, spaShell: true } } })).toEqual(['apps/web']);
227
+ });
228
+ });
@@ -0,0 +1,194 @@
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
+
20
+ import { existsSync, readFileSync } from 'node:fs';
21
+ import path from 'node:path';
22
+ import { fileURLToPath } from 'node:url';
23
+ import { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser';
24
+ import type { ParseError } from 'jsonc-parser';
25
+ import { validateManifest } from './manifest-validate.ts';
26
+
27
+ export { FAMILY_GOD_FILE_LIMITS, validateManifest } from './manifest-validate.ts';
28
+
29
+ /**
30
+ The file name, resolved against a repo root.
31
+ */
32
+ export const MANIFEST_FILENAME = '.rexezuge.jsonc';
33
+
34
+ export interface ManifestD1 {
35
+ readonly binding: string;
36
+ readonly database: string;
37
+ readonly migrationsDir?: string;
38
+ }
39
+
40
+ export interface ManifestWeb {
41
+ /**
42
+ The SPA is served by Cloudflare Pages.
43
+ */
44
+ readonly pages: boolean;
45
+ /**
46
+ The SPA shell is embedded into the worker (`spa-shell` scripts).
47
+ */
48
+ readonly spaShell: boolean;
49
+ }
50
+
51
+ export interface ManifestFeatures {
52
+ readonly d1?: ManifestD1;
53
+ readonly web?: ManifestWeb;
54
+ readonly background?: boolean;
55
+ readonly backupD1?: boolean;
56
+ /**
57
+ Durable Object class names.
58
+ */
59
+ readonly durableObjects?: readonly string[];
60
+ /**
61
+ Queue names.
62
+ */
63
+ readonly queues?: readonly string[];
64
+ /**
65
+ Workflow class names.
66
+ */
67
+ readonly workflows?: readonly string[];
68
+ readonly email?: boolean;
69
+ readonly android?: boolean;
70
+ }
71
+
72
+ /**
73
+ * One dependency layer: a directory, and the other layers it may import.
74
+ *
75
+ * Everything not named in `mayImport` / `typeOnly` is banned, by package name
76
+ * (`<scope>/<basename of dir>`, or `package`). `mayImport: []` isolates the layer
77
+ * from the whole scope (`<scope>/*`).
78
+ */
79
+ export interface ManifestLayer {
80
+ readonly name: string;
81
+ /**
82
+ Repo-relative directory, no globs: `packages/backend-data`.
83
+ */
84
+ readonly dir: string;
85
+ /**
86
+ Package suffix when it is not the directory's basename.
87
+ */
88
+ readonly package?: string;
89
+ /**
90
+ Names of layers this layer may import.
91
+ */
92
+ readonly mayImport: readonly string[];
93
+ /**
94
+ Names of layers importable as `import type` only.
95
+ */
96
+ readonly typeOnly?: readonly string[];
97
+ /**
98
+ Extra external specifiers this layer may not import, e.g. `aws4fetch`.
99
+ */
100
+ readonly forbid?: readonly string[];
101
+ /**
102
+ Message for `forbid`; defaults to a generic one.
103
+ */
104
+ readonly forbidMessage?: string;
105
+ /**
106
+ May import `hono`/`chanfana` (and hand-build error envelopes).
107
+ */
108
+ readonly http?: boolean;
109
+ /**
110
+ Browser code: may use `console`, and lints with browser globals.
111
+ */
112
+ readonly browser?: boolean;
113
+ }
114
+
115
+ export interface ManifestCoverage {
116
+ readonly lines: number;
117
+ readonly branches: number;
118
+ readonly functions: number;
119
+ readonly statements: number;
120
+ }
121
+
122
+ export interface ManifestQuality {
123
+ readonly coverage?: ManifestCoverage;
124
+ readonly godFiles?: { readonly soft: number; readonly hard: number };
125
+ }
126
+
127
+ export interface FamilyManifest {
128
+ readonly $schema?: string;
129
+ readonly name: string;
130
+ /**
131
+ npm scope with the `@`, e.g. `@mail-meow`.
132
+ */
133
+ readonly scope: string;
134
+ readonly features?: ManifestFeatures;
135
+ readonly layers?: readonly ManifestLayer[];
136
+ readonly quality?: ManifestQuality;
137
+ /**
138
+ Repo-specific settings, namespaced by key. Never read by the kit.
139
+ */
140
+ readonly extensions?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;
141
+ }
142
+
143
+ export type ManifestValidation =
144
+ { readonly ok: true; readonly manifest: FamilyManifest } | { readonly ok: false; readonly errors: string[] };
145
+
146
+ /**
147
+ Thrown by {@link loadManifest} and {@link parseManifest}; `errors` has one line per problem.
148
+ */
149
+ export class ManifestError extends Error {
150
+ readonly errors: readonly string[];
151
+ constructor(source: string, errors: readonly string[]) {
152
+ super(`${source} is not a valid family manifest:\n${errors.map((line) => ` - ${line}`).join('\n')}`);
153
+ this.name = 'ManifestError';
154
+ this.errors = errors;
155
+ }
156
+ }
157
+
158
+ /**
159
+ Parse JSONC text and validate it. Throws {@link ManifestError}.
160
+ */
161
+ export function parseManifest(text: string, source: string = MANIFEST_FILENAME): FamilyManifest {
162
+ const syntax: ParseError[] = [];
163
+ const value: unknown = parseJsonc(text, syntax, { allowTrailingComma: true });
164
+ if (syntax.length > 0) {
165
+ throw new ManifestError(
166
+ source,
167
+ syntax.map((error) => `syntax error at offset ${error.offset}: ${printParseErrorCode(error.error)}`),
168
+ );
169
+ }
170
+ const result = validateManifest(value);
171
+ if (!result.ok) throw new ManifestError(source, result.errors);
172
+ return result.manifest;
173
+ }
174
+
175
+ /**
176
+ * Load `<root>/.rexezuge.jsonc`. Returns `null` when the file is absent (the
177
+ * repo has not adopted a manifest) and throws {@link ManifestError} when it is
178
+ * present but invalid: a broken manifest must fail the gate, not fall back.
179
+ */
180
+ export function loadManifest(root: string): FamilyManifest | null {
181
+ const file = path.join(root, MANIFEST_FILENAME);
182
+ if (!existsSync(file)) return null;
183
+ return parseManifest(readFileSync(file, 'utf8'), file);
184
+ }
185
+
186
+ /**
187
+ * The manifest's coverage floor for a vitest config, or `undefined` when the
188
+ * repo has no manifest or declares none. `root` is what the factories take: a
189
+ * directory path or a `file:` URL (`new URL('.', import.meta.url).href`).
190
+ */
191
+ export function manifestCoverageThresholds(root: string): ManifestCoverage | undefined {
192
+ const dir = root.startsWith('file:') ? fileURLToPath(root) : root;
193
+ return loadManifest(dir)?.quality?.coverage;
194
+ }
@@ -0,0 +1,63 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { parse } from 'jsonc-parser';
3
+ import { describe, expect, it } from 'vitest';
4
+
5
+ const here = (path: string): URL => new URL(`../${path}`, import.meta.url);
6
+ const json = <T>(path: string): T => parse(readFileSync(here(path), 'utf8')) as T;
7
+
8
+ interface TsConfig {
9
+ extends?: string;
10
+ compilerOptions: Record<string, unknown>;
11
+ }
12
+
13
+ describe('tsconfig presets', () => {
14
+ const base = json<TsConfig>('presets/tsconfig/base.json').compilerOptions;
15
+ const worker = json<TsConfig>('presets/tsconfig/worker.json');
16
+ const web = json<TsConfig>('presets/tsconfig/web.json');
17
+
18
+ it('base carries the options the family copies shared', () => {
19
+ expect(base).toMatchObject({
20
+ target: 'ES2022',
21
+ module: 'ES2022',
22
+ moduleResolution: 'Bundler',
23
+ strict: true,
24
+ isolatedModules: true,
25
+ noEmit: true,
26
+ skipLibCheck: true,
27
+ resolveJsonModule: true,
28
+ });
29
+ });
30
+
31
+ it('worker and web extend base; web adds the DOM libs and the JSX transform', () => {
32
+ expect(worker.extends).toBe('./base.json');
33
+ expect(web.extends).toBe('./base.json');
34
+ expect(worker.compilerOptions['lib']).toEqual(['ES2022', 'DOM']);
35
+ expect(web.compilerOptions).toMatchObject({ jsx: 'react-jsx', target: 'ES2020', lib: ['ES2020', 'DOM', 'DOM.Iterable'] });
36
+ });
37
+ });
38
+
39
+ describe('prettier preset', () => {
40
+ it('matches the .prettierrc the family repos carried', async () => {
41
+ const { default: config } = (await import('../presets/prettier.mjs')) as { default: unknown };
42
+ expect(config).toEqual({ printWidth: 140, singleQuote: true, semi: true, useTabs: false });
43
+ });
44
+ });
45
+
46
+ describe('package exports', () => {
47
+ const pkg = json<{ exports: Record<string, unknown>; files: string[] }>('package.json');
48
+
49
+ it('maps every preset and the schema to a file that ships', () => {
50
+ for (const key of ['./tsconfig/base.json', './tsconfig/worker.json', './tsconfig/web.json', './manifest.schema.json', './prettier']) {
51
+ const target = pkg.exports[key];
52
+ const file = typeof target === 'string' ? target : (target as { default: string }).default;
53
+ expect(existsSync(here(file)), `${key} -> ${file}`).toBe(true);
54
+ expect(pkg.files).toContain(file.split('/', 2)[1]);
55
+ }
56
+ });
57
+
58
+ it('lists the explicit entries before the `./*` wildcard that would shadow them', () => {
59
+ const keys = Object.keys(pkg.exports);
60
+ expect(keys.indexOf('./tsconfig/base.json')).toBeLessThan(keys.indexOf('./*'));
61
+ expect(keys.indexOf('./prettier')).toBeLessThan(keys.indexOf('./*'));
62
+ });
63
+ });
@@ -51,6 +51,7 @@ import path from 'node:path';
51
51
  import { fail } from './lib/github-actions.ts';
52
52
  import { isEntrypoint } from './lib/entrypoint.ts';
53
53
  import { isSet, parseFlags, splitPositional, valueOf } from './lib/cli-args.ts';
54
+ import { loadManifest } from '../manifest.ts';
54
55
 
55
56
  /**
56
57
  * A file past a size the guard reports on.
@@ -329,6 +330,8 @@ export function checkGodFilesCli(argv: readonly string[] = process.argv.slice(2)
329
330
  const report = checkGodFiles({
330
331
  root,
331
332
  allowlist: readAllowlist(allowlistPath),
333
+ // A manifest may only lower the family limits (the validator refuses more).
334
+ ...loadManifest(root)?.quality?.godFiles,
332
335
  failOnHard: isSet(flags, 'fail-on-hard'),
333
336
  });
334
337
  console.log(report.reported);
@@ -1,115 +1,8 @@
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
- /**
56
- * The subset of `DurableObjectState` a Node test reaches.
57
- *
58
- * Declared structurally rather than imported: `id`, `storage` and `waitUntil` are
59
- * the three a hand-driven lifecycle touches, and nothing here needs the rest.
60
- */
61
- export interface DurableObjectState {
62
- readonly id: { toString(): string; readonly name?: string };
63
- }
64
-
65
- /**
66
- * The subset of `ExecutionContext` a Node test reaches.
67
- *
68
- * `waitUntil` is present because a Workflow's `run()` is driven through it, and
69
- * `passThroughOnException` is absent on purpose — nothing in a Node suite wires a
70
- * request through it.
71
- */
72
- export interface ExecutionContext {
73
- waitUntil(promise: Promise<unknown>): void;
74
- }
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
- class DurableObject<TEnv = unknown> {
83
- protected ctx: DurableObjectState;
84
- protected env: TEnv;
85
-
86
- constructor(ctx: DurableObjectState, env: TEnv) {
87
- this.ctx = ctx;
88
- this.env = env;
89
- }
90
- }
91
-
92
- /**
93
- * The base class `dofs`' `Fs` extends. See the header: an empty body is the
94
- * whole point, and a missing class is a module-load failure.
95
- */
96
- class RpcTarget {}
97
-
98
- /**
99
- * The base class every Workflow extends.
100
- *
101
- * `ctx` is `ExecutionContext` rather than `unknown` (Mail-Meow/Mail-Otter's
102
- * form) because a Workflow's step code reads it; `void ctx` to silence the unused
103
- * warning would be a lie about which of the two a subclass uses.
104
- */
105
- class WorkflowEntrypoint<TEnv = unknown> {
106
- protected ctx: ExecutionContext;
107
- protected env: TEnv;
108
-
109
- constructor(ctx: ExecutionContext, env: TEnv) {
110
- this.ctx = ctx;
111
- this.env = env;
112
- }
113
- }
114
-
115
- export { DurableObject, RpcTarget, WorkflowEntrypoint };
7
+ export { DurableObject, RpcTarget, WorkflowEntrypoint } from '@rexezuge/testing/cloudflare-workers';
8
+ export type { DurableObjectState, ExecutionContext } from '@rexezuge/testing/cloudflare-workers';
package/src/vite.ts CHANGED
@@ -206,6 +206,7 @@ export function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBun
206
206
  );
207
207
 
208
208
  if (!existsSync(indexPath)) {
209
+ // eslint-disable-next-line no-restricted-globals -- build-time Vite plugin, not worker code: there is no logger to inject
209
210
  console.warn('spa-shell-embed: dist/index.html not found, skipping');
210
211
  return;
211
212
  }
@@ -1,3 +1,7 @@
1
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
1
5
  import { describe, expect, it } from 'vitest';
2
6
  import { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';
3
7
 
@@ -31,6 +35,25 @@ describe('workspaceAliases', () => {
31
35
  expect(aliases.some((alias) => alias.find instanceof RegExp && alias.find.source === String.raw`^~\/`)).toBe(true);
32
36
  });
33
37
 
38
+ it('falls back to the kit mock when the repo has none, and prefers the repo copy when it has one', () => {
39
+ const replacement = (root: string): string | undefined =>
40
+ workspaceAliases({ scope: '@fixture', root, packages: [], mocks: ['workers', 'sockets'] }).find(
41
+ (alias) => alias.find === 'cloudflare:workers',
42
+ )?.replacement;
43
+ const bare = mkdtempSync(path.join(tmpdir(), 'aliases-bare-'));
44
+ expect(replacement(pathToFileURL(`${bare}/`).href)).toMatch(/testing[/\\]dist[/\\]cloudflare-workers\.js$/);
45
+ rmSync(bare, { recursive: true, force: true });
46
+ const dir = mkdtempSync(path.join(tmpdir(), 'aliases-'));
47
+ mkdirSync(path.join(dir, 'test/mocks'), { recursive: true });
48
+ writeFileSync(path.join(dir, 'test/mocks/cloudflare-workers.ts'), 'export {};');
49
+ expect(replacement(pathToFileURL(`${dir}/`).href)).toBe(path.join(dir, 'test/mocks/cloudflare-workers.ts'));
50
+ rmSync(dir, { recursive: true, force: true });
51
+ const sockets = workspaceAliases({ scope: '@fixture', root: ROOT, packages: [], mocks: ['sockets'] }).find(
52
+ (alias) => alias.find === 'cloudflare:sockets',
53
+ );
54
+ expect(sockets?.replacement).toMatch(/test[/\\]mocks[/\\]cloudflare-sockets\.ts$/);
55
+ });
56
+
34
57
  it('lets a repo narrow the package and mock sets', () => {
35
58
  const aliases = workspaceAliases({ scope: '@fixture', root: ROOT, packages: ['shared'], mocks: ['workers'] });
36
59
  expect(finds(aliases)).toContain('@fixture/shared');