@rexezuge/tooling 1.9.1 → 1.9.2

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 (33) hide show
  1. package/dist/scripts/check-god-files.js +2 -2
  2. package/dist/scripts/check-god-files.js.map +3 -3
  3. package/dist/scripts/lib/entrypoint.d.ts +27 -0
  4. package/dist/scripts/lib/entrypoint.d.ts.map +1 -0
  5. package/dist/scripts/lib/entrypoint.js +1 -0
  6. package/dist/scripts/lib/entrypoint.js.map +7 -0
  7. package/dist/scripts/spa-shell.js +2 -2
  8. package/dist/scripts/spa-shell.js.map +3 -3
  9. package/dist/scripts/validate-locales.js +5 -5
  10. package/dist/scripts/validate-locales.js.map +3 -3
  11. package/dist/scripts/verify-migrations.js +2 -2
  12. package/dist/scripts/verify-migrations.js.map +3 -3
  13. package/dist/scripts/wrangler-config/patches.d.ts.map +1 -1
  14. package/dist/scripts/wrangler-config/patches.js +3 -3
  15. package/dist/scripts/wrangler-config/patches.js.map +3 -3
  16. package/dist/scripts/wrangler-config/resources.d.ts +17 -7
  17. package/dist/scripts/wrangler-config/resources.d.ts.map +1 -1
  18. package/dist/scripts/wrangler-config/resources.js +1 -1
  19. package/dist/scripts/wrangler-config/resources.js.map +3 -3
  20. package/dist/scripts/wrangler-config/types.d.ts +3 -2
  21. package/dist/scripts/wrangler-config/types.d.ts.map +1 -1
  22. package/dist/scripts/wrangler-config/types.js.map +2 -2
  23. package/package.json +2 -2
  24. package/src/scripts/check-god-files.ts +2 -2
  25. package/src/scripts/lib/entrypoint.test.ts +60 -0
  26. package/src/scripts/lib/entrypoint.ts +39 -0
  27. package/src/scripts/spa-shell.ts +2 -2
  28. package/src/scripts/validate-locales.ts +2 -2
  29. package/src/scripts/verify-migrations.ts +2 -2
  30. package/src/scripts/wrangler-config/patches.ts +11 -2
  31. package/src/scripts/wrangler-config/resources.test.ts +49 -0
  32. package/src/scripts/wrangler-config/resources.ts +38 -16
  33. package/src/scripts/wrangler-config/types.ts +3 -2
@@ -0,0 +1,60 @@
1
+ import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import path from 'node:path';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { isEntrypoint } from './entrypoint.ts';
6
+
7
+ function repo(): string {
8
+ return mkdtempSync(path.join(tmpdir(), 'entrypoint-'));
9
+ }
10
+
11
+ describe('isEntrypoint', () => {
12
+ it('matches when the entrypoint is the file itself', () => {
13
+ const file = path.join(repo(), 'script.mjs');
14
+ writeFileSync(file, '');
15
+ expect(isEntrypoint(`file://${file}`, file)).toBe(true);
16
+ });
17
+
18
+ it('matches through a symlink, which is how pnpm installs every package', () => {
19
+ // The regression. `process.argv[1]` is whatever the caller typed —
20
+ // `node_modules/@rexezuge/tooling/dist/scripts/x.js`, a symlink into the
21
+ // store — while `import.meta.url` is always the realpath, because the ESM
22
+ // resolver follows links. Comparing the two unresolved returns false, the
23
+ // guard never fires, and the script exits 0 having printed nothing.
24
+ //
25
+ // For a *gate* that is the worst shape a failure can take: `validate-locales`
26
+ // passed with a key missing from eleven bundles and `check-god-files` reported
27
+ // no file over the limit, both silently. Found by a consumer swapping in its
28
+ // own copy and finding the replacement stopped catching what the old one
29
+ // reported on the same tree.
30
+ const root = repo();
31
+ const store = path.join(root, 'store', 'tooling');
32
+ mkdirSync(path.join(store, 'dist'), { recursive: true });
33
+ const real = path.join(store, 'dist', 'script.mjs');
34
+ writeFileSync(real, '');
35
+ // The pnpm layout: `node_modules/@rexezuge/tooling` is a symlink to the store.
36
+ mkdirSync(path.join(root, 'node_modules'), { recursive: true });
37
+ symlinkSync(path.dirname(store), path.join(root, 'node_modules', '@rexezuge'), 'dir');
38
+ const entry = path.join(root, 'node_modules', '@rexezuge', 'tooling', 'dist', 'script.mjs');
39
+ expect(isEntrypoint(`file://${real}`, entry)).toBe(true);
40
+ });
41
+
42
+ it('does not match the module a suite imported', () => {
43
+ // The reason the guard exists: these modules export their rules so the tests
44
+ // can import them, and during a test run `argv[1]` is the test file.
45
+ const root = repo();
46
+ const test = path.join(root, 'thing.test.ts');
47
+ const script = path.join(root, 'script.mjs');
48
+ writeFileSync(test, '');
49
+ writeFileSync(script, '');
50
+ expect(isEntrypoint(`file://${script}`, test)).toBe(false);
51
+ });
52
+
53
+ it('does not match when the entrypoint is absent, or does not resolve', () => {
54
+ // Exercised through the real default rather than by passing `undefined`:
55
+ // `isEntrypoint` reads `process.argv[1]`, and under a test run that is the
56
+ // test file, which is the case the guard exists to exclude anyway.
57
+ expect(isEntrypoint('file:///nope.mjs')).toBe(false);
58
+ expect(isEntrypoint('file:///nope.mjs', '/also/not/here.mjs')).toBe(false);
59
+ });
60
+ });
@@ -0,0 +1,39 @@
1
+ import { realpathSync } from 'node:fs';
2
+ import { pathToFileURL } from 'node:url';
3
+
4
+ /**
5
+ * Whether this module is the process's entrypoint.
6
+ *
7
+ * The comparison needs **both** sides resolved through `realpathSync`, and that
8
+ * is not a detail. `process.argv[1]` is whatever the caller typed — under pnpm
9
+ * that is `node_modules/@rexezuge/tooling/dist/scripts/…`, a **symlink** into the
10
+ * store — while `import.meta.url` is always the realpath, because the ESM
11
+ * resolver follows links. So the two never matched, the guard never fired, and
12
+ * every script below exited 0 having printed nothing.
13
+ *
14
+ * That is the worst shape a gate can fail in: it looks green. `check-god-files`
15
+ * reported no file over the limit for every repository that adopted it,
16
+ * `validate-locales` passed with a key missing from eleven bundles, and neither
17
+ * said a word. Found by AWS-AccessBridge swapping in its own `validate_locales`
18
+ * and finding that the replacement stopped catching the defect the old one
19
+ * reported on the same tree.
20
+ *
21
+ * It is worth a function rather than an inline comparison because four scripts
22
+ * carry the same guard, and a shared helper is what makes the fifth correct
23
+ * instead of a fourth copy of the same mistake.
24
+ *
25
+ * A missing or unreadable entrypoint is not the entrypoint, and the caller
26
+ * exports the rule functions precisely so the module stays importable — a suite
27
+ * imports these to test the rules, and there `process.argv[1]` is the test file.
28
+ */
29
+ export function isEntrypoint(moduleUrl: string, argv1: string | undefined = process.argv[1]): boolean {
30
+ if (argv1 === undefined) {
31
+ return false;
32
+ }
33
+ try {
34
+ return moduleUrl === pathToFileURL(realpathSync(argv1)).href;
35
+ } catch {
36
+ // A path that does not resolve cannot be the file that is running.
37
+ return false;
38
+ }
39
+ }
@@ -1,3 +1,4 @@
1
+ import { isEntrypoint } from './lib/entrypoint.ts';
1
2
  /**
2
3
  * The SPA shell pair: `ensure-spa-shell-stub` + `verify-spa-shell`.
3
4
  *
@@ -14,7 +15,6 @@
14
15
  * with nothing in the source tree saying so.
15
16
  */
16
17
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
17
- import { pathToFileURL } from 'node:url';
18
18
  import path from 'node:path';
19
19
 
20
20
  interface SpaShellPaths {
@@ -188,6 +188,6 @@ export type { SpaShellPaths, VerifyResult };
188
188
  // an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
189
189
  // it is what keeps the rule modules importable — which is the whole reason they are
190
190
  // separate modules in the first place.
191
- if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
191
+ if (isEntrypoint(import.meta.url)) {
192
192
  process.exit(spaShellCli(process.argv.slice(2)));
193
193
  }
@@ -1,3 +1,4 @@
1
+ import { isEntrypoint } from './lib/entrypoint.ts';
1
2
  /**
2
3
  * Validate that every locale bundle carries exactly the base locale's keys.
3
4
  *
@@ -36,7 +37,6 @@
36
37
  * the kit ships and the SPA bundles the repos do.
37
38
  */
38
39
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
39
- import { pathToFileURL } from 'node:url';
40
40
  import path from 'node:path';
41
41
 
42
42
  /**
@@ -771,6 +771,6 @@ export type { LocaleProblem, LocaleReport, LocaleShape };
771
771
  // an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
772
772
  // it is what keeps the rule modules importable — which is the whole reason they are
773
773
  // separate modules in the first place.
774
- if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
774
+ if (isEntrypoint(import.meta.url)) {
775
775
  process.exit(validateLocalesCli(process.argv.slice(2)));
776
776
  }
@@ -1,3 +1,4 @@
1
+ import { isEntrypoint } from './lib/entrypoint.ts';
1
2
  /**
2
3
  * Verify the migration set is complete, ordered, and locked; write the lock.
3
4
  *
@@ -59,7 +60,6 @@
59
60
  * bless a drift would be the operator blessing their own edit.
60
61
  */
61
62
  import { createHash } from 'node:crypto';
62
- import { pathToFileURL } from 'node:url';
63
63
  import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
64
64
  import path from 'node:path';
65
65
 
@@ -391,6 +391,6 @@ export type { MigrationEntry, MigrationLockFile, MigrationProblem, MigrationRepo
391
391
  // an unconditional call is the same guard Durable-DAV's init-secrets.ts uses, and
392
392
  // it is what keeps the rule modules importable — which is the whole reason they are
393
393
  // separate modules in the first place.
394
- if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
394
+ if (isEntrypoint(import.meta.url)) {
395
395
  process.exit(verifyMigrationsCli(process.argv.slice(2)));
396
396
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { copyFileSync, readFileSync, writeFileSync } from 'node:fs';
14
+ import path from 'node:path';
14
15
  import { applyEdits, modify, parse } from 'jsonc-parser';
15
16
  import { CONFIG_PATH, TEMPLATE_PATH, type WranglerConfig } from './types.ts';
16
17
 
@@ -90,6 +91,14 @@ function parseJsonObject(raw: string | undefined, name: string, expected: string
90
91
  return parsed as Record<string, unknown>;
91
92
  }
92
93
 
94
+ /**
95
+ * A path as a log line should name it: relative to the working directory the
96
+ * script was invoked from, which is the repo root in every consumer.
97
+ */
98
+ function displayPath(filePath: string): string {
99
+ return path.relative(process.cwd(), filePath) || filePath;
100
+ }
101
+
93
102
  /**
94
103
  * Materialize the config: the repository variable when it is set, otherwise the
95
104
  * committed template.
@@ -102,7 +111,7 @@ export function prepareConfigFile(): void {
102
111
  return;
103
112
  }
104
113
  copyFileSync(TEMPLATE_PATH, CONFIG_PATH);
105
- console.log('WRANGLER_JSONC is empty; copied apps/api/wrangler.template.jsonc to wrangler.jsonc.');
114
+ console.log(`WRANGLER_JSONC is empty; copied ${displayPath(TEMPLATE_PATH)} to ${displayPath(CONFIG_PATH)}.`);
106
115
  }
107
116
 
108
117
  /**
@@ -122,7 +131,7 @@ export function ensureMinimumConfigVersion(): void {
122
131
  const currentVersion = config.$version;
123
132
  if (typeof currentVersion !== 'number' || currentVersion < template.$minimumVersion) {
124
133
  throw new Error(
125
- `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from apps/api/wrangler.template.jsonc.`,
134
+ `wrangler.jsonc version (${typeof currentVersion === 'number' ? currentVersion : 'missing'}) is below minimum template version (${template.$minimumVersion}). Regenerate it from ${displayPath(TEMPLATE_PATH)}.`,
126
135
  );
127
136
  }
128
137
  }
@@ -0,0 +1,49 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { ensureRequiredKvBindings, getKVNamespaceName, getRequiredKvBindings } from './resources.ts';
3
+ import type { WranglerConfig } from './types.ts';
4
+
5
+ describe('getRequiredKvBindings', () => {
6
+ it('defaults to the CACHE binding every deployment needs', () => {
7
+ expect(getRequiredKvBindings()).toEqual(['CACHE']);
8
+ });
9
+
10
+ it('takes the bindings from the map it is given', () => {
11
+ expect(getRequiredKvBindings({ RECORD_CACHE: 'record-provider-record-cache' })).toEqual(['RECORD_CACHE']);
12
+ });
13
+
14
+ it('treats an explicitly empty map as needing no bindings', () => {
15
+ expect(getRequiredKvBindings({})).toEqual([]);
16
+ });
17
+ });
18
+
19
+ describe('getKVNamespaceName', () => {
20
+ it('derives a name from the worker and binding when the map does not list it', () => {
21
+ expect(getKVNamespaceName({ name: 'records-provider' }, 'RECORD_CACHE')).toBe('records-provider-record_cache');
22
+ });
23
+
24
+ it('uses the name the map gives', () => {
25
+ const namespaceNames = { RECORD_CACHE: 'record-provider-record-cache' };
26
+ expect(getKVNamespaceName({ name: 'records-provider' }, 'RECORD_CACHE', namespaceNames)).toBe('record-provider-record-cache');
27
+ });
28
+ });
29
+
30
+ describe('ensureRequiredKvBindings', () => {
31
+ it('adds the bindings from the caller’s map rather than the default CACHE binding', () => {
32
+ // The regression: a repo that binds RECORD_CACHE to an existing namespace
33
+ // must not have a stray CACHE added, whose provisioning would create an
34
+ // empty namespace and leave the record data unread.
35
+ const patched = ensureRequiredKvBindings(
36
+ '{\n "kv_namespaces": []\n}',
37
+ { kv_namespaces: [] },
38
+ { RECORD_CACHE: 'record-provider-record-cache' },
39
+ );
40
+ const bindings = (JSON.parse(patched) as WranglerConfig).kv_namespaces?.map((namespace) => namespace.binding);
41
+ expect(bindings).toEqual(['RECORD_CACHE']);
42
+ });
43
+
44
+ it('adds the default binding when no map is given', () => {
45
+ const patched = ensureRequiredKvBindings('{\n "kv_namespaces": []\n}', { kv_namespaces: [] });
46
+ const bindings = (JSON.parse(patched) as WranglerConfig).kv_namespaces?.map((namespace) => namespace.binding);
47
+ expect(bindings).toEqual(['CACHE']);
48
+ });
49
+ });
@@ -77,14 +77,27 @@ export function listKVNamespaces(): KVNamespace[] {
77
77
  }
78
78
 
79
79
  /**
80
- The namespace name a binding's namespace is created under.
81
- */
82
- export function getKVNamespaceName(config: WranglerConfig, binding: string): string {
83
- return DEFAULT_KV_NAMESPACE_NAMES[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;
80
+ * The namespace name a binding's namespace is created under.
81
+ *
82
+ * `namespaceNames` is the binding → namespace map, defaulting to the kit's
83
+ * `DEFAULT_KV_NAMESPACE_NAMES`. A consumer whose namespaces predate that convention
84
+ * passes its own, so provisioning finds the namespace that already holds the data
85
+ * instead of creating an empty one beside it and binding the worker to the new one.
86
+ */
87
+ export function getKVNamespaceName(
88
+ config: WranglerConfig,
89
+ binding: string,
90
+ namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,
91
+ ): string {
92
+ return namespaceNames[binding] ?? `${config.name ?? DEFAULT_WORKER_NAME}-${binding.toLowerCase()}`;
84
93
  }
85
94
 
86
- export function ensureKVNamespace(config: WranglerConfig, binding: string): Provisioned {
87
- const namespaceName = getKVNamespaceName(config, binding);
95
+ export function ensureKVNamespace(
96
+ config: WranglerConfig,
97
+ binding: string,
98
+ namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,
99
+ ): Provisioned {
100
+ const namespaceName = getKVNamespaceName(config, binding, namespaceNames);
88
101
  const candidateNames = new Set([namespaceName, `${config.name ?? DEFAULT_WORKER_NAME}-${binding}`, binding]);
89
102
  let namespace = listKVNamespaces().find((candidate) => {
90
103
  const candidateName = candidate.title ?? candidate.name;
@@ -106,8 +119,8 @@ export function ensureKVNamespace(config: WranglerConfig, binding: string): Prov
106
119
  /**
107
120
  The bindings a deployment always needs, whether or not a custom config lists them.
108
121
  */
109
- export function getRequiredKvBindings(): string[] {
110
- return Object.keys(DEFAULT_KV_NAMESPACE_NAMES);
122
+ export function getRequiredKvBindings(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {
123
+ return Object.keys(namespaceNames);
111
124
  }
112
125
 
113
126
  /**
@@ -116,9 +129,13 @@ export function getRequiredKvBindings(): string[] {
116
129
  * A config supplied through `WRANGLER_JSONC` is edited by hand and drifts; without
117
130
  * this the worker starts with an unbound `CACHE` and fails on the first read.
118
131
  */
119
- export function ensureRequiredKvBindings(content: string, config: WranglerConfig): string {
132
+ export function ensureRequiredKvBindings(
133
+ content: string,
134
+ config: WranglerConfig,
135
+ namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES,
136
+ ): string {
120
137
  const existing = new Set((config.kv_namespaces ?? []).map((namespace) => namespace.binding).filter((binding) => binding !== undefined));
121
- const missing = getRequiredKvBindings().filter((binding) => !existing.has(binding));
138
+ const missing = getRequiredKvBindings(namespaceNames).filter((binding) => !existing.has(binding));
122
139
  if (missing.length === 0) {
123
140
  return content;
124
141
  }
@@ -256,15 +273,15 @@ function provisionD1Databases(content: string, config: WranglerConfig, created:
256
273
  /**
257
274
  Replace each placeholder KV namespace id with a real one.
258
275
  */
259
- function provisionKvNamespaces(content: string, config: WranglerConfig, created: string[]): string {
276
+ function provisionKvNamespaces(content: string, config: WranglerConfig, created: string[], namespaceNames: Record<string, string>): string {
260
277
  let patched = content;
261
278
  for (const [index, namespace] of config.kv_namespaces?.entries() ?? []) {
262
279
  if (namespace.id !== DEFAULT_HEX_ID) continue;
263
280
  if (namespace.binding === undefined || namespace.binding === '') {
264
281
  throw new Error(`KV namespace at index ${index} has a placeholder id but no binding.`);
265
282
  }
266
- const resolved = ensureKVNamespace(config, namespace.binding);
267
- const namespaceName = getKVNamespaceName(config, namespace.binding);
283
+ const resolved = ensureKVNamespace(config, namespace.binding, namespaceNames);
284
+ const namespaceName = getKVNamespaceName(config, namespace.binding, namespaceNames);
268
285
  if (resolved.created) {
269
286
  created.push(`kv:${namespaceName}`);
270
287
  }
@@ -302,16 +319,21 @@ function provisionSecretStore(content: string, config: WranglerConfig, created:
302
319
  * Create every resource the config names, and write the real ids over the
303
320
  * placeholders.
304
321
  *
322
+ * `namespaceNames` is the binding → namespace map KV provisioning reconciles
323
+ * against, defaulting to the kit's `DEFAULT_KV_NAMESPACE_NAMES`; a consumer whose
324
+ * namespaces were named before that convention passes its own so the existing
325
+ * namespace is found instead of a second empty one being created.
326
+ *
305
327
  * Returns what it had to create, as `<kind>:<name>` — returned rather than logged,
306
328
  * because a caller acts on it: the backup workflow refuses to export a D1 database
307
329
  * that appears here, since one created moments ago holds no user data and an empty
308
330
  * dump uploaded on schedule is a false sense of safety.
309
331
  */
310
- export function provisionWranglerResources(): string[] {
332
+ export function provisionWranglerResources(namespaceNames: Record<string, string> = DEFAULT_KV_NAMESPACE_NAMES): string[] {
311
333
  const created: string[] = [];
312
334
  let { content, config } = readConfig();
313
335
 
314
- content = ensureRequiredKvBindings(content, config);
336
+ content = ensureRequiredKvBindings(content, config, namespaceNames);
315
337
  config = parse(content) as WranglerConfig;
316
338
 
317
339
  // Each of the three below re-parses before it patches, because each writes into
@@ -322,7 +344,7 @@ export function provisionWranglerResources(): string[] {
322
344
  content = provisionD1Databases(content, config, created);
323
345
  config = parse(content) as WranglerConfig;
324
346
 
325
- content = provisionKvNamespaces(content, config, created);
347
+ content = provisionKvNamespaces(content, config, created, namespaceNames);
326
348
  config = parse(content) as WranglerConfig;
327
349
 
328
350
  content = provisionSecretStore(content, config, created);
@@ -54,8 +54,9 @@ export const DEFAULT_WORKER_NAME = process.env['WRANGLER_WORKER_NAME'] ?? 'my-wo
54
54
  /**
55
55
  * KV bindings a deployment always needs, and the namespace each maps to.
56
56
  *
57
- * A consumer whose worker has no cache binding passes an empty map; a consumer
58
- * with one names it here or leaves the derived `<worker>-<BINDING>` convention.
57
+ * The default for `provisionWranglerResources`'s `namespaceNames` argument: a
58
+ * consumer whose worker has no cache binding passes an empty map, and one whose
59
+ * namespaces predate this convention passes its own map.
59
60
  */
60
61
  export const DEFAULT_KV_NAMESPACE_NAMES: Record<string, string> = {
61
62
  CACHE: `${DEFAULT_WORKER_NAME}-cache`,