@harlan-zw/nuxt-cloudflare 0.0.1 → 0.0.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.
package/README.md CHANGED
@@ -7,11 +7,15 @@ The module extracts production patterns already proven in Nuxt SEO and gscdump.
7
7
  ## Defaults
8
8
 
9
9
  - Cloudflare module preset, generated Wrangler config, and Node compatibility
10
- - Static assets always bypass the Worker. Any `assets.run_worker_first` declaration fails the build and `doctor`
10
+ - Static assets remain asset first by default. Blanket `assets.run_worker_first: true` fails the build and `doctor`; narrow route-pattern arrays remain available for intentional middleware and skew recovery
11
11
  - Workers Logs sampled at 10%, traces at 1%, both overridable
12
+ - Preview URLs disabled unless explicitly enabled
13
+ - `workers_dev` disabled when a route proves the Worker remains reachable; workers without routes must choose explicitly
12
14
  - Version metadata binding at `CF_VERSION_METADATA`
15
+ - Workers Caching explicitly disabled by default; opt-in requires a version-sharing decision
13
16
  - Source-map upload when the Nitro build emits maps; explicit `false` is preserved
14
- - `secrets.required` names only, with plaintext secret-looking `vars` rejected
17
+ - Module-wide `secrets.required` names copied to each environment; source root secrets remain scoped to the root
18
+ - Version metadata is skipped when `CF_VERSION_METADATA` already names another binding
15
19
  - Raw `cloudflare-kv-binding` on Nitro's `cache` mount upgraded to a 30-day physical expiry
16
20
  - Final generated Wrangler config audited after production Nitro compiles
17
21
  - Complete defaults and diagnostics applied to every named Wrangler environment
@@ -26,6 +30,7 @@ export default defineNuxtConfig({
26
30
 
27
31
  nuxtCloudflare: {
28
32
  requiredSecrets: ['NUXT_SESSION_PASSWORD'],
33
+ workersCache: { _tag: 'enabled', crossVersion: false },
29
34
  },
30
35
 
31
36
  nitro: {
@@ -52,6 +57,8 @@ export default defineNuxtConfig({
52
57
 
53
58
  Cloudflare KV requires TTLs of at least 60 seconds.
54
59
 
60
+ Workers Caching is separate from Nitro's KV-backed cache. Enabling it lets Cloudflare serve responses without invoking the Worker. Keep `crossVersion: false` for deploy isolation; choose `true` only when stale responses across deployments are acceptable and a purge path exists. An authored `nitro.cloudflare.wrangler.cache` block is preserved unless `nuxtCloudflare.workersCache` is set.
61
+
55
62
  ## Doctor
56
63
 
57
64
  Audit Wrangler's effective configuration, including generated config redirects and named environments:
@@ -59,20 +66,40 @@ Audit Wrangler's effective configuration, including generated config redirects a
59
66
  ```sh
60
67
  pnpm nuxt-cloudflare doctor
61
68
  pnpm nuxt-cloudflare doctor --env production --json
69
+ pnpm nuxt-cloudflare doctor --strict --allow-warning source-maps-disabled
62
70
  ```
63
71
 
64
- Errors include worker-first assets, missing `nodejs_compat`, malformed compatibility dates, and secret-looking plaintext variables. Diagnostics report secret names only.
72
+ The CLI reads Wrangler config through Wrangler itself, so JSON, JSONC, TOML, environments, upward lookup, and Nitro generated-config redirects follow deployment semantics. It separately inspects root authoring format. Existing TOML remains supported and receives non-blocking guidance because Cloudflare recommends JSONC for new projects. Shadowed root configs warn because they can silently drift.
73
+
74
+ Errors cover blanket Worker-first assets, malformed selective asset patterns, missing `nodejs_compat`, malformed compatibility dates, secret names duplicated across `vars` and `secrets.required`, queue platform-limit violations, and unflattened generated environments. Warnings cover secret-looking variable names, telemetry gaps, stale dates, implicit or cross-version Workers Caching, `keep_vars`, public endpoints, preview URLs, missing DLQs, and project policy. Secret values are never included.
75
+
76
+ Normal mode fails errors. `--strict` also fails warnings. Intentional exceptions remain visible and may be listed with `--allow-warning`. Module builds use the equivalent policy:
77
+
78
+ `nodejs_compat` is required by default because this is a Nuxt module. Use `--node-compat ignore` only when auditing a non-Nuxt companion Worker, such as a redirect-only Worker.
79
+
80
+ ```ts
81
+ export default defineNuxtConfig({
82
+ nuxtCloudflare: {
83
+ doctor: {
84
+ _tag: 'strict',
85
+ allowedWarnings: ['source-maps-disabled'],
86
+ },
87
+ },
88
+ })
89
+ ```
65
90
 
66
91
  Recommended CI sequence:
67
92
 
68
93
  ```sh
69
94
  pnpm nuxt build
70
- pnpm nuxt-cloudflare doctor
71
- pnpm wrangler types --check
72
- pnpm wrangler deploy --strict --dry-run --outdir .wrangler-dist
73
- pnpm wrangler check startup
95
+ pnpm nuxt-cloudflare doctor --strict
96
+ pnpm wrangler types --check --config .output/server/wrangler.json
97
+ pnpm wrangler deploy --strict --dry-run --config .output/server/wrangler.json --outdir .wrangler-dist
98
+ pnpm wrangler check startup --config .output/server/wrangler.json
74
99
  ```
75
100
 
101
+ Pass the final generated config explicitly to `types` and `check startup`; Nitro's `.wrangler/deploy/config.json` redirect does not apply to those commands.
102
+
76
103
  ## Runtime primitives
77
104
 
78
105
  ### D1 sessions and safe retries
@@ -90,6 +117,29 @@ await retryIdempotentD1Write({
90
117
 
91
118
  One `first-primary` session is cached per request and binding. D1 already retries read-only queries. Write retries require an explicit safety tag. `lock-only` retries SQLite lock contention; `replay-safe` also permits classified transient network and reset failures.
92
119
 
120
+ ### D1 parameter plans
121
+
122
+ ```ts
123
+ import {
124
+ assertD1BoundParameters,
125
+ chunkD1Items,
126
+ defineD1ParameterPlan,
127
+ } from '@harlan-zw/nuxt-cloudflare/d1'
128
+
129
+ const siteIdPlan = defineD1ParameterPlan({
130
+ parametersPerItem: 1,
131
+ reservedParameters: 2,
132
+ })
133
+
134
+ for (const ids of chunkD1Items(siteIds, siteIdPlan)) {
135
+ const query = db.select().from(sites).where(inArray(sites.id, ids))
136
+ assertD1BoundParameters(query.toSQL().params)
137
+ await query
138
+ }
139
+ ```
140
+
141
+ D1 allows 100 bound parameters per statement, including each statement inside `db.batch()`. The parsed opaque plan rejects fractions, non-finite values, negative reservations, forged runtime plans, and budgets that cannot fit one item. `parametersPerItem` supports multi-row inserts; `reservedParameters` accounts for fixed binds and deliberate headroom. `assertD1BoundParameters` verifies the final ORM output in regression tests. Chunk execution, ordering, transaction boundaries, and result merging remain explicit at the call site.
142
+
93
143
  ### Bindings
94
144
 
95
145
  ```ts
@@ -2,14 +2,55 @@
2
2
  import process from 'node:process';
3
3
  import { defineCommand, runMain } from 'citty';
4
4
  import { resolve, dirname } from 'pathe';
5
+ import { d as discoverWranglerSourceConfigs, a as diagnoseWranglerSourceConfigs, p as parseWranglerAllowedWarnings, e as evaluateWranglerDiagnostics } from '../shared/nuxt-cloudflare.6X-qzF_b.mjs';
5
6
  import { diagnoseWranglerConfig, formatWranglerDiagnostics } from '../wrangler.mjs';
6
7
  import { existsSync, readFileSync } from 'node:fs';
7
8
  import { unstable_readConfig } from 'wrangler';
8
9
  import 'node:fs/promises';
9
10
 
11
+ function errorMessage(error) {
12
+ return error instanceof Error ? error.message : String(error);
13
+ }
14
+ function attempt(run) {
15
+ try {
16
+ return { _tag: "loaded", value: run() };
17
+ } catch (error) {
18
+ return { _tag: "invalid", reason: errorMessage(error) };
19
+ }
20
+ }
21
+ function findUpFile(cwd, relativePath) {
22
+ let directory = resolve(cwd);
23
+ while (true) {
24
+ const candidate = resolve(directory, relativePath);
25
+ if (existsSync(candidate))
26
+ return candidate;
27
+ const parent = dirname(directory);
28
+ if (parent === directory)
29
+ return void 0;
30
+ directory = parent;
31
+ }
32
+ }
33
+ function findUpWranglerConfig(cwd) {
34
+ let directory = resolve(cwd);
35
+ while (true) {
36
+ for (const name of ["wrangler.json", "wrangler.jsonc", "wrangler.toml"]) {
37
+ const candidate = resolve(directory, name);
38
+ if (existsSync(candidate))
39
+ return candidate;
40
+ }
41
+ const parent = dirname(directory);
42
+ if (parent === directory)
43
+ return void 0;
44
+ directory = parent;
45
+ }
46
+ }
10
47
  function resolveNitroDeployConfig(cwd) {
11
- const redirectPath = resolve(cwd, ".wrangler/deploy/config.json");
12
- if (!existsSync(redirectPath))
48
+ const redirectPath = findUpFile(cwd, ".wrangler/deploy/config.json");
49
+ if (!redirectPath)
50
+ return void 0;
51
+ const redirectProjectDirectory = dirname(dirname(dirname(redirectPath)));
52
+ const authoredConfigPath = findUpWranglerConfig(cwd);
53
+ if (authoredConfigPath && dirname(authoredConfigPath) !== redirectProjectDirectory)
13
54
  return void 0;
14
55
  const parsed = JSON.parse(readFileSync(redirectPath, "utf8"));
15
56
  if (!parsed || typeof parsed !== "object" || !("configPath" in parsed) || typeof parsed.configPath !== "string")
@@ -17,18 +58,75 @@ function resolveNitroDeployConfig(cwd) {
17
58
  return resolve(dirname(redirectPath), parsed.configPath);
18
59
  }
19
60
  function readProjectWranglerConfig(options) {
20
- const configPath = options.config ? resolve(options.cwd, options.config) : resolveNitroDeployConfig(options.cwd);
21
- const config = unstable_readConfig({
61
+ const redirect = attempt(() => options.config ? void 0 : resolveNitroDeployConfig(options.cwd));
62
+ if (redirect._tag === "invalid") {
63
+ return {
64
+ _tag: "invalid",
65
+ generated: false,
66
+ path: findUpFile(options.cwd, ".wrangler/deploy/config.json") ?? resolve(options.cwd, ".wrangler/deploy/config.json"),
67
+ reason: redirect.reason
68
+ };
69
+ }
70
+ const generatedConfigPath = redirect.value;
71
+ const configPath = options.config ? resolve(options.cwd, options.config) : generatedConfigPath;
72
+ const loaded = attempt(() => unstable_readConfig({
22
73
  config: configPath,
23
74
  env: options.environment,
24
75
  script: resolve(options.cwd, "__nuxt-cloudflare-doctor.mjs")
25
76
  }, {
26
77
  hideWarnings: true,
27
78
  useRedirectIfAvailable: false
28
- });
79
+ }));
80
+ if (loaded._tag === "invalid") {
81
+ return {
82
+ _tag: "invalid",
83
+ generated: generatedConfigPath !== void 0,
84
+ path: configPath,
85
+ reason: loaded.reason
86
+ };
87
+ }
88
+ return {
89
+ _tag: "loaded",
90
+ config: loaded.value,
91
+ generated: generatedConfigPath !== void 0,
92
+ path: loaded.value.configPath
93
+ };
94
+ }
95
+
96
+ function diagnoseWranglerProject(options) {
97
+ const sourceConfigPaths = discoverWranglerSourceConfigs(options.cwd, options.config);
98
+ const loaded = readProjectWranglerConfig(options);
99
+ if (loaded._tag === "invalid") {
100
+ return {
101
+ configPath: loaded.path,
102
+ diagnostics: [{
103
+ _tag: "error",
104
+ code: "wrangler-config-unreadable",
105
+ message: "Wrangler could not read the effective config. Build Nuxt again or run Wrangler locally for validation details.",
106
+ sourcePath: loaded.path ?? "wrangler config"
107
+ }, ...diagnoseWranglerSourceConfigs(sourceConfigPaths)],
108
+ sourceConfigPaths
109
+ };
110
+ }
111
+ if (!loaded.path && sourceConfigPaths.length === 0) {
112
+ return {
113
+ configPath: void 0,
114
+ diagnostics: [{
115
+ _tag: "error",
116
+ code: "wrangler-config-missing",
117
+ message: "No authored or generated Wrangler config exists. Build Nuxt before running doctor.",
118
+ sourcePath: options.cwd
119
+ }],
120
+ sourceConfigPaths
121
+ };
122
+ }
29
123
  return {
30
- config,
31
- path: config.configPath
124
+ configPath: loaded.path,
125
+ diagnostics: [
126
+ ...diagnoseWranglerConfig(loaded.config, { ...options, generated: loaded.generated }),
127
+ ...diagnoseWranglerSourceConfigs(sourceConfigPaths)
128
+ ],
129
+ sourceConfigPaths
32
130
  };
33
131
  }
34
132
 
@@ -39,32 +137,57 @@ const doctor = defineCommand({
39
137
  "config": { type: "string", description: "Wrangler config path" },
40
138
  "env": { type: "string", description: "Wrangler environment" },
41
139
  "json": { type: "boolean", description: "Print JSON diagnostics", default: false },
42
- "max-compatibility-age": { type: "string", description: "Compatibility date policy in days", default: "90" }
140
+ "max-compatibility-age": { type: "string", description: "Compatibility date policy in days", default: "90" },
141
+ "node-compat": { type: "string", description: "Node compatibility policy: required or ignore", default: "required" },
142
+ "public-var": { type: "string", description: "Comma-separated public var names exempt from secret-name heuristics" },
143
+ "strict": { type: "boolean", description: "Fail on warnings as well as errors", default: false },
144
+ "allow-warning": { type: "string", description: "Comma-separated warning codes allowed in strict mode" }
43
145
  },
44
146
  run({ args }) {
45
147
  const cwd = resolve(args.cwd);
46
- const loaded = readProjectWranglerConfig({ cwd, config: args.config, environment: args.env });
47
- const diagnostics = diagnoseWranglerConfig(loaded.config, {
48
- compatibilityMaxAgeDays: Number(args["max-compatibility-age"])
148
+ const compatibilityMaxAgeDays = Number(args["max-compatibility-age"]);
149
+ if (!Number.isSafeInteger(compatibilityMaxAgeDays) || compatibilityMaxAgeDays < 1)
150
+ throw new TypeError("--max-compatibility-age must be a positive integer");
151
+ if (args["node-compat"] !== "required" && args["node-compat"] !== "ignore")
152
+ throw new TypeError("--node-compat must be required or ignore");
153
+ const publicVarNames = args["public-var"]?.split(",").map((value) => value.trim()).filter(Boolean);
154
+ const result = diagnoseWranglerProject({
155
+ cwd,
156
+ config: args.config,
157
+ environment: args.env,
158
+ compatibilityMaxAgeDays,
159
+ publicVarNames,
160
+ requireNodeCompat: args["node-compat"] === "required"
49
161
  });
50
- const payload = { configPath: loaded.path, diagnostics };
162
+ const allowedWarnings = parseWranglerAllowedWarnings(args["allow-warning"]);
163
+ const policy = args.strict ? { _tag: "strict", allowedWarnings } : { _tag: "advisory" };
164
+ const outcome = evaluateWranglerDiagnostics(result.diagnostics, policy);
165
+ const payload = {
166
+ configPath: result.configPath,
167
+ diagnostics: result.diagnostics,
168
+ outcome: outcome._tag,
169
+ ...outcome._tag === "failed" ? { reason: outcome.reason } : {},
170
+ schemaVersion: outcome.schemaVersion,
171
+ sourceConfigPaths: result.sourceConfigPaths,
172
+ strict: args.strict
173
+ };
51
174
  if (args.json)
52
175
  process.stdout.write(`${JSON.stringify(payload, null, 2)}
53
176
  `);
54
- else if (diagnostics.length === 0)
55
- process.stdout.write(`Cloudflare config valid: ${loaded.path ?? "inline/default"}
177
+ else if (result.diagnostics.length === 0)
178
+ process.stdout.write(`Cloudflare config valid: ${result.configPath ?? "inline/default"}
56
179
  `);
57
180
  else
58
- process.stdout.write(`${formatWranglerDiagnostics(diagnostics)}
181
+ process.stdout.write(`${formatWranglerDiagnostics(result.diagnostics)}
59
182
  `);
60
- if (diagnostics.some((diagnostic) => diagnostic._tag === "error"))
183
+ if (outcome._tag === "failed")
61
184
  process.exitCode = 1;
62
185
  }
63
186
  });
64
187
  const main = defineCommand({
65
188
  meta: {
66
189
  name: "nuxt-cloudflare",
67
- version: "0.0.1",
190
+ version: "0.0.2",
68
191
  description: "Cloudflare deployment defaults and diagnostics for Nuxt"
69
192
  },
70
193
  subCommands: { doctor }
package/dist/d1.d.mts CHANGED
@@ -3,6 +3,18 @@ type D1WriteSafety = {
3
3
  } | {
4
4
  _tag: 'replay-safe';
5
5
  };
6
+ declare const D1_MAX_BOUND_PARAMETERS = 100;
7
+ declare const D1_PARAMETER_PLAN: unique symbol;
8
+ interface D1ParameterPlanInput {
9
+ parametersPerItem: number;
10
+ reservedParameters: number;
11
+ }
12
+ interface D1ParameterPlan {
13
+ readonly [D1_PARAMETER_PLAN]: true;
14
+ readonly itemsPerStatement: number;
15
+ readonly parametersPerItem: number;
16
+ readonly reservedParameters: number;
17
+ }
6
18
  type D1Consistency = {
7
19
  _tag: 'first-primary';
8
20
  } | {
@@ -28,10 +40,13 @@ type D1RetryErrorKind = {
28
40
  } | {
29
41
  _tag: 'permanent';
30
42
  };
43
+ declare function defineD1ParameterPlan(input: D1ParameterPlanInput): D1ParameterPlan;
44
+ declare function chunkD1Items<T>(items: readonly T[], plan: D1ParameterPlan): T[][];
45
+ declare function assertD1BoundParameters(parameters: readonly unknown[]): void;
31
46
  declare function classifyD1RetryError(error: unknown): D1RetryErrorKind;
32
47
  declare function isTransientD1Error(error: unknown): boolean;
33
48
  declare function getRequestD1Session<Session>(requestContext: Record<PropertyKey, unknown>, binding: string, database: D1SessionSource<Session>, consistency?: D1Consistency): Session;
34
49
  declare function retryIdempotentD1Write<T>(options: RetryIdempotentD1WriteOptions<T>): Promise<T>;
35
50
 
36
- export { classifyD1RetryError, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
37
- export type { D1Consistency, D1RetryErrorKind, D1SessionSource, D1WriteSafety, RetryIdempotentD1WriteOptions };
51
+ export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
52
+ export type { D1Consistency, D1ParameterPlan, D1ParameterPlanInput, D1RetryErrorKind, D1SessionSource, D1WriteSafety, RetryIdempotentD1WriteOptions };
package/dist/d1.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ const D1_MAX_BOUND_PARAMETERS = 100;
2
+ const D1_PARAMETER_PLAN = Symbol("@harlan-zw/nuxt-cloudflare:d1-parameter-plan");
1
3
  const REQUEST_D1_SESSIONS = Symbol.for("@harlan-zw/nuxt-cloudflare:d1-sessions");
2
4
  const TRANSIENT_D1_SIGNALS = [
3
5
  "Network connection lost",
@@ -28,12 +30,73 @@ function parseMaxAttempts(value) {
28
30
  throw new TypeError("D1 maxAttempts must be a positive integer");
29
31
  return attempts;
30
32
  }
33
+ function parseParameterCount(name, value, minimum) {
34
+ if (!Number.isSafeInteger(value) || value < minimum)
35
+ throw new TypeError(`D1 ${name} must be an integer greater than or equal to ${minimum}`);
36
+ return value;
37
+ }
38
+ function defineD1ParameterPlan(input) {
39
+ const parametersPerItem = parseParameterCount("parametersPerItem", input.parametersPerItem, 1);
40
+ const reservedParameters = parseParameterCount(
41
+ "reservedParameters",
42
+ input.reservedParameters,
43
+ 0
44
+ );
45
+ const itemsPerStatement = Math.floor(
46
+ (D1_MAX_BOUND_PARAMETERS - reservedParameters) / parametersPerItem
47
+ );
48
+ if (itemsPerStatement < 1)
49
+ throw new TypeError("D1 parameter budget cannot fit one item");
50
+ return Object.freeze({
51
+ [D1_PARAMETER_PLAN]: true,
52
+ itemsPerStatement,
53
+ parametersPerItem,
54
+ reservedParameters
55
+ });
56
+ }
57
+ function chunkD1Items(items, plan) {
58
+ if (plan?.[D1_PARAMETER_PLAN] !== true)
59
+ throw new TypeError("D1 parameter plan must come from defineD1ParameterPlan");
60
+ const chunks = [];
61
+ for (let index = 0; index < items.length; index += plan.itemsPerStatement)
62
+ chunks.push(items.slice(index, index + plan.itemsPerStatement));
63
+ return chunks;
64
+ }
65
+ function assertD1BoundParameters(parameters) {
66
+ if (!Array.isArray(parameters))
67
+ throw new TypeError("D1 bound parameters must be an array");
68
+ if (parameters.length > D1_MAX_BOUND_PARAMETERS) {
69
+ throw new RangeError(
70
+ `D1 statement has ${parameters.length} bound parameters; maximum is ${D1_MAX_BOUND_PARAMETERS}`
71
+ );
72
+ }
73
+ }
31
74
  function classifyD1RetryError(error) {
32
- const message = error instanceof Error ? error.message : String(error);
33
- if (/busy|locked/i.test(message))
75
+ const messages = [];
76
+ const seen = /* @__PURE__ */ new WeakSet();
77
+ let current = error;
78
+ while (current !== void 0 && current !== null) {
79
+ if (typeof current !== "object") {
80
+ messages.push(String(current));
81
+ break;
82
+ }
83
+ if (seen.has(current))
84
+ break;
85
+ seen.add(current);
86
+ if (current instanceof Error)
87
+ messages.push(current.message);
88
+ else if ("message" in current && typeof current.message === "string")
89
+ messages.push(current.message);
90
+ current = "cause" in current ? current.cause : void 0;
91
+ }
92
+ if (messages.some((message) => /busy|locked/i.test(message)))
34
93
  return { _tag: "lock" };
35
- if (TRANSIENT_D1_SIGNALS.some((signal) => message.includes(signal)))
94
+ if (messages.some((message) => {
95
+ const normalized = message.toLowerCase();
96
+ return TRANSIENT_D1_SIGNALS.some((signal) => normalized.includes(signal.toLowerCase()));
97
+ })) {
36
98
  return { _tag: "transient" };
99
+ }
37
100
  return { _tag: "permanent" };
38
101
  }
39
102
  function isTransientD1Error(error) {
@@ -57,7 +120,7 @@ async function retryIdempotentD1Write(options) {
57
120
  const sleep = options.sleep ?? defaultSleep;
58
121
  let lastError;
59
122
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
60
- const outcome = await options.run().then(
123
+ const outcome = await Promise.resolve().then(options.run).then(
61
124
  (value) => ({ _tag: "ok", value }),
62
125
  (error) => ({ _tag: "error", error })
63
126
  );
@@ -73,4 +136,4 @@ async function retryIdempotentD1Write(options) {
73
136
  throw lastError;
74
137
  }
75
138
 
76
- export { classifyD1RetryError, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
139
+ export { D1_MAX_BOUND_PARAMETERS, assertD1BoundParameters, chunkD1Items, classifyD1RetryError, defineD1ParameterPlan, getRequestD1Session, isTransientD1Error, retryIdempotentD1Write };
package/dist/module.d.mts CHANGED
@@ -1,10 +1,18 @@
1
- import { WranglerConfigInput } from './wrangler.mjs';
1
+ import { WranglerDiagnosticCode, WorkersCachePolicy, WranglerConfigInput } from './wrangler.mjs';
2
2
  import { Nuxt } from '@nuxt/schema';
3
3
 
4
+ type WranglerDiagnosticPolicy = {
5
+ _tag: 'advisory';
6
+ } | {
7
+ _tag: 'strict';
8
+ allowedWarnings?: readonly WranglerDiagnosticCode[];
9
+ };
10
+
4
11
  interface ModuleOptions {
5
12
  enabled?: boolean;
6
13
  compatibilityDate?: string;
7
14
  compatibilityMaxAgeDays?: number;
15
+ doctor?: WranglerDiagnosticPolicy;
8
16
  kvCache?: false | {
9
17
  binding: string;
10
18
  defaultTtl?: number;
@@ -15,6 +23,7 @@ interface ModuleOptions {
15
23
  sourceMaps?: boolean;
16
24
  tracesSampleRate?: number;
17
25
  versionMetadataBinding?: string;
26
+ workersCache?: WorkersCachePolicy;
18
27
  }
19
28
  interface NitroStorageMount extends Record<string, unknown> {
20
29
  driver?: unknown;
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.5.0"
6
6
  },
7
- "version": "0.0.1",
7
+ "version": "0.0.2",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  import { useLogger, defineNuxtModule } from '@nuxt/kit';
2
2
  import { resolve } from 'pathe';
3
+ import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
3
4
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, applyCloudflareDefaults } from './wrangler.mjs';
5
+ import 'node:fs';
4
6
  import 'node:fs/promises';
5
7
 
6
8
  const logger = useLogger("nuxt-cloudflare");
@@ -16,7 +18,8 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
16
18
  requiredSecrets: options.requiredSecrets,
17
19
  tracesSampleRate: options.tracesSampleRate,
18
20
  uploadSourceMaps: options.sourceMaps ?? nitro.sourceMap ?? nuxtServerSourceMaps ?? false,
19
- versionMetadataBinding: options.versionMetadataBinding
21
+ versionMetadataBinding: options.versionMetadataBinding,
22
+ workersCache: options.workersCache
20
23
  });
21
24
  if (options.kvCache === false)
22
25
  return;
@@ -32,24 +35,33 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
32
35
  defaultTtl: configuredCache?.defaultTtl ?? 30 * 24 * 60 * 60
33
36
  };
34
37
  }
35
- async function auditGeneratedWranglerConfig(nitro, options) {
38
+ async function auditGeneratedWranglerConfig(nitro, options, rootDir) {
36
39
  const path = resolve(nitro.options.output.serverDir, "wrangler.json");
37
40
  const result = await readWranglerJsonFile(path);
38
41
  if (result._tag === "missing")
39
42
  throw new Error(`[nuxt-cloudflare] Generated Wrangler config is missing: ${path}`);
40
43
  if (result._tag === "invalid")
41
44
  throw new Error(`[nuxt-cloudflare] Generated Wrangler config is invalid: ${result.reason}`);
42
- const diagnostics = diagnoseWranglerConfig(result.config, {
43
- compatibilityMaxAgeDays: options.compatibilityMaxAgeDays,
44
- publicVarNames: options.publicVarNames
45
- });
46
- const warnings = diagnostics.filter((diagnostic) => diagnostic._tag === "warning");
47
- const errors = diagnostics.filter((diagnostic) => diagnostic._tag === "error");
45
+ const diagnostics = [
46
+ ...diagnoseWranglerConfig(result.config, {
47
+ compatibilityMaxAgeDays: options.compatibilityMaxAgeDays,
48
+ generated: true,
49
+ publicVarNames: options.publicVarNames
50
+ }),
51
+ ...diagnoseWranglerSourceConfigs(discoverWranglerSourceConfigs(rootDir))
52
+ ];
53
+ const policy = options.doctor ?? { _tag: "advisory" };
54
+ const outcome = evaluateWranglerDiagnostics(diagnostics, policy);
55
+ const blocking = new Set(outcome.blockingDiagnostics);
56
+ const warnings = diagnostics.filter((diagnostic) => diagnostic._tag === "warning" && !blocking.has(diagnostic));
57
+ const information = diagnostics.filter((diagnostic) => diagnostic._tag === "info");
58
+ if (information.length > 0)
59
+ logger.info(formatWranglerDiagnostics(information));
48
60
  if (warnings.length > 0)
49
61
  logger.warn(formatWranglerDiagnostics(warnings));
50
- if (errors.length > 0)
62
+ if (outcome._tag === "failed")
51
63
  throw new Error(`[nuxt-cloudflare]
52
- ${formatWranglerDiagnostics(errors)}`);
64
+ ${formatWranglerDiagnostics(outcome.blockingDiagnostics)}`);
53
65
  }
54
66
  function setupCloudflareModule(options, nuxt) {
55
67
  if (!options.enabled)
@@ -65,7 +77,7 @@ function setupCloudflareModule(options, nuxt) {
65
77
  });
66
78
  if (!nuxt.options.dev) {
67
79
  nuxt.hook("nitro:init", (nitro) => {
68
- nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(nitro, options));
80
+ nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(nitro, options, nuxt.options.rootDir));
69
81
  });
70
82
  }
71
83
  }
@@ -78,6 +90,7 @@ const module$1 = defineNuxtModule({
78
90
  defaults: {
79
91
  enabled: true,
80
92
  compatibilityMaxAgeDays: 90,
93
+ doctor: { _tag: "advisory" },
81
94
  logsSampleRate: 0.1,
82
95
  tracesSampleRate: 0.01,
83
96
  versionMetadataBinding: "CF_VERSION_METADATA"
@@ -0,0 +1,77 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { resolve, dirname, extname } from 'pathe';
3
+ import { WRANGLER_DIAGNOSTIC_CODES } from '../wrangler.mjs';
4
+
5
+ const WRANGLER_SOURCE_CONFIG_NAMES = [
6
+ "wrangler.json",
7
+ "wrangler.jsonc",
8
+ "wrangler.toml"
9
+ ];
10
+ function discoverWranglerSourceConfigs(cwd, explicitConfig) {
11
+ if (explicitConfig) {
12
+ const path = resolve(cwd, explicitConfig);
13
+ return existsSync(path) ? [path] : [];
14
+ }
15
+ let directory = resolve(cwd);
16
+ while (true) {
17
+ const paths = WRANGLER_SOURCE_CONFIG_NAMES.map((name) => resolve(directory, name)).filter((path) => existsSync(path));
18
+ if (paths.length > 0)
19
+ return paths;
20
+ const parent = dirname(directory);
21
+ if (parent === directory)
22
+ return [];
23
+ directory = parent;
24
+ }
25
+ }
26
+ function diagnoseWranglerSourceConfigs(paths) {
27
+ const diagnostics = paths.flatMap((path) => extname(path) === ".toml" ? [{
28
+ _tag: "info",
29
+ code: "wrangler-jsonc-preferred",
30
+ message: "Cloudflare recommends wrangler.jsonc for new projects; TOML remains supported.",
31
+ sourcePath: path
32
+ }] : []);
33
+ if (paths.length > 1) {
34
+ diagnostics.push({
35
+ _tag: "warning",
36
+ code: "wrangler-config-shadowed",
37
+ message: "Multiple root Wrangler configs exist. Keep one wrangler.jsonc source of truth to prevent silent precedence drift.",
38
+ sourcePath: paths[0]
39
+ });
40
+ }
41
+ return diagnostics;
42
+ }
43
+ function isWranglerDiagnosticBlocking(diagnostic, policy) {
44
+ if (diagnostic._tag === "error")
45
+ return true;
46
+ return diagnostic._tag === "warning" && policy._tag === "strict" && !new Set(policy.allowedWarnings ?? []).has(diagnostic.code);
47
+ }
48
+ function parseWranglerAllowedWarnings(value) {
49
+ if (!value)
50
+ return [];
51
+ const knownCodes = new Set(WRANGLER_DIAGNOSTIC_CODES);
52
+ return value.split(",").map((part) => part.trim()).filter(Boolean).map((code) => {
53
+ if (!knownCodes.has(code))
54
+ throw new TypeError(`Unknown Wrangler diagnostic code: ${code}`);
55
+ return code;
56
+ });
57
+ }
58
+ function evaluateWranglerDiagnostics(diagnostics, policy) {
59
+ const blockingDiagnostics = diagnostics.filter((diagnostic) => isWranglerDiagnosticBlocking(diagnostic, policy));
60
+ if (blockingDiagnostics.length === 0) {
61
+ return {
62
+ _tag: "passed",
63
+ blockingDiagnostics: [],
64
+ diagnostics,
65
+ schemaVersion: 1
66
+ };
67
+ }
68
+ return {
69
+ _tag: "failed",
70
+ blockingDiagnostics,
71
+ diagnostics,
72
+ reason: blockingDiagnostics.some((diagnostic) => diagnostic._tag === "error") ? "errors" : "strict-warnings",
73
+ schemaVersion: 1
74
+ };
75
+ }
76
+
77
+ export { diagnoseWranglerSourceConfigs as a, discoverWranglerSourceConfigs as d, evaluateWranglerDiagnostics as e, parseWranglerAllowedWarnings as p };
@@ -3,6 +3,16 @@ interface WranglerAssetsInput {
3
3
  binding?: string;
4
4
  run_worker_first?: boolean | string[];
5
5
  }
6
+ interface WranglerWorkersCacheInput {
7
+ enabled: boolean;
8
+ cross_version_cache?: boolean;
9
+ }
10
+ type WorkersCachePolicy = {
11
+ _tag: 'disabled';
12
+ } | {
13
+ _tag: 'enabled';
14
+ crossVersion: boolean;
15
+ };
6
16
  interface WranglerObservabilityInput {
7
17
  enabled?: boolean;
8
18
  head_sampling_rate?: number;
@@ -18,13 +28,19 @@ interface WranglerObservabilityInput {
18
28
  }
19
29
  interface WranglerConfigInput extends Record<string, unknown> {
20
30
  assets?: WranglerAssetsInput;
31
+ cache?: WranglerWorkersCacheInput;
21
32
  compatibility_date?: string;
22
33
  compatibility_flags?: string[];
23
34
  env?: Record<string, WranglerConfigInput>;
35
+ keep_vars?: boolean;
24
36
  observability?: WranglerObservabilityInput;
37
+ preview_urls?: boolean;
25
38
  queues?: {
26
39
  consumers?: Array<Record<string, unknown>>;
40
+ producers?: Array<Record<string, unknown>>;
27
41
  };
42
+ route?: string | Record<string, unknown>;
43
+ routes?: Array<string | Record<string, unknown>>;
28
44
  secrets?: {
29
45
  required?: string[];
30
46
  };
@@ -42,17 +58,23 @@ interface CloudflareDefaultOptions {
42
58
  tracesSampleRate?: number;
43
59
  uploadSourceMaps?: boolean;
44
60
  versionMetadataBinding?: string;
61
+ workersCache?: WorkersCachePolicy;
45
62
  }
63
+ declare const WRANGLER_DIAGNOSTIC_CODES: readonly ["assets-worker-first", "assets-worker-first-pattern-invalid", "compatibility-date-missing", "compatibility-date-invalid", "durable-object-binding-inactive", "durable-object-lifecycle-mixed", "durable-object-lifecycle-unmanaged", "generated-config-has-env", "keep-vars-enabled", "missing-nodejs-compat", "nodejs-compat-version-implicit", "observability-disabled", "observability-sampling-implicit", "observability-sampling-out-of-range", "plaintext-secret-var", "preview-urls-public", "queue-dlq-missing", "queue-retries-above-policy", "queue-retries-out-of-range", "queue-retry-delay-out-of-range", "secret-declared-as-var", "source-maps-disabled", "stale-compatibility-date", "traces-disabled", "version-metadata-missing", "workers-dev-enabled", "workers-dev-implicit", "workers-cache-cross-version-enabled", "workers-cache-policy-implicit", "wrangler-config-shadowed", "wrangler-config-missing", "wrangler-config-unreadable", "wrangler-jsonc-preferred"];
64
+ type WranglerDiagnosticCode = typeof WRANGLER_DIAGNOSTIC_CODES[number];
46
65
  interface WranglerDiagnostic {
47
- _tag: 'error' | 'warning';
48
- code: 'assets-worker-first' | 'compatibility-date-missing' | 'compatibility-date-invalid' | 'missing-nodejs-compat' | 'observability-disabled' | 'plaintext-secret-var' | 'queue-retries-excessive' | 'secret-declared-as-var' | 'source-maps-disabled' | 'stale-compatibility-date' | 'version-metadata-missing' | 'workers-dev-enabled';
66
+ _tag: 'error' | 'info' | 'warning';
67
+ code: WranglerDiagnosticCode;
49
68
  message: string;
50
- path: string;
69
+ configPath?: string;
70
+ sourcePath?: string;
51
71
  }
52
72
  interface WranglerDiagnosticOptions {
53
73
  compatibilityMaxAgeDays?: number;
74
+ generated?: boolean;
54
75
  now?: Date;
55
76
  publicVarNames?: readonly string[];
77
+ requireNodeCompat?: boolean;
56
78
  }
57
79
  type WranglerJsonFileResult = {
58
80
  _tag: 'loaded';
@@ -71,5 +93,5 @@ declare function diagnoseWranglerConfig(config: WranglerConfigInput, options?: W
71
93
  declare function formatWranglerDiagnostics(diagnostics: readonly WranglerDiagnostic[]): string;
72
94
  declare function readWranglerJsonFile(path: string): Promise<WranglerJsonFileResult>;
73
95
 
74
- export { applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
75
- export type { CloudflareDefaultOptions, WranglerAssetsInput, WranglerConfigInput, WranglerDiagnostic, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput };
96
+ export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
97
+ export type { CloudflareDefaultOptions, WorkersCachePolicy, WranglerAssetsInput, WranglerConfigInput, WranglerDiagnostic, WranglerDiagnosticCode, WranglerDiagnosticOptions, WranglerJsonFileResult, WranglerObservabilityInput, WranglerWorkersCacheInput };
package/dist/wrangler.mjs CHANGED
@@ -1,8 +1,44 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
 
3
+ const WRANGLER_DIAGNOSTIC_CODES = [
4
+ "assets-worker-first",
5
+ "assets-worker-first-pattern-invalid",
6
+ "compatibility-date-missing",
7
+ "compatibility-date-invalid",
8
+ "durable-object-binding-inactive",
9
+ "durable-object-lifecycle-mixed",
10
+ "durable-object-lifecycle-unmanaged",
11
+ "generated-config-has-env",
12
+ "keep-vars-enabled",
13
+ "missing-nodejs-compat",
14
+ "nodejs-compat-version-implicit",
15
+ "observability-disabled",
16
+ "observability-sampling-implicit",
17
+ "observability-sampling-out-of-range",
18
+ "plaintext-secret-var",
19
+ "preview-urls-public",
20
+ "queue-dlq-missing",
21
+ "queue-retries-above-policy",
22
+ "queue-retries-out-of-range",
23
+ "queue-retry-delay-out-of-range",
24
+ "secret-declared-as-var",
25
+ "source-maps-disabled",
26
+ "stale-compatibility-date",
27
+ "traces-disabled",
28
+ "version-metadata-missing",
29
+ "workers-dev-enabled",
30
+ "workers-dev-implicit",
31
+ "workers-cache-cross-version-enabled",
32
+ "workers-cache-policy-implicit",
33
+ "wrangler-config-shadowed",
34
+ "wrangler-config-missing",
35
+ "wrangler-config-unreadable",
36
+ "wrangler-jsonc-preferred"
37
+ ];
3
38
  const SECRET_NAME_RE = /(?:^|_)(?:API_?KEY|AUTH_TOKEN|CLIENT_SECRET|CREDENTIALS?|DATABASE_URL|DB_URL|ENCRYPTION_KEY|KEY|PASSWORD|PRIVATE_KEY|SECRET|SIGNING_KEY|TOKEN)(?:_|$)/i;
4
39
  const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
5
40
  const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1e3;
41
+ const NODEJS_COMPAT_V2_DATE = /* @__PURE__ */ new Date("2024-09-23T00:00:00.000Z");
6
42
  function unique(values) {
7
43
  return [...new Set(values)];
8
44
  }
@@ -15,15 +51,87 @@ function parseDateOnly(value) {
15
51
  const date = /* @__PURE__ */ new Date(`${value}T00:00:00.000Z`);
16
52
  return Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== value ? void 0 : date;
17
53
  }
18
- function hasOwn(value, key) {
19
- return Object.hasOwn(value, key);
54
+ function parsedCompatibilityDateBeforeV2(value) {
55
+ const parsed = value && parseDateOnly(value);
56
+ return Boolean(parsed && parsed < NODEJS_COMPAT_V2_DATE);
57
+ }
58
+ function resolveWorkersCachePolicy(policy) {
59
+ if (policy._tag === "disabled")
60
+ return { enabled: false, cross_version_cache: false };
61
+ return { enabled: true, cross_version_cache: policy.crossVersion };
62
+ }
63
+ const WRANGLER_BINDING_CATEGORIES = [
64
+ "data_blobs",
65
+ "durable_objects",
66
+ "kv_namespaces",
67
+ "send_email",
68
+ "d1_databases",
69
+ "vectorize",
70
+ "ai_search_namespaces",
71
+ "ai_search",
72
+ "websearch",
73
+ "agent_memory",
74
+ "hyperdrive",
75
+ "r2_buckets",
76
+ "logfwdr",
77
+ "services",
78
+ "analytics_engine_datasets",
79
+ "text_blobs",
80
+ "browser",
81
+ "ai",
82
+ "images",
83
+ "stream",
84
+ "media",
85
+ "version_metadata",
86
+ "unsafe",
87
+ "vars",
88
+ "wasm_modules",
89
+ "dispatch_namespaces",
90
+ "mtls_certificates",
91
+ "workflows",
92
+ "pipelines",
93
+ "secrets_store_secrets",
94
+ "artifacts",
95
+ "ratelimits",
96
+ "assets",
97
+ "unsafe_hello_world",
98
+ "flagship"
99
+ ];
100
+ function addBindingNames(names, value) {
101
+ if (Array.isArray(value)) {
102
+ value.forEach((entry) => {
103
+ if (isRecord(entry) && typeof entry.binding === "string")
104
+ names.add(entry.binding);
105
+ });
106
+ return;
107
+ }
108
+ if (!isRecord(value))
109
+ return;
110
+ if (Array.isArray(value.bindings) && value.bindings.every((binding) => isRecord(binding) && typeof binding.name === "string")) {
111
+ value.bindings.forEach((binding) => names.add(binding.name));
112
+ return;
113
+ }
114
+ if (typeof value.binding === "string") {
115
+ names.add(value.binding);
116
+ return;
117
+ }
118
+ Object.entries(value).forEach(([name, binding]) => {
119
+ if (binding !== void 0)
120
+ names.add(name);
121
+ });
122
+ }
123
+ function collectBindingNames(config) {
124
+ const names = new Set(config.secrets?.required ?? []);
125
+ WRANGLER_BINDING_CATEGORIES.forEach((category) => addBindingNames(names, config[category]));
126
+ addBindingNames(names, config.queues?.producers);
127
+ return names;
20
128
  }
21
129
  function applyCloudflareDefaults(config, options = {}) {
22
130
  const root = applyEnvironmentDefaults(config, options);
23
131
  const environments = config.env && Object.fromEntries(
24
132
  Object.entries(config.env).map(([name, environment]) => [name, applyEnvironmentDefaults(environment, {
25
133
  ...options,
26
- requiredSecrets: root.secrets?.required
134
+ requiredSecrets: options.requiredSecrets
27
135
  }, root)])
28
136
  );
29
137
  return environments ? { ...root, env: environments } : root;
@@ -31,14 +139,21 @@ function applyCloudflareDefaults(config, options = {}) {
31
139
  function applyEnvironmentDefaults(config, options, inherited = {}) {
32
140
  const compatibilityDate = config.compatibility_date ?? inherited.compatibility_date ?? options.compatibilityDate;
33
141
  const compatibilityFlags = unique([...config.compatibility_flags ?? inherited.compatibility_flags ?? [], "nodejs_compat"]);
142
+ const cache = options.workersCache ? resolveWorkersCachePolicy(options.workersCache) : config.cache ?? inherited.cache ?? resolveWorkersCachePolicy({ _tag: "disabled" });
34
143
  const requiredSecrets = unique([...config.secrets?.required ?? [], ...options.requiredSecrets ?? []]);
35
144
  const logs = config.observability?.logs;
36
145
  const inheritedLogs = inherited.observability?.logs;
37
146
  const traces = config.observability?.traces;
38
147
  const inheritedTraces = inherited.observability?.traces;
39
148
  const uploadSourceMaps = config.upload_source_maps ?? inherited.upload_source_maps ?? options.uploadSourceMaps ?? true;
149
+ const previewUrls = config.preview_urls ?? inherited.preview_urls ?? false;
150
+ const workersDev = config.workers_dev ?? inherited.workers_dev ?? (config.route !== void 0 || (config.routes?.length ?? 0) > 0 ? false : void 0);
151
+ const versionMetadataBinding = options.versionMetadataBinding ?? "CF_VERSION_METADATA";
152
+ const localBindingNames = collectBindingNames(config);
153
+ const versionMetadata = config.version_metadata ?? (inherited.version_metadata && !localBindingNames.has(inherited.version_metadata.binding) ? inherited.version_metadata : void 0) ?? (localBindingNames.has(versionMetadataBinding) ? void 0 : { binding: versionMetadataBinding });
40
154
  return {
41
155
  ...config,
156
+ cache,
42
157
  ...compatibilityDate === void 0 ? {} : { compatibility_date: compatibilityDate },
43
158
  compatibility_flags: compatibilityFlags,
44
159
  observability: {
@@ -61,50 +176,170 @@ function applyEnvironmentDefaults(config, options, inherited = {}) {
61
176
  },
62
177
  ...requiredSecrets.length > 0 ? { secrets: { ...config.secrets, required: requiredSecrets } } : {},
63
178
  upload_source_maps: uploadSourceMaps,
64
- version_metadata: config.version_metadata ?? inherited.version_metadata ?? {
65
- binding: options.versionMetadataBinding ?? "CF_VERSION_METADATA"
66
- }
179
+ ...versionMetadata ? { version_metadata: versionMetadata } : {},
180
+ preview_urls: previewUrls,
181
+ ...workersDev === void 0 ? {} : { workers_dev: workersDev }
67
182
  };
68
183
  }
69
184
  function diagnoseEnvironment(config, prefix, diagnostics, publicVarNames) {
70
- if (config.assets && hasOwn(config.assets, "run_worker_first")) {
185
+ const workerFirst = config.assets?.run_worker_first;
186
+ if (workerFirst === true) {
71
187
  diagnostics.push({
72
188
  _tag: "error",
73
189
  code: "assets-worker-first",
74
- message: "Remove assets.run_worker_first. Static assets must bypass the Worker.",
75
- path: `${prefix}assets.run_worker_first`
190
+ message: "Replace blanket Worker-first routing with false or a narrow route-pattern array.",
191
+ configPath: `${prefix}assets.run_worker_first`
192
+ });
193
+ } else if (Array.isArray(workerFirst)) {
194
+ const invalidPatternIndex = workerFirst.findIndex(
195
+ (pattern) => typeof pattern !== "string" || !/^(?:!\/|\/)/.test(pattern)
196
+ );
197
+ if (invalidPatternIndex !== -1) {
198
+ diagnostics.push({
199
+ _tag: "error",
200
+ code: "assets-worker-first-pattern-invalid",
201
+ message: "Selective Worker-first patterns must begin with / or !/.",
202
+ configPath: `${prefix}assets.run_worker_first.${invalidPatternIndex}`
203
+ });
204
+ }
205
+ } else if (workerFirst !== void 0 && workerFirst !== false) {
206
+ diagnostics.push({
207
+ _tag: "error",
208
+ code: "assets-worker-first-pattern-invalid",
209
+ message: "assets.run_worker_first must be false or an array of route patterns.",
210
+ configPath: `${prefix}assets.run_worker_first`
211
+ });
212
+ }
213
+ const durableObjectExports = isRecord(config.exports) ? Object.entries(config.exports).filter(([, value]) => isRecord(value) && value.type === "durable-object") : [];
214
+ const migrations = Array.isArray(config.migrations) ? config.migrations : [];
215
+ if (durableObjectExports.length > 0 && migrations.length > 0) {
216
+ diagnostics.push({
217
+ _tag: "error",
218
+ code: "durable-object-lifecycle-mixed",
219
+ message: "Durable Object declarative exports and legacy migrations are mutually exclusive.",
220
+ configPath: `${prefix}exports`
221
+ });
222
+ }
223
+ const durableObjects = isRecord(config.durable_objects) ? config.durable_objects : void 0;
224
+ const bindings = Array.isArray(durableObjects?.bindings) ? durableObjects.bindings : [];
225
+ const localClassNames = bindings.flatMap((binding) => {
226
+ if (!isRecord(binding) || typeof binding.script_name === "string" || typeof binding.class_name !== "string")
227
+ return [];
228
+ return [binding.class_name];
229
+ });
230
+ const inactiveExportedClassNames = new Set(durableObjectExports.flatMap(([name, value]) => {
231
+ if (!isRecord(value) || value.state === void 0 || value.state === "created")
232
+ return [];
233
+ return [name];
234
+ }));
235
+ if (localClassNames.some((className) => inactiveExportedClassNames.has(className))) {
236
+ diagnostics.push({
237
+ _tag: "error",
238
+ code: "durable-object-binding-inactive",
239
+ message: "A Durable Object binding may target only an active declarative export with state created or omitted.",
240
+ configPath: `${prefix}durable_objects.bindings`
241
+ });
242
+ }
243
+ const exportedClassNames = new Set(durableObjectExports.map(([name]) => name));
244
+ const migratedClassNames = /* @__PURE__ */ new Set();
245
+ for (const migration of migrations) {
246
+ if (!isRecord(migration))
247
+ continue;
248
+ for (const key of ["new_classes", "new_sqlite_classes"]) {
249
+ if (Array.isArray(migration[key])) {
250
+ for (const className of migration[key]) {
251
+ if (typeof className === "string") {
252
+ migratedClassNames.add(className);
253
+ }
254
+ }
255
+ }
256
+ }
257
+ if (Array.isArray(migration.renamed_classes)) {
258
+ for (const rename of migration.renamed_classes) {
259
+ if (!isRecord(rename))
260
+ continue;
261
+ if (typeof rename.from === "string")
262
+ migratedClassNames.delete(rename.from);
263
+ if (typeof rename.to === "string")
264
+ migratedClassNames.add(rename.to);
265
+ }
266
+ }
267
+ if (Array.isArray(migration.transferred_classes)) {
268
+ for (const transfer of migration.transferred_classes) {
269
+ if (isRecord(transfer) && typeof transfer.to === "string")
270
+ migratedClassNames.add(transfer.to);
271
+ }
272
+ }
273
+ if (Array.isArray(migration.deleted_classes)) {
274
+ for (const className of migration.deleted_classes) {
275
+ if (typeof className === "string") {
276
+ migratedClassNames.delete(className);
277
+ }
278
+ }
279
+ }
280
+ }
281
+ if (localClassNames.some((className) => !exportedClassNames.has(className) && !migratedClassNames.has(className))) {
282
+ diagnostics.push({
283
+ _tag: "error",
284
+ code: "durable-object-lifecycle-unmanaged",
285
+ message: "Every locally defined Durable Object needs a declarative export or a legacy migration history.",
286
+ configPath: `${prefix}durable_objects.bindings`
76
287
  });
77
288
  }
78
289
  const requiredSecrets = new Set(config.secrets?.required ?? []);
79
290
  for (const name of Object.keys(config.vars ?? {})) {
80
- const path = `${prefix}vars.${name}`;
291
+ const configPath = `${prefix}vars.${name}`;
81
292
  if (requiredSecrets.has(name)) {
82
293
  diagnostics.push({
83
294
  _tag: "error",
84
295
  code: "secret-declared-as-var",
85
296
  message: `Remove ${name} from vars; it is declared as a required encrypted secret.`,
86
- path
297
+ configPath
87
298
  });
88
299
  continue;
89
300
  }
90
301
  if (!publicVarNames.has(name) && !/^(?:NUXT_)?PUBLIC_/i.test(name) && SECRET_NAME_RE.test(name)) {
91
302
  diagnostics.push({
92
- _tag: "error",
303
+ _tag: "warning",
93
304
  code: "plaintext-secret-var",
94
305
  message: `Move secret-looking variable ${name} to an encrypted Worker secret.`,
95
- path
306
+ configPath
96
307
  });
97
308
  }
98
309
  }
99
310
  const consumers = config.queues?.consumers ?? [];
100
311
  consumers.forEach((consumer, index) => {
101
312
  const retries = consumer.max_retries;
102
- if (typeof retries === "number" && retries > 10) {
313
+ const retryDelay = consumer.retry_delay;
314
+ if (typeof retries === "number" && (!Number.isSafeInteger(retries) || retries < 0 || retries > 100)) {
315
+ diagnostics.push({
316
+ _tag: "error",
317
+ code: "queue-retries-out-of-range",
318
+ message: "Queue consumer max_retries must be an integer between 0 and 100.",
319
+ configPath: `${prefix}queues.consumers.${index}.max_retries`
320
+ });
321
+ } else if (typeof retries === "number" && retries > 3) {
103
322
  diagnostics.push({
104
323
  _tag: "warning",
105
- code: "queue-retries-excessive",
106
- message: `Queue consumer retries ${retries} times; verify this is intentional and backed by a DLQ.`,
107
- path: `${prefix}queues.consumers.${index}.max_retries`
324
+ code: "queue-retries-above-policy",
325
+ message: `Queue consumer retries ${retries} times, above Cloudflare's default of 3. Verify the work is replay-safe.`,
326
+ configPath: `${prefix}queues.consumers.${index}.max_retries`
327
+ });
328
+ }
329
+ if (typeof consumer.dead_letter_queue !== "string" || consumer.dead_letter_queue.length === 0) {
330
+ diagnostics.push({
331
+ _tag: "warning",
332
+ code: "queue-dlq-missing",
333
+ message: "Configure a dead-letter queue or explicitly allow this warning for intentionally lossy work.",
334
+ configPath: `${prefix}queues.consumers.${index}.dead_letter_queue`
335
+ });
336
+ }
337
+ if (typeof retryDelay === "number" && (!Number.isSafeInteger(retryDelay) || retryDelay < 0 || retryDelay > 86400)) {
338
+ diagnostics.push({
339
+ _tag: "error",
340
+ code: "queue-retry-delay-out-of-range",
341
+ message: "Queue consumer retry_delay must be between 0 and 86400 seconds.",
342
+ configPath: `${prefix}queues.consumers.${index}.retry_delay`
108
343
  });
109
344
  }
110
345
  });
@@ -116,7 +351,7 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
116
351
  _tag: "error",
117
352
  code: "compatibility-date-missing",
118
353
  message: "Set an explicit compatibility_date.",
119
- path: `${prefix}compatibility_date`
354
+ configPath: `${prefix}compatibility_date`
120
355
  });
121
356
  } else {
122
357
  const parsed = parseDateOnly(compatibilityDate);
@@ -125,23 +360,31 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
125
360
  _tag: "error",
126
361
  code: "compatibility-date-invalid",
127
362
  message: "compatibility_date must be a real YYYY-MM-DD date.",
128
- path: `${prefix}compatibility_date`
363
+ configPath: `${prefix}compatibility_date`
129
364
  });
130
365
  } else if ((options.now.getTime() - parsed.getTime()) / MILLISECONDS_PER_DAY > options.compatibilityMaxAgeDays) {
131
366
  diagnostics.push({
132
367
  _tag: "warning",
133
368
  code: "stale-compatibility-date",
134
369
  message: `compatibility_date is older than the ${options.compatibilityMaxAgeDays}-day project policy. Review compatibility flags before advancing it.`,
135
- path: `${prefix}compatibility_date`
370
+ configPath: `${prefix}compatibility_date`
136
371
  });
137
372
  }
138
373
  }
139
- if (!config.compatibility_flags?.includes("nodejs_compat")) {
374
+ if (options.requireNodeCompat && !config.compatibility_flags?.includes("nodejs_compat")) {
140
375
  diagnostics.push({
141
376
  _tag: "error",
142
377
  code: "missing-nodejs-compat",
143
378
  message: "Add nodejs_compat to compatibility_flags.",
144
- path: `${prefix}compatibility_flags`
379
+ configPath: `${prefix}compatibility_flags`
380
+ });
381
+ }
382
+ if (options.requireNodeCompat && parsedCompatibilityDateBeforeV2(compatibilityDate) && config.compatibility_flags?.includes("nodejs_compat") && !config.compatibility_flags.includes("nodejs_compat_v2") && !config.compatibility_flags.includes("no_nodejs_compat_v2")) {
383
+ diagnostics.push({
384
+ _tag: "error",
385
+ code: "nodejs-compat-version-implicit",
386
+ message: "Before 2024-09-23, choose nodejs_compat_v2 or no_nodejs_compat_v2 explicitly.",
387
+ configPath: `${prefix}compatibility_flags`
145
388
  });
146
389
  }
147
390
  if (config.observability?.enabled !== true) {
@@ -149,15 +392,49 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
149
392
  _tag: "warning",
150
393
  code: "observability-disabled",
151
394
  message: "Enable Workers observability.",
152
- path: `${prefix}observability.enabled`
395
+ configPath: `${prefix}observability.enabled`
153
396
  });
397
+ } else {
398
+ const samplingRates = [
399
+ ["head_sampling_rate", config.observability.head_sampling_rate],
400
+ ["logs.head_sampling_rate", config.observability.logs?.head_sampling_rate],
401
+ ["traces.head_sampling_rate", config.observability.traces?.head_sampling_rate]
402
+ ];
403
+ for (const [path, rate] of samplingRates) {
404
+ if (rate !== void 0 && (!Number.isFinite(rate) || rate < 0 || rate > 1)) {
405
+ diagnostics.push({
406
+ _tag: "error",
407
+ code: "observability-sampling-out-of-range",
408
+ message: "Observability sampling rates must be finite numbers between 0 and 1.",
409
+ configPath: `${prefix}observability.${path}`
410
+ });
411
+ }
412
+ }
413
+ if (config.observability.traces?.enabled !== true) {
414
+ diagnostics.push({
415
+ _tag: "warning",
416
+ code: "traces-disabled",
417
+ message: "Enable Workers traces with an explicit sampling rate.",
418
+ configPath: `${prefix}observability.traces.enabled`
419
+ });
420
+ }
421
+ const logsEnabled = config.observability.logs?.enabled !== false;
422
+ const tracesEnabled = config.observability.traces?.enabled === true;
423
+ if (logsEnabled && config.observability.logs?.head_sampling_rate === void 0 || tracesEnabled && config.observability.traces?.head_sampling_rate === void 0) {
424
+ diagnostics.push({
425
+ _tag: "warning",
426
+ code: "observability-sampling-implicit",
427
+ message: "Set explicit log and trace sampling rates; enabled telemetry otherwise defaults to 100%.",
428
+ configPath: `${prefix}observability`
429
+ });
430
+ }
154
431
  }
155
432
  if (config.upload_source_maps !== true) {
156
433
  diagnostics.push({
157
434
  _tag: "warning",
158
435
  code: "source-maps-disabled",
159
436
  message: "Enable upload_source_maps when the Worker build emits source maps.",
160
- path: `${prefix}upload_source_maps`
437
+ configPath: `${prefix}upload_source_maps`
161
438
  });
162
439
  }
163
440
  if (!config.version_metadata?.binding) {
@@ -165,15 +442,53 @@ function diagnosePolicy(config, prefix, diagnostics, options, publicVarNames) {
165
442
  _tag: "warning",
166
443
  code: "version-metadata-missing",
167
444
  message: "Add a version_metadata binding for deployment correlation.",
168
- path: `${prefix}version_metadata`
445
+ configPath: `${prefix}version_metadata`
446
+ });
447
+ }
448
+ if (config.keep_vars === true) {
449
+ diagnostics.push({
450
+ _tag: "warning",
451
+ code: "keep-vars-enabled",
452
+ message: "keep_vars allows dashboard-managed plaintext variables to drift from source control.",
453
+ configPath: `${prefix}keep_vars`
454
+ });
455
+ }
456
+ if (config.cache === void 0) {
457
+ diagnostics.push({
458
+ _tag: "warning",
459
+ code: "workers-cache-policy-implicit",
460
+ message: "Choose an explicit Workers Caching policy. Headerless 200 responses are cached for two hours when enabled.",
461
+ configPath: `${prefix}cache`
462
+ });
463
+ } else if (config.cache.enabled && config.cache.cross_version_cache === true) {
464
+ diagnostics.push({
465
+ _tag: "warning",
466
+ code: "workers-cache-cross-version-enabled",
467
+ message: "Cross-version caching can serve responses from superseded deployments until expiry or purge.",
468
+ configPath: `${prefix}cache.cross_version_cache`
469
+ });
470
+ }
471
+ if (config.preview_urls === true) {
472
+ diagnostics.push({
473
+ _tag: "warning",
474
+ code: "preview-urls-public",
475
+ message: "Preview URLs are public unless protected by Access; their logs cannot be viewed through Workers Logs, tail, or Logpush.",
476
+ configPath: `${prefix}preview_urls`
169
477
  });
170
478
  }
171
479
  if (config.workers_dev === true) {
172
480
  diagnostics.push({
173
481
  _tag: "warning",
174
482
  code: "workers-dev-enabled",
175
- message: "Production workers.dev exposure is enabled; verify this is intentional.",
176
- path: `${prefix}workers_dev`
483
+ message: "The public workers.dev endpoint is enabled. Set workers_dev to false unless this is intentional.",
484
+ configPath: `${prefix}workers_dev`
485
+ });
486
+ } else if (config.workers_dev === void 0) {
487
+ diagnostics.push({
488
+ _tag: "warning",
489
+ code: "workers-dev-implicit",
490
+ message: "Set workers_dev explicitly; current Wrangler behavior and published defaults differ when routes are present.",
491
+ configPath: `${prefix}workers_dev`
177
492
  });
178
493
  }
179
494
  diagnoseEnvironment(config, prefix, diagnostics, publicVarNames);
@@ -191,9 +506,13 @@ function mergeObservability(inherited, environment) {
191
506
  function resolveEnvironmentPolicy(root, environment) {
192
507
  return {
193
508
  ...environment,
509
+ cache: environment.cache ?? root.cache,
194
510
  compatibility_date: environment.compatibility_date ?? root.compatibility_date,
195
511
  compatibility_flags: environment.compatibility_flags ?? root.compatibility_flags,
512
+ exports: environment.exports ?? root.exports,
513
+ migrations: environment.migrations ?? root.migrations,
196
514
  observability: mergeObservability(root.observability, environment.observability),
515
+ preview_urls: environment.preview_urls ?? root.preview_urls,
197
516
  upload_source_maps: environment.upload_source_maps ?? root.upload_source_maps,
198
517
  workers_dev: environment.workers_dev ?? root.workers_dev
199
518
  };
@@ -202,8 +521,17 @@ function diagnoseWranglerConfig(config, options = {}) {
202
521
  const diagnostics = [];
203
522
  const diagnosticOptions = {
204
523
  compatibilityMaxAgeDays: options.compatibilityMaxAgeDays ?? 90,
205
- now: options.now ?? /* @__PURE__ */ new Date()
524
+ now: options.now ?? /* @__PURE__ */ new Date(),
525
+ requireNodeCompat: options.requireNodeCompat ?? true
206
526
  };
527
+ if (options.generated && Object.keys(config.env ?? {}).length > 0) {
528
+ diagnostics.push({
529
+ _tag: "error",
530
+ code: "generated-config-has-env",
531
+ message: "Generated Wrangler config must target one flattened environment and contain no env block.",
532
+ configPath: "env"
533
+ });
534
+ }
207
535
  const publicVarNames = new Set(options.publicVarNames ?? []);
208
536
  diagnosePolicy(config, "", diagnostics, diagnosticOptions, publicVarNames);
209
537
  for (const [name, environment] of Object.entries(config.env ?? {})) {
@@ -218,7 +546,11 @@ function diagnoseWranglerConfig(config, options = {}) {
218
546
  return diagnostics;
219
547
  }
220
548
  function formatWranglerDiagnostics(diagnostics) {
221
- return diagnostics.map((diagnostic) => `${diagnostic._tag === "error" ? "ERROR" : "WARN"} ${diagnostic.code} ${diagnostic.path}: ${diagnostic.message}`).join("\n");
549
+ return diagnostics.map((diagnostic) => {
550
+ const location = [diagnostic.sourcePath, diagnostic.configPath].filter(Boolean).join(":");
551
+ const severity = diagnostic._tag === "error" ? "ERROR" : diagnostic._tag === "warning" ? "WARN" : "INFO";
552
+ return `${severity} ${diagnostic.code}${location ? ` ${location}` : ""}: ${diagnostic.message}`;
553
+ }).join("\n");
222
554
  }
223
555
  async function readWranglerJsonFile(path) {
224
556
  return readFile(path, "utf8").then((source) => {
@@ -241,4 +573,4 @@ async function readWranglerJsonFile(path) {
241
573
  });
242
574
  }
243
575
 
244
- export { applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
576
+ export { WRANGLER_DIAGNOSTIC_CODES, applyCloudflareDefaults, diagnoseWranglerConfig, formatWranglerDiagnostics, readWranglerJsonFile };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.0.1",
4
+ "version": "0.0.2",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",