@rexezuge/tooling 1.12.0 → 1.14.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 (130) hide show
  1. package/README.md +149 -18
  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-options.d.ts +54 -0
  7. package/dist/eslint-options.d.ts.map +1 -0
  8. package/dist/eslint-options.js +0 -0
  9. package/dist/eslint-options.js.map +7 -0
  10. package/dist/eslint-strict.d.ts +45 -0
  11. package/dist/eslint-strict.d.ts.map +1 -0
  12. package/dist/eslint-strict.js +1 -0
  13. package/dist/eslint-strict.js.map +7 -0
  14. package/dist/eslint.d.ts +2 -36
  15. package/dist/eslint.d.ts.map +1 -1
  16. package/dist/eslint.js +1 -1
  17. package/dist/eslint.js.map +3 -3
  18. package/dist/index.d.ts +5 -2
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +3 -3
  22. package/dist/manifest-validate.d.ts +14 -0
  23. package/dist/manifest-validate.d.ts.map +1 -0
  24. package/dist/manifest-validate.js +1 -0
  25. package/dist/manifest-validate.js.map +7 -0
  26. package/dist/manifest.d.ts +159 -0
  27. package/dist/manifest.d.ts.map +1 -0
  28. package/dist/manifest.js +3 -0
  29. package/dist/manifest.js.map +7 -0
  30. package/dist/pages-proxy.d.ts +2 -0
  31. package/dist/pages-proxy.d.ts.map +1 -0
  32. package/dist/pages-proxy.js +1 -0
  33. package/dist/pages-proxy.js.map +7 -0
  34. package/dist/plugin-option.d.ts +15 -0
  35. package/dist/plugin-option.d.ts.map +1 -0
  36. package/dist/plugin-option.js +1 -0
  37. package/dist/plugin-option.js.map +7 -0
  38. package/dist/scripts/check-god-files.d.ts.map +1 -1
  39. package/dist/scripts/check-god-files.js +2 -2
  40. package/dist/scripts/check-god-files.js.map +3 -3
  41. package/dist/scripts/ensure-spa-shell-stub.d.ts +4 -2
  42. package/dist/scripts/ensure-spa-shell-stub.d.ts.map +1 -1
  43. package/dist/scripts/ensure-spa-shell-stub.js +1 -2
  44. package/dist/scripts/ensure-spa-shell-stub.js.map +3 -3
  45. package/dist/scripts/init-secrets.d.ts +1 -2
  46. package/dist/scripts/init-secrets.d.ts.map +1 -1
  47. package/dist/scripts/init-secrets.js +2 -3
  48. package/dist/scripts/init-secrets.js.map +3 -3
  49. package/dist/scripts/migrations-lock.d.ts +6 -2
  50. package/dist/scripts/migrations-lock.d.ts.map +1 -1
  51. package/dist/scripts/migrations-lock.js +1 -2
  52. package/dist/scripts/migrations-lock.js.map +3 -3
  53. package/dist/scripts/prepare-wrangler-config.d.ts +6 -2
  54. package/dist/scripts/prepare-wrangler-config.d.ts.map +1 -1
  55. package/dist/scripts/prepare-wrangler-config.js +1 -2
  56. package/dist/scripts/prepare-wrangler-config.js.map +3 -3
  57. package/dist/scripts/validate-locales.d.ts +20 -2
  58. package/dist/scripts/validate-locales.d.ts.map +1 -1
  59. package/dist/scripts/validate-locales.js +5 -5
  60. package/dist/scripts/validate-locales.js.map +3 -3
  61. package/dist/scripts/verify-spa-shell.d.ts +7 -2
  62. package/dist/scripts/verify-spa-shell.d.ts.map +1 -1
  63. package/dist/scripts/verify-spa-shell.js +1 -2
  64. package/dist/scripts/verify-spa-shell.js.map +3 -3
  65. package/dist/test/mocks/cloudflare-workers.d.ts +6 -103
  66. package/dist/test/mocks/cloudflare-workers.d.ts.map +1 -1
  67. package/dist/test/mocks/cloudflare-workers.js +1 -1
  68. package/dist/test/mocks/cloudflare-workers.js.map +3 -3
  69. package/dist/vite.d.ts +2 -1
  70. package/dist/vite.d.ts.map +1 -1
  71. package/dist/vite.js +3 -3
  72. package/dist/vite.js.map +3 -3
  73. package/dist/vitest-aliases.d.ts +3 -0
  74. package/dist/vitest-aliases.d.ts.map +1 -1
  75. package/dist/vitest-aliases.js +1 -1
  76. package/dist/vitest-aliases.js.map +3 -3
  77. package/dist/vitest-integration.d.ts +3 -2
  78. package/dist/vitest-integration.d.ts.map +1 -1
  79. package/dist/vitest-integration.js +1 -1
  80. package/dist/vitest-integration.js.map +3 -3
  81. package/dist/vitest-repo.d.ts +5 -3
  82. package/dist/vitest-repo.d.ts.map +1 -1
  83. package/dist/vitest-repo.js +1 -1
  84. package/dist/vitest-repo.js.map +3 -3
  85. package/dist/vitest-web.d.ts +3 -2
  86. package/dist/vitest-web.d.ts.map +1 -1
  87. package/dist/vitest-web.js +1 -1
  88. package/dist/vitest-web.js.map +3 -3
  89. package/dist/vitest.d.ts +5 -3
  90. package/dist/vitest.d.ts.map +1 -1
  91. package/dist/vitest.js +1 -1
  92. package/dist/vitest.js.map +3 -3
  93. package/package.json +14 -3
  94. package/presets/prettier.d.mts +4 -0
  95. package/presets/prettier.mjs +16 -0
  96. package/presets/tsconfig/base.json +19 -0
  97. package/presets/tsconfig/web.json +10 -0
  98. package/presets/tsconfig/worker.json +9 -0
  99. package/schema/manifest.schema.json +105 -0
  100. package/src/eslint-manifest.ts +71 -0
  101. package/src/eslint-options.ts +54 -0
  102. package/src/eslint-strict.test.ts +106 -0
  103. package/src/eslint-strict.ts +191 -0
  104. package/src/eslint.ts +18 -41
  105. package/src/index.ts +15 -2
  106. package/src/manifest-validate.ts +202 -0
  107. package/src/manifest.test.ts +228 -0
  108. package/src/manifest.ts +194 -0
  109. package/src/pages-proxy.test.ts +8 -0
  110. package/src/pages-proxy.ts +13 -0
  111. package/src/plugin-option.test.ts +13 -0
  112. package/src/plugin-option.ts +18 -0
  113. package/src/presets.test.ts +63 -0
  114. package/src/scripts/check-god-files.ts +3 -0
  115. package/src/scripts/ensure-spa-shell-stub.ts +18 -10
  116. package/src/scripts/entrypoints.test.ts +55 -0
  117. package/src/scripts/init-secrets.ts +8 -6
  118. package/src/scripts/migrations-lock.ts +22 -17
  119. package/src/scripts/prepare-wrangler-config.ts +26 -14
  120. package/src/scripts/validate-locales.ts +39 -17
  121. package/src/scripts/verify-spa-shell.ts +21 -20
  122. package/src/test/mocks/cloudflare-workers.ts +6 -113
  123. package/src/vite.ts +6 -3
  124. package/src/vitest-aliases.test.ts +23 -0
  125. package/src/vitest-aliases.ts +22 -1
  126. package/src/vitest-factories.test.ts +30 -1
  127. package/src/vitest-integration.ts +5 -3
  128. package/src/vitest-repo.ts +10 -5
  129. package/src/vitest-web.ts +5 -3
  130. package/src/vitest.ts +10 -5
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Create the Secrets Store entries declared in `wrangler.jsonc`, generating a fresh
4
3
  * value for each one that does not exist yet.
@@ -47,6 +46,7 @@
47
46
  import { execFileSync } from 'node:child_process';
48
47
  import { existsSync, readFileSync } from 'node:fs';
49
48
  import { parse } from 'jsonc-parser';
49
+ import { isEntrypoint } from './lib/entrypoint.ts';
50
50
  import { fail } from './lib/github-actions.ts';
51
51
  import { isEmptySecretsStoreListing, parseWranglerNames } from './lib/wrangler-table.ts';
52
52
  import { CONFIG_PATH, type WranglerConfig } from './wrangler-config/types.ts';
@@ -230,7 +230,7 @@ function createSecret(storeId: string, secretName: string, secretValue: string):
230
230
  wrangler(['secrets-store', 'secret', 'create', storeId, '--name', secretName, '--scopes', 'workers', '--remote'], secretValue);
231
231
  }
232
232
 
233
- async function main(): Promise<void> {
233
+ export async function main(): Promise<void> {
234
234
  console.log('Initializing Cloudflare secrets...');
235
235
  const config = parseWranglerConfig();
236
236
  const plan = planSecrets(config);
@@ -266,8 +266,10 @@ async function main(): Promise<void> {
266
266
  // as a stack trace with its cause intact and the process exits non-zero. Either way
267
267
  // the exit status has to be right: this runs in the deploy pipeline, and swallowing
268
268
  // the rejection reported a failed key bootstrap as a green step.
269
- try {
270
- await main();
271
- } catch (error: unknown) {
272
- fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));
269
+ if (isEntrypoint(import.meta.url)) {
270
+ try {
271
+ await main();
272
+ } catch (error: unknown) {
273
+ fail(error instanceof Error ? `Secret initialization failed: ${error.message}` : String(error));
274
+ }
273
275
  }
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Record newly-added migration files in `migrations/migrations.lock.json`.
4
3
  *
@@ -29,23 +28,29 @@
29
28
  */
30
29
  import path from 'node:path';
31
30
  import { fileURLToPath } from 'node:url';
31
+ import { isEntrypoint } from './lib/entrypoint.ts';
32
32
  import { LOCK_NAME, verifyMigrations } from './verify-migrations.ts';
33
33
 
34
- const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
35
- const migrationsDir = process.argv[2] === undefined ? path.join(REPOSITORY_ROOT, 'migrations') : path.resolve(process.argv[2]);
36
-
37
- const report = verifyMigrations(migrationsDir, { write: true });
38
-
39
- for (const problem of report.problems) {
40
- console.error(`FAIL: ${problem.problem}`);
34
+ /**
35
+ * Write the lock. `args[0]` is the migrations directory (default `./migrations`
36
+ * beside the repo this file sits in). Returns the exit code; it is non-zero when a
37
+ * problem the write cannot resolve (an `edited` entry) remains.
38
+ */
39
+ export function main(args: readonly string[] = process.argv.slice(2)): number {
40
+ const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
41
+ const migrationsDir = args[0] === undefined ? path.join(repositoryRoot, 'migrations') : path.resolve(args[0]);
42
+ const report = verifyMigrations(migrationsDir, { write: true });
43
+ for (const problem of report.problems) {
44
+ console.error(`FAIL: ${problem.problem}`);
45
+ }
46
+ console.log(
47
+ `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} (${report.files.length} migration(s) recorded)`,
48
+ );
49
+ // The lock is re-checked by the caller: `verify-migrations.ts` re-reads from disk,
50
+ // so running it after this command reports the same verdict CI will.
51
+ return report.problems.length === 0 ? 0 : 1;
41
52
  }
42
53
 
43
- console.log(
44
- `${report.lock === null ? 'left' : 'wrote'} ${path.join(migrationsDir, LOCK_NAME)} (${report.files.length} migration(s) recorded)`,
45
- );
46
-
47
- // The lock is re-checked by the caller: `verify-migrations.ts` re-reads from disk,
48
- // so running it after this command reports the same verdict CI will. A `--write`
49
- // that could not resolve everything still exits non-zero here, which is why an
50
- // incremental `edited` finding does not vanish just because someone wrote.
51
- process.exit(report.problems.length === 0 ? 0 : 1);
54
+ if (isEntrypoint(import.meta.url)) {
55
+ process.exit(main());
56
+ }
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Materialize `wrangler.jsonc` and provision what it refers to.
4
3
  *
@@ -34,18 +33,31 @@
34
33
  import { setOutput } from './lib/github-actions.ts';
35
34
  import { applyTopLevelPatch, applyVarsPatch, ensureMinimumConfigVersion, prepareConfigFile } from './wrangler-config/patches.ts';
36
35
  import { provisionWranglerResources } from './wrangler-config/resources.ts';
36
+ import { isEntrypoint } from './lib/entrypoint.ts';
37
37
 
38
- prepareConfigFile();
39
- ensureMinimumConfigVersion();
40
- applyTopLevelPatch();
41
- applyVarsPatch();
42
- const created = provisionWranglerResources();
38
+ /**
39
+ * Materialize and provision. Reads `process.env` and `process.cwd()` (the config paths
40
+ * resolve when `wrangler-config/types.ts` is first imported, so a caller changing
41
+ * directory must do so before importing this module). Returns the created resources.
42
+ */
43
+ export function main(): string[] {
44
+ prepareConfigFile();
45
+ ensureMinimumConfigVersion();
46
+ applyTopLevelPatch();
47
+ applyVarsPatch();
48
+ const created = provisionWranglerResources();
49
+
50
+ // Published as a step output rather than only printed. The backup workflow needs
51
+ // to know whether the D1 database *existed* or was created moments ago: a fresh one
52
+ // holds no user data, and uploading that empty dump every night is a false sense
53
+ // of safety. The alternative — re-reading the placeholder id out of
54
+ // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches
55
+ // the placeholder away before the reader ever runs.
56
+ setOutput('created', created.join(','));
57
+ console.log('Wrangler configuration is ready.');
58
+ return created;
59
+ }
43
60
 
44
- // Published as a step output rather than only printed. The backup workflow needs
45
- // to know whether the D1 database *existed* or was created moments ago: a fresh one
46
- // holds no user data, and uploading that empty dump every night is a false sense
47
- // of safety. The alternative — re-reading the placeholder id out of
48
- // `wrangler.jsonc` — is unreachable, because `provisionWranglerResources` patches
49
- // the placeholder away before the reader ever runs.
50
- setOutput('created', created.join(','));
51
- console.log('Wrangler configuration is ready.');
61
+ if (isEntrypoint(import.meta.url)) {
62
+ main();
63
+ }
@@ -720,6 +720,42 @@ function validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): nu
720
720
  const callSiteDir = argv.find((arg) => arg.startsWith('--call-sites='))?.slice('--call-sites='.length);
721
721
  const tagsFile = argv.find((arg) => arg.startsWith('--tags='))?.slice('--tags='.length);
722
722
 
723
+ const { report, problems } = collectLocaleProblems({ dir, base, shape, callSiteDir, tagsFile });
724
+ const failures = problems.filter((problem) => problem.advisory !== true);
725
+ const advisories = problems.filter((problem) => problem.advisory === true);
726
+
727
+ if (failures.length > 0) {
728
+ console.error(`Locale validation failed for ${dir} (${failures.length} problem(s)):`);
729
+ for (const problem of failures) console.error(` - ${problem.locale}: ${problem.problem}`);
730
+ return 1;
731
+ }
732
+ if (advisories.length > 0) {
733
+ console.warn(`Locale validation passed for ${dir} with ${advisories.length} advisory finding(s):`);
734
+ for (const problem of advisories) console.warn(` - ${problem.locale}: ${problem.problem}`);
735
+ }
736
+ console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);
737
+ return 0;
738
+ }
739
+
740
+ /**
741
+ What `collectLocaleProblems` checks: the bundles, and optionally the declared tags and the `t()` call sites.
742
+ */
743
+ interface LocaleCheckOptions {
744
+ dir: string;
745
+ base?: string;
746
+ shape?: LocaleShape;
747
+ callSiteDir?: string;
748
+ tagsFile?: string;
749
+ }
750
+
751
+ /**
752
+ * Every finding for one locales directory, as data. The CLI prints it and `rexezuge locales validate --json` serializes it;
753
+ * advisories carry `advisory: true`, everything else is a failure.
754
+ */
755
+ function collectLocaleProblems(options: LocaleCheckOptions): { report: LocaleReport; problems: LocaleProblem[] } {
756
+ const { dir, callSiteDir, tagsFile } = options;
757
+ const base = options.base ?? 'en';
758
+ const shape = options.shape ?? 'auto';
723
759
  const report = validateLocales(dir, base, shape);
724
760
  const problems = [...report.problems];
725
761
 
@@ -744,25 +780,11 @@ function validateLocalesCli(argv: readonly string[] = process.argv.slice(2)): nu
744
780
  problems.push({ locale: 'call-site', problem: `${callSiteDir}: ${error instanceof Error ? error.message : String(error)}` });
745
781
  }
746
782
  }
747
-
748
- const failures = problems.filter((problem) => problem.advisory !== true);
749
- const advisories = problems.filter((problem) => problem.advisory === true);
750
-
751
- if (failures.length > 0) {
752
- console.error(`Locale validation failed for ${dir} (${failures.length} problem(s)):`);
753
- for (const problem of failures) console.error(` - ${problem.locale}: ${problem.problem}`);
754
- return 1;
755
- }
756
- if (advisories.length > 0) {
757
- console.warn(`Locale validation passed for ${dir} with ${advisories.length} advisory finding(s):`);
758
- for (const problem of advisories) console.warn(` - ${problem.locale}: ${problem.problem}`);
759
- }
760
- console.log(`Locale validation passed (${report.locales.length} locales, ${report.keys} keys each, shape ${shape}).`);
761
- return 0;
783
+ return { report, problems };
762
784
  }
763
785
 
764
- export { parseObjectLiteral, validateLocales, validateLocalesCli };
765
- export type { LocaleProblem, LocaleReport, LocaleShape };
786
+ export { collectLocaleProblems, parseObjectLiteral, validateLocales, validateLocalesCli };
787
+ export type { LocaleCheckOptions, LocaleProblem, LocaleReport, LocaleShape };
766
788
 
767
789
  // Run only when this file is the entrypoint.
768
790
  //
@@ -1,4 +1,3 @@
1
- #!/usr/bin/env tsx
2
1
  /**
3
2
  * Fail when the SPA shell the API worker serves is missing or self-inconsistent.
4
3
  *
@@ -31,28 +30,30 @@
31
30
  */
32
31
  import path from 'node:path';
33
32
  import { fileURLToPath } from 'node:url';
33
+ import { isEntrypoint } from './lib/entrypoint.ts';
34
34
  import { verifySpaShell } from './spa-shell.ts';
35
35
 
36
36
  /**
37
- * The repository root, derived from this file rather than from `process.cwd()`.
38
- *
39
- * Two levels up, because this file sits in `scripts/`. Deriving it means the gate
40
- * reads the same tree whatever directory it is invoked from — which is the
41
- * difference between a gate and a gate that passes because nobody ran it from the
42
- * right place.
37
+ * Verify the shell. `args[0]` is the repo root, derived from this file when absent
38
+ * rather than from `process.cwd()`: the gate reads the same tree whatever directory
39
+ * it is invoked from, which is the difference between a gate and a gate that passes
40
+ * because nobody ran it from the right place. Returns the exit code.
43
41
  */
44
- const REPOSITORY_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
45
-
46
- const root = process.argv[2] === undefined ? REPOSITORY_ROOT : path.resolve(process.argv[2]);
47
-
48
- const { problems } = verifySpaShell({ root });
49
-
50
- if (problems.length > 0) {
51
- console.error('SPA shell check failed:');
52
- for (const problem of problems) console.error(` - ${problem}`);
53
- process.exit(1);
42
+ export function main(args: readonly string[] = process.argv.slice(2)): number {
43
+ const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
44
+ const root = args[0] === undefined ? repositoryRoot : path.resolve(args[0]);
45
+ const { problems } = verifySpaShell({ root });
46
+ if (problems.length > 0) {
47
+ console.error('SPA shell check failed:');
48
+ for (const problem of problems) console.error(` - ${problem}`);
49
+ return 1;
50
+ }
51
+ console.log(
52
+ `SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`,
53
+ );
54
+ return 0;
54
55
  }
55
56
 
56
- console.log(
57
- `SPA shell check passed (${path.join(root, 'apps/api/src/generated/spa-shell.ts')} matches ${path.join(root, 'apps/web/dist')}).`,
58
- );
57
+ if (isEntrypoint(import.meta.url)) {
58
+ process.exit(main());
59
+ }
@@ -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
@@ -33,6 +33,8 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
33
33
  import path from 'node:path';
34
34
  import { fileURLToPath, pathToFileURL } from 'node:url';
35
35
  import { defineConfig, type Plugin, type ViteUserConfig } from 'vitest/config';
36
+ import { asVitePlugins } from './plugin-option.ts';
37
+ import type { PluginOption } from './plugin-option.ts';
36
38
 
37
39
  /**
38
40
  * One dev-server proxy entry, as Vite's `server.proxy` accepts it.
@@ -104,7 +106,7 @@ export interface WebViteConfigOptions {
104
106
  * needs. Applied before the spa-shell plugin so the shell is written after the
105
107
  * bundle exists.
106
108
  */
107
- readonly plugins?: readonly Plugin[];
109
+ readonly plugins?: readonly PluginOption[];
108
110
  /**
109
111
  * Dev-server proxy entries. Keyed by path prefix.
110
112
  */
@@ -206,6 +208,7 @@ export function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBun
206
208
  );
207
209
 
208
210
  if (!existsSync(indexPath)) {
211
+ // eslint-disable-next-line no-restricted-globals -- build-time Vite plugin, not worker code: there is no logger to inject
209
212
  console.warn('spa-shell-embed: dist/index.html not found, skipping');
210
213
  return;
211
214
  }
@@ -235,13 +238,13 @@ export function spaShellEmbedPlugin(target: SpaShellTarget): Plugin & { closeBun
235
238
  * ```
236
239
  */
237
240
  export function defineWebViteConfig(options: WebViteConfigOptions = {}): ViteUserConfig {
238
- const plugins: Plugin[] = [...(options.plugins ?? [])];
241
+ const plugins: PluginOption[] = [...(options.plugins ?? [])];
239
242
  if (options.spaShell !== undefined) {
240
243
  plugins.push(spaShellEmbedPlugin(options.spaShell));
241
244
  }
242
245
 
243
246
  return defineConfig({
244
- ...(plugins.length > 0 && { plugins }),
247
+ ...(plugins.length > 0 && { plugins: asVitePlugins(plugins) }),
245
248
  ...(options.proxy !== undefined && { server: { proxy: { ...options.proxy } } }),
246
249
  build: {
247
250
  outDir: options.outDir ?? 'dist',
@@ -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');
@@ -1,3 +1,5 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { createRequire } from 'node:module';
1
3
  import { fileURLToPath } from 'node:url';
2
4
 
3
5
  /**
@@ -113,9 +115,24 @@ export interface WorkspaceAliasesOptions {
113
115
  readonly extraAliases?: readonly VitestAlias[];
114
116
  }
115
117
 
118
+ /**
119
+ * Where the kit's own `cloudflare:workers` mock lives, or `null` when
120
+ * `@rexezuge/testing` is not resolvable from here.
121
+ */
122
+ function kitWorkersMock(): string | null {
123
+ try {
124
+ return createRequire(import.meta.url).resolve('@rexezuge/testing/cloudflare-workers');
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
116
130
  /**
117
131
  * Build the workspace alias table for a consumer repo.
118
132
  *
133
+ * `cloudflare:workers` resolves to `<root>/test/mocks/cloudflare-workers.ts` when
134
+ * that file exists, and otherwise to `@rexezuge/testing/cloudflare-workers`.
135
+ *
119
136
  * Aliases point at source rather than at built output, so a test exercises the
120
137
  * code the worker would run without a build step. `background` resolves under
121
138
  * `apps/`; every other package under `packages/`. `@/` maps to the API worker
@@ -133,7 +150,11 @@ export function workspaceAliases(options: WorkspaceAliasesOptions): VitestAlias[
133
150
  aliases.push({ find: `${scope}/${name}`, replacement: at(dir) });
134
151
  }
135
152
  for (const mock of mocks) {
136
- aliases.push({ find: `cloudflare:${mock}`, replacement: at(`test/mocks/cloudflare-${mock}.ts`) });
153
+ const local = at(`test/mocks/cloudflare-${mock}.ts`);
154
+ // A repo with no copy of its own gets the kit's: the `workers` mock is a
155
+ // superset of the thirteen family copies, so deleting yours is safe.
156
+ const kit = mock === 'workers' && !existsSync(local) ? kitWorkersMock() : null;
157
+ aliases.push({ find: `cloudflare:${mock}`, replacement: kit ?? local });
137
158
  }
138
159
  const apiSrc = at('apps/api/src');
139
160
  const webSrc = at('apps/web/src');
@@ -1,4 +1,8 @@
1
- import { describe, expect, it } from 'vitest';
1
+ import { mkdtempSync, 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 { afterAll, beforeAll, describe, expect, it } from 'vitest';
2
6
  import { defineUnitVitestConfig } from './vitest.ts';
3
7
  import { defineWebVitestConfig } from './vitest-web.ts';
4
8
  import { defineRepoVitestConfig } from './vitest-repo.ts';
@@ -125,3 +129,28 @@ describe('defineIntegrationVitestConfig', () => {
125
129
  expect(test['pool']).toBeUndefined();
126
130
  });
127
131
  });
132
+
133
+ describe('coverage thresholds from the manifest', () => {
134
+ const coverageOf = (config: unknown): { thresholds?: unknown } => (testOf(config)['coverage'] ?? {}) as { thresholds?: unknown };
135
+ let dir: string;
136
+ let root: string;
137
+ beforeAll(() => {
138
+ dir = mkdtempSync(path.join(tmpdir(), 'vitest-manifest-'));
139
+ root = pathToFileURL(`${dir}/`).href;
140
+ writeFileSync(
141
+ path.join(dir, '.rexezuge.jsonc'),
142
+ '{ "name": "x", "scope": "@x", "quality": { "coverage": { "lines": 71, "branches": 62, "functions": 73, "statements": 74 } } }',
143
+ );
144
+ });
145
+ afterAll(() => rmSync(dir, { recursive: true, force: true }));
146
+
147
+ const floor = { lines: 71, branches: 62, functions: 73, statements: 74 };
148
+ it('defaults the unit and repo factories to the manifest floor', () => {
149
+ expect(coverageOf(defineUnitVitestConfig({ root })).thresholds).toEqual(floor);
150
+ expect(coverageOf(defineRepoVitestConfig({ scope: '@x', root })).thresholds).toEqual(floor);
151
+ });
152
+ it('lets an explicit option win, and sets none without a manifest', () => {
153
+ expect(coverageOf(defineUnitVitestConfig({ root, thresholds: { lines: 5 } })).thresholds).toEqual({ lines: 5 });
154
+ expect(coverageOf(defineUnitVitestConfig({ root: ROOT })).thresholds).toBeUndefined();
155
+ });
156
+ });
@@ -17,7 +17,9 @@
17
17
  * `node:sqlite`, no coverage); the workerd suites pass all three.
18
18
  */
19
19
 
20
- import { defineConfig, type Plugin } from 'vitest/config';
20
+ import { defineConfig } from 'vitest/config';
21
+ import { asVitePlugins } from './plugin-option.ts';
22
+ import type { PluginOption } from './plugin-option.ts';
21
23
  import type { Pool } from 'vitest/node';
22
24
  import { DEFAULT_WORKSPACE_PACKAGES, workspaceAliases } from './vitest-aliases.ts';
23
25
  import type { VitestAlias } from './vitest-aliases.ts';
@@ -54,7 +56,7 @@ export interface IntegrationVitestConfigOptions {
54
56
  * runner's own plugin so a workerd plugin is accepted and nothing new is
55
57
  * imported — this package stays dependency-free.
56
58
  */
57
- readonly plugins?: readonly Plugin[];
59
+ readonly plugins?: readonly PluginOption[];
58
60
  /**
59
61
  * The pool (the workerd `cloudflarePool()`). The runner's own `Pool` type,
60
62
  * so a custom pool is accepted without importing its provider.
@@ -105,7 +107,7 @@ export function defineIntegrationVitestConfig(options: IntegrationVitestConfigOp
105
107
 
106
108
  return defineConfig({
107
109
  ...(options.define !== undefined && { define: { ...options.define } }),
108
- ...(options.plugins !== undefined && { plugins: [...options.plugins] }),
110
+ ...(options.plugins !== undefined && { plugins: asVitePlugins(options.plugins) }),
109
111
  resolve: { alias: aliases },
110
112
  test: {
111
113
  globals: true,
@@ -23,8 +23,11 @@
23
23
  * 'node'` and `server.deps.inline` from `defineUnitVitestConfig()`.
24
24
  */
25
25
 
26
- import { defineConfig, type Plugin } from 'vitest/config';
26
+ import { defineConfig } from 'vitest/config';
27
+ import { asVitePlugins } from './plugin-option.ts';
28
+ import type { PluginOption } from './plugin-option.ts';
27
29
  import { fileURLToPath } from 'node:url';
30
+ import { manifestCoverageThresholds } from './manifest.ts';
28
31
  import { DEFAULT_CLOUDFLARE_MOCKS, DEFAULT_WORKSPACE_PACKAGES, KIT_NO_EXTERNAL, workspaceAliases } from './vitest-aliases.ts';
29
32
  import type { VitestAlias } from './vitest-aliases.ts';
30
33
  import type { CoverageThresholds } from './vitest.ts';
@@ -80,7 +83,7 @@ export interface RepoWebOptions {
80
83
  /**
81
84
  * Vite plugins the SPA needs (`react()` for JSX).
82
85
  */
83
- readonly plugins?: readonly Plugin[];
86
+ readonly plugins?: readonly PluginOption[];
84
87
  /**
85
88
  * Extra resolver entries for the web project only.
86
89
  */
@@ -140,7 +143,8 @@ export interface RepoVitestConfigOptions {
140
143
  */
141
144
  readonly includeIndexBarrels?: boolean;
142
145
  /**
143
- * Coverage floors. Omitted by default; a repo that wants them sets them.
146
+ * Coverage floors. Defaults to the manifest's `quality.coverage` (`.rexezuge.jsonc`
147
+ * at `root`); without one, no floor.
144
148
  */
145
149
  readonly thresholds?: CoverageThresholds;
146
150
  /**
@@ -206,6 +210,7 @@ const INDEX_BARREL_EXCLUDE = '**/index.ts';
206
210
  */
207
211
  export function defineRepoVitestConfig(options: RepoVitestConfigOptions): ReturnType<typeof defineConfig> {
208
212
  const root = options.root ?? new URL('.', import.meta.url).href;
213
+ const thresholds = options.thresholds ?? manifestCoverageThresholds(root);
209
214
  const packages = options.packages ?? DEFAULT_WORKSPACE_PACKAGES;
210
215
  const mocks = options.mocks ?? DEFAULT_CLOUDFLARE_MOCKS;
211
216
  const noExternal = [...KIT_NO_EXTERNAL, ...(options.noExternal ?? [])];
@@ -247,7 +252,7 @@ export function defineRepoVitestConfig(options: RepoVitestConfigOptions): Return
247
252
  },
248
253
  },
249
254
  {
250
- ...(web.plugins !== undefined && { plugins: [...web.plugins] }),
255
+ ...(web.plugins !== undefined && { plugins: asVitePlugins(web.plugins) }),
251
256
  resolve: { alias: webAliases, noExternal },
252
257
  test: {
253
258
  name: 'web',
@@ -275,7 +280,7 @@ export function defineRepoVitestConfig(options: RepoVitestConfigOptions): Return
275
280
  exclude: options.includeIndexBarrels
276
281
  ? [...CANONICAL_COVERAGE_EXCLUDE.filter((glob) => glob !== INDEX_BARREL_EXCLUDE), ...(options.coverageExclude ?? [])]
277
282
  : [...CANONICAL_COVERAGE_EXCLUDE, ...(options.coverageExclude ?? [])],
278
- ...(options.thresholds !== undefined && { thresholds: { ...options.thresholds } }),
283
+ ...(thresholds !== undefined && { thresholds: { ...thresholds } }),
279
284
  },
280
285
  },
281
286
  });