@harlan-zw/nuxt-cloudflare 0.3.0 → 0.4.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.
package/README.md CHANGED
@@ -172,7 +172,7 @@ pnpm nuxt-cloudflare doctor --strict --allow-warning source-maps-disabled
172
172
 
173
173
  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.
174
174
 
175
- Errors cover malformed asset patterns, invalid Durable Object lifecycles, invalid Container storage, queue limits, unsafe example bindings, and unflattened generated environments. Warnings cover blanket Worker-first assets, missing environment bindings, unrestricted email, local service fidelity, deprecated fields, telemetry gaps, and public endpoints. Secret values are never included.
175
+ Errors cover `_headers` and `_redirects` files past Cloudflare's rule limits, malformed asset patterns, invalid Durable Object lifecycles, invalid Container storage, queue limits, unsafe example bindings, and unflattened generated environments. Warnings cover blanket Worker-first assets, missing environment bindings, unrestricted email, local service fidelity, deprecated fields, telemetry gaps, and public endpoints. Secret values are never included.
176
176
 
177
177
  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:
178
178
 
@@ -280,6 +280,18 @@ function apiToken(event?: H3Event) {
280
280
 
281
281
  `nuxt prepare` runs Wrangler and writes exact, compatibility-aware types to `.nuxt/types/cloudflare-bindings.d.ts`. It merges root JSON, JSONC, or TOML bindings with `nitro.cloudflare.wrangler`. Nuxt and Nitro typechecks both reference the declaration, while bindings remain server runtime values. Production builds compare it with the final generated Wrangler config and fail on drift. Set `bindingTypes: false` only when another tool owns the declaration.
282
282
 
283
+ Binding types use a shared cache under `$XDG_CACHE_HOME/nuxt-cloudflare` or `~/.cache/nuxt-cloudflare`. The cache key includes the Wrangler config and version. Each worktree still receives private `.nuxt` files. Set `cacheDir` to a shared absolute path. Set it to `false` to bypass the cache.
284
+
285
+ ```ts
286
+ export default defineNuxtConfig({
287
+ nuxtCloudflare: {
288
+ bindingTypes: {
289
+ cacheDir: '/shared/nuxt-cloudflare',
290
+ },
291
+ },
292
+ })
293
+ ```
294
+
283
295
  The source may be an H3 event, Nitro task input, or task context. Eventless access uses Nitro's `globalThis.__env__` Cloudflare entry shim. An explicit environment always wins and never mixes with the global environment. Binding names come from the generated `CloudflareBindings` interface. Missing required bindings throw. Pass a generic only to override generated types in a focused test.
284
296
 
285
297
  `useCloudflareRuntimeConfig` reads runtime config from both contexts. On Cloudflare, `NUXT_*` Worker vars and secrets bind onto runtime config only through an event, so a bare `useRuntimeConfig()` off the request path returns build-time defaults. Without an event this reads the Cloudflare entry environment and wraps it as the source Nitro requires. The module's Nitro plugin supplies the reader; use `runtimeConfigSource` directly only when you own the `useRuntimeConfig` call.
@@ -1,10 +1,15 @@
1
- import { mkdir, writeFile } from 'node:fs/promises';
2
- import { resolve } from 'pathe';
3
- import { experimental_generateTypes } from 'wrangler';
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { mkdir, writeFile, readFile, rename, unlink } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { homedir } from 'node:os';
5
+ import process from 'node:process';
6
+ import { resolve, dirname } from 'pathe';
4
7
  import { readAuthoredWranglerConfig } from '../wrangler.mjs';
5
8
  import 'node:fs';
6
9
  import 'confbox';
7
10
 
11
+ const BINDING_TYPE_CACHE_SCHEMA = 1;
12
+ const require$1 = createRequire(import.meta.url);
8
13
  const COMPUTED_WRANGLER_KEYS = /* @__PURE__ */ new Set([
9
14
  "configPath",
10
15
  "definedEnvironments",
@@ -15,6 +20,24 @@ const COMPUTED_WRANGLER_KEYS = /* @__PURE__ */ new Set([
15
20
  function isRecord(value) {
16
21
  return value !== null && typeof value === "object" && !Array.isArray(value);
17
22
  }
23
+ function errorMessage(error) {
24
+ return error instanceof Error ? error.message : String(error);
25
+ }
26
+ function isNodeError(error, code) {
27
+ return error instanceof Error && "code" in error && error.code === code;
28
+ }
29
+ function hash(value) {
30
+ return createHash("sha256").update(value).digest("hex");
31
+ }
32
+ function stableValue(value) {
33
+ if (Array.isArray(value))
34
+ return value.map(stableValue);
35
+ if (!isRecord(value))
36
+ return value;
37
+ return Object.fromEntries(
38
+ Object.entries(value).sort(([left], [right]) => compareText(left, right)).map(([key, child]) => [key, stableValue(child)])
39
+ );
40
+ }
18
41
  function mergeDefaults(primary, fallback) {
19
42
  if (primary === void 0 || primary === null)
20
43
  return fallback;
@@ -67,7 +90,115 @@ function canonicalizeBindingEnvironment(environment) {
67
90
  );
68
91
  }
69
92
  function createBindingTypeSignature(environment, runtime) {
70
- return `${canonicalizeBindingEnvironment(environment)}\0${runtime.replaceAll("\r\n", "\n")}`;
93
+ return hash(`${canonicalizeBindingEnvironment(environment)}\0${runtime.replaceAll("\r\n", "\n")}`);
94
+ }
95
+ function normalizeGeneratedContent(content) {
96
+ return content.replace(
97
+ /^\/\/ Generated by Wrangler by running `.*` \(hash: ([a-zA-Z0-9]+)\)$/m,
98
+ "// Generated by Wrangler by running `wrangler types` (hash: $1)"
99
+ );
100
+ }
101
+ function reportInvalidCache(reason, report) {
102
+ if (report) {
103
+ report(reason);
104
+ return;
105
+ }
106
+ process.emitWarning(`[nuxt-cloudflare] Binding type cache entry is invalid: ${reason}. Rebuilding it.`);
107
+ }
108
+ function parseCacheEntry(source) {
109
+ let value;
110
+ try {
111
+ value = JSON.parse(source);
112
+ } catch (error) {
113
+ return { _tag: "invalid", reason: `JSON cannot be parsed: ${errorMessage(error)}` };
114
+ }
115
+ if (!isRecord(value))
116
+ return { _tag: "invalid", reason: "the entry must be an object" };
117
+ if (value.schema !== BINDING_TYPE_CACHE_SCHEMA)
118
+ return { _tag: "invalid", reason: `schema ${String(value.schema)} is unsupported` };
119
+ if (typeof value.content !== "string")
120
+ return { _tag: "invalid", reason: "content must be a string" };
121
+ if (typeof value.signature !== "string" || !/^[a-f0-9]{64}$/.test(value.signature))
122
+ return { _tag: "invalid", reason: "signature must be a SHA-256 hash" };
123
+ if (typeof value.artifactHash !== "string" || value.artifactHash !== hash(`${value.content}\0${value.signature}`))
124
+ return { _tag: "invalid", reason: "the artifact hash does not match" };
125
+ return {
126
+ _tag: "hit",
127
+ artifact: { content: value.content, signature: value.signature }
128
+ };
129
+ }
130
+ async function readCacheEntry(path) {
131
+ const source = await readFile(path, "utf8").then((value) => ({ _tag: "read", value })).catch((error) => isNodeError(error, "ENOENT") ? { _tag: "missing" } : { _tag: "failed", error });
132
+ if (source._tag === "missing")
133
+ return { _tag: "missing" };
134
+ if (source._tag === "failed")
135
+ return { _tag: "invalid", reason: `the entry cannot be read: ${errorMessage(source.error)}` };
136
+ return parseCacheEntry(source.value);
137
+ }
138
+ function cacheEntry(artifact) {
139
+ return {
140
+ schema: BINDING_TYPE_CACHE_SCHEMA,
141
+ artifactHash: hash(`${artifact.content}\0${artifact.signature}`),
142
+ content: artifact.content,
143
+ signature: artifact.signature
144
+ };
145
+ }
146
+ function artifactsMatch(left, right) {
147
+ return left.content === right.content && left.signature === right.signature;
148
+ }
149
+ async function removeTemporaryFile(path) {
150
+ return unlink(path).then(() => void 0).catch((error) => isNodeError(error, "ENOENT") ? void 0 : error);
151
+ }
152
+ async function writeCacheEntry(path, artifact) {
153
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
154
+ await writeFile(temporaryPath, `${JSON.stringify(cacheEntry(artifact))}
155
+ `, { flag: "wx", mode: 384 });
156
+ const write = await rename(temporaryPath, path).then(() => ({ _tag: "written" })).catch((error) => ({ _tag: "failed", error }));
157
+ if (write._tag === "written")
158
+ return;
159
+ const [existing, cleanupError] = await Promise.all([
160
+ readCacheEntry(path),
161
+ removeTemporaryFile(temporaryPath)
162
+ ]);
163
+ if (cleanupError)
164
+ throw new AggregateError([write.error, cleanupError], "Binding type cache write and cleanup failed.");
165
+ if (existing._tag === "hit" && artifactsMatch(existing.artifact, artifact))
166
+ return;
167
+ throw write.error;
168
+ }
169
+ async function readWranglerVersion() {
170
+ const packagePath = require$1.resolve("wrangler/package.json");
171
+ const source = await readFile(packagePath, "utf8");
172
+ const parsed = parseCachePackage(source);
173
+ if (parsed._tag === "invalid")
174
+ throw new Error(`[nuxt-cloudflare] Wrangler package metadata is invalid: ${parsed.reason}`);
175
+ return parsed.version;
176
+ }
177
+ function parseCachePackage(source) {
178
+ let value;
179
+ try {
180
+ value = JSON.parse(source);
181
+ } catch (error) {
182
+ return { _tag: "invalid", reason: `JSON cannot be parsed: ${errorMessage(error)}` };
183
+ }
184
+ if (!isRecord(value) || typeof value.version !== "string" || value.version.length === 0)
185
+ return { _tag: "invalid", reason: "version must be a non-empty string" };
186
+ return { _tag: "valid", version: value.version };
187
+ }
188
+ function defaultCacheDir() {
189
+ return resolve(process.env.XDG_CACHE_HOME || resolve(homedir(), ".cache"), "nuxt-cloudflare/binding-types");
190
+ }
191
+ function resolveCacheDir(options) {
192
+ if (options.cacheDir === false)
193
+ return false;
194
+ return options.cacheDir ? resolve(options.rootDir, options.cacheDir) : defaultCacheDir();
195
+ }
196
+ function cacheKey(config, wranglerVersion) {
197
+ return hash(JSON.stringify({
198
+ config: stableValue(config),
199
+ schema: BINDING_TYPE_CACHE_SCHEMA,
200
+ wranglerVersion
201
+ }));
71
202
  }
72
203
  function readAuthoredConfig(rootDir) {
73
204
  const authored = readAuthoredWranglerConfig(rootDir);
@@ -79,9 +210,25 @@ async function generateCloudflareBindingTypes(options) {
79
210
  const directory = resolve(options.buildDir, "nuxt-cloudflare");
80
211
  const configPath = resolve(directory, "wrangler.json");
81
212
  const typePath = resolve(options.buildDir, "types/cloudflare-bindings.d.ts");
82
- await mkdir(directory, { recursive: true });
83
- await writeFile(configPath, `${JSON.stringify(normalizeConfig(options.config, options), null, 2)}
213
+ const config = normalizeConfig(options.config, options);
214
+ await Promise.all([
215
+ mkdir(directory, { recursive: true }),
216
+ mkdir(dirname(typePath), { recursive: true })
217
+ ]);
218
+ await writeFile(configPath, `${JSON.stringify(config, null, 2)}
84
219
  `);
220
+ const cacheDir = options.cacheDir;
221
+ const cachePath = cacheDir ? resolve(cacheDir, `${cacheKey(config, await readWranglerVersion())}.json`) : void 0;
222
+ if (cachePath) {
223
+ const cached = await readCacheEntry(cachePath);
224
+ if (cached._tag === "hit") {
225
+ await writeFile(typePath, cached.artifact.content);
226
+ return cached.artifact;
227
+ }
228
+ if (cached._tag === "invalid")
229
+ reportInvalidCache(cached.reason, options.onCacheInvalid);
230
+ }
231
+ const { experimental_generateTypes } = await import('wrangler');
85
232
  const generated = await experimental_generateTypes({
86
233
  config: configPath,
87
234
  envInterface: "CloudflareBindings",
@@ -91,15 +238,21 @@ async function generateCloudflareBindingTypes(options) {
91
238
  });
92
239
  if (!generated.env || !generated.runtime)
93
240
  throw new Error("[nuxt-cloudflare] Wrangler did not generate Cloudflare binding and runtime types.");
94
- return {
95
- content: generated.content,
241
+ const artifact = {
242
+ content: normalizeGeneratedContent(generated.content),
96
243
  signature: createBindingTypeSignature(generated.env, generated.runtime)
97
244
  };
245
+ await writeFile(typePath, artifact.content);
246
+ if (cachePath && cacheDir) {
247
+ await mkdir(cacheDir, { recursive: true, mode: 448 });
248
+ await writeCacheEntry(cachePath, artifact);
249
+ }
250
+ return artifact;
98
251
  }
99
252
  async function prepareCloudflareBindingTypes(options) {
100
253
  const authored = readAuthoredConfig(options.rootDir);
101
254
  const config = mergeDefaults(options.wrangler, authored);
102
- return generateCloudflareBindingTypes({ ...options, config });
255
+ return generateCloudflareBindingTypes({ ...options, cacheDir: resolveCacheDir(options), config });
103
256
  }
104
257
  async function assertCloudflareBindingTypesCurrent(options) {
105
258
  const generated = await generateCloudflareBindingTypes(options);
@@ -2,7 +2,7 @@
2
2
  import process from 'node:process';
3
3
  import { defineCommand, runMain } from 'citty';
4
4
  import { resolve } 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
+ import { d as discoverWranglerSourceConfigs, a as diagnoseWranglerSourceConfigs, r as resolveConfigStaticAssetDirectory, b as diagnoseStaticAssetRules, c as readStaticAssetRuleFiles, p as parseWranglerAllowedWarnings, e as evaluateWranglerDiagnostics } from '../shared/nuxt-cloudflare.Drgx8RDh.mjs';
6
6
  import { diagnoseWranglerConfig, formatWranglerDiagnostics } from '../wrangler.mjs';
7
7
  import { readProjectWranglerConfig } from '../chunks/wrangler-reader.mjs';
8
8
  import { readFileSync } from 'node:fs';
@@ -38,11 +38,13 @@ function diagnoseWranglerProject(options) {
38
38
  sourceConfigPaths
39
39
  };
40
40
  }
41
+ const staticAssetDirectory = resolveConfigStaticAssetDirectory(loaded.path, loaded.config);
41
42
  return {
42
43
  configPath: loaded.path,
43
44
  diagnostics: [
44
45
  ...diagnoseWranglerConfig(loaded.config, { ...options, generated: loaded.generated, normalized: true }),
45
- ...diagnoseWranglerSourceConfigs(sourceConfigPaths)
46
+ ...diagnoseWranglerSourceConfigs(sourceConfigPaths),
47
+ ...staticAssetDirectory === void 0 ? [] : diagnoseStaticAssetRules(readStaticAssetRuleFiles(staticAssetDirectory))
46
48
  ],
47
49
  sourceConfigPaths
48
50
  };
package/dist/module.d.mts CHANGED
@@ -9,7 +9,10 @@ type WranglerDiagnosticPolicy = {
9
9
  };
10
10
 
11
11
  interface ModuleOptions {
12
- bindingTypes?: boolean;
12
+ bindingTypes?: boolean | {
13
+ /** Shared cache directory. Set false to generate binding types every time. */
14
+ cacheDir?: false | string;
15
+ };
13
16
  enabled?: boolean;
14
17
  compatibilityDate?: string;
15
18
  compatibilityMaxAgeDays?: number;
@@ -65,7 +68,7 @@ type BindingTypeAudit = {
65
68
  * reuses a cached template must fail, not skip: a skipped comparison reports a
66
69
  * clean build for types that no longer match the deployed config.
67
70
  */
68
- declare function resolveBindingTypeAudit(bindingTypes: boolean | undefined, signature: string | undefined): BindingTypeAudit;
71
+ declare function resolveBindingTypeAudit(bindingTypes: ModuleOptions['bindingTypes'], signature: string | undefined): BindingTypeAudit;
69
72
  declare function setupCloudflareModule(options: ModuleOptions, nuxt: Nuxt): void;
70
73
  declare const _default: any;
71
74
 
package/dist/module.json CHANGED
@@ -2,9 +2,9 @@
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "configKey": "nuxtCloudflare",
4
4
  "compatibility": {
5
- "nuxt": ">=4.5.0 <5.0.0"
5
+ "nuxt": ">=4.5.0 <6.0.0"
6
6
  },
7
- "version": "0.3.0",
7
+ "version": "0.4.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import process from 'node:process';
2
2
  import { useLogger, defineNuxtModule, hasNuxtModule, addTypeTemplate } from '@nuxt/kit';
3
3
  import { resolve } from 'pathe';
4
- import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
4
+ import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, b as diagnoseStaticAssetRules, c as readStaticAssetRuleFiles, f as resolveBuildStaticAssetDirectory, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.Drgx8RDh.mjs';
5
5
  import { resolveHtmlCacheGuarantee, staleDirectivesAreDisabled } from '../dist/runtime/server/utils/workers-cache.js';
6
6
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, applyCloudflareDefaults } from './wrangler.mjs';
7
7
  import 'node:fs';
@@ -227,7 +227,12 @@ async function auditGeneratedWranglerConfig(nitro, options, buildDir, rootDir, b
227
227
  generated: true,
228
228
  publicVarNames: options.publicVarNames
229
229
  }),
230
- ...diagnoseWranglerSourceConfigs(discoverWranglerSourceConfigs(rootDir))
230
+ ...diagnoseWranglerSourceConfigs(discoverWranglerSourceConfigs(rootDir)),
231
+ // Every module's prerender headers land in one `_headers` file, and the
232
+ // upload is the first thing that counts them. Count them here instead.
233
+ ...diagnoseStaticAssetRules(readStaticAssetRuleFiles(
234
+ resolveBuildStaticAssetDirectory(nitro.options.preset, nitro.options.output)
235
+ ))
231
236
  ];
232
237
  const policy = options.doctor ?? { _tag: "advisory" };
233
238
  const outcome = evaluateWranglerDiagnostics(diagnostics, policy);
@@ -267,10 +272,13 @@ function setupCloudflareModule(options, nuxt) {
267
272
  getContents: async () => {
268
273
  const { prepareCloudflareBindingTypes } = await import('./chunks/binding-types.mjs');
269
274
  const compatibilityDate = nuxt.options.compatibilityDate;
275
+ const cacheDir = typeof options.bindingTypes === "object" ? options.bindingTypes.cacheDir : void 0;
270
276
  const artifact = await prepareCloudflareBindingTypes({
271
277
  buildDir: nuxt.options.buildDir,
278
+ cacheDir,
272
279
  compatibilityDate: typeof compatibilityDate === "string" ? compatibilityDate || void 0 : compatibilityDate.cloudflare ?? compatibilityDate.default,
273
280
  nodeCompat: Boolean(nuxt.options.nitro.cloudflare?.nodeCompat),
281
+ onCacheInvalid: (reason) => logger.warn(`Binding type cache entry is invalid: ${reason}. Rebuilding it.`),
274
282
  rootDir: nuxt.options.rootDir,
275
283
  wrangler: nuxt.options.nitro.cloudflare?.wrangler ?? {}
276
284
  });
@@ -354,7 +362,7 @@ const module$1 = defineNuxtModule({
354
362
  meta: {
355
363
  name: "@harlan-zw/nuxt-cloudflare",
356
364
  configKey: "nuxtCloudflare",
357
- compatibility: { nuxt: ">=4.5.0 <5.0.0" }
365
+ compatibility: { nuxt: ">=4.5.0 <6.0.0" }
358
366
  },
359
367
  defaults: {
360
368
  bindingTypes: true,
@@ -0,0 +1,147 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve, dirname, extname, join } 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
+ const STATIC_ASSET_RULE_LIMITS = {
78
+ headers: 100,
79
+ redirectsStatic: 2e3,
80
+ redirectsDynamic: 100
81
+ };
82
+ function resolveBuildStaticAssetDirectory(preset, output) {
83
+ return String(preset || "").includes("pages") ? output.dir : output.publicDir;
84
+ }
85
+ function resolveConfigStaticAssetDirectory(configPath, config) {
86
+ const directory = config.assets?.directory ?? config.pages_build_output_dir;
87
+ if (!configPath || !directory)
88
+ return void 0;
89
+ return resolve(dirname(configPath), directory);
90
+ }
91
+ function readStaticAssetRuleFiles(directory) {
92
+ const files = {};
93
+ for (const [key, name] of [["headers", "_headers"], ["redirects", "_redirects"]]) {
94
+ const path = join(directory, name);
95
+ if (existsSync(path))
96
+ files[key] = readFileSync(path, "utf8");
97
+ }
98
+ return files;
99
+ }
100
+ function ruleLines(contents) {
101
+ return contents.split(/\r?\n/).filter((line) => /^[^\s#]/.test(line));
102
+ }
103
+ function rulePrefix(route) {
104
+ const segments = route.split("/").filter(Boolean);
105
+ return segments.length > 1 ? `/${segments[0]}/*` : route;
106
+ }
107
+ function topPrefixes(routes, limit = 3) {
108
+ const counts = /* @__PURE__ */ new Map();
109
+ for (const route of routes)
110
+ counts.set(rulePrefix(route), (counts.get(rulePrefix(route)) ?? 0) + 1);
111
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([prefix, count]) => `${prefix} (${count})`).join(", ");
112
+ }
113
+ function isDynamicRedirect(source) {
114
+ return source.includes("*") || source.includes(":");
115
+ }
116
+ function diagnoseStaticAssetRules(files) {
117
+ const diagnostics = [];
118
+ if (files.headers !== void 0) {
119
+ const routes = ruleLines(files.headers).map((line) => line.trim());
120
+ if (routes.length > STATIC_ASSET_RULE_LIMITS.headers) {
121
+ diagnostics.push({
122
+ _tag: "error",
123
+ code: "static-headers-rule-limit",
124
+ message: `_headers has ${routes.length} rules and Cloudflare accepts ${STATIC_ASSET_RULE_LIMITS.headers}. The upload fails past that. Most rules sit under: ${topPrefixes(routes)}. Collapse them into globs or stop the module that emits them.`,
125
+ sourcePath: "_headers"
126
+ });
127
+ }
128
+ }
129
+ if (files.redirects !== void 0) {
130
+ const sources = ruleLines(files.redirects).map((line) => line.trim().split(/\s+/)[0]);
131
+ const dynamic = sources.filter(isDynamicRedirect);
132
+ const staticCount = sources.length - dynamic.length;
133
+ const overStatic = staticCount > STATIC_ASSET_RULE_LIMITS.redirectsStatic;
134
+ const overDynamic = dynamic.length > STATIC_ASSET_RULE_LIMITS.redirectsDynamic;
135
+ if (overStatic || overDynamic) {
136
+ diagnostics.push({
137
+ _tag: "error",
138
+ code: "static-redirects-rule-limit",
139
+ message: `_redirects has ${staticCount} static and ${dynamic.length} dynamic rules and Cloudflare accepts ${STATIC_ASSET_RULE_LIMITS.redirectsStatic} static and ${STATIC_ASSET_RULE_LIMITS.redirectsDynamic} dynamic. The upload fails past that. Most rules sit under: ${topPrefixes(sources)}.`,
140
+ sourcePath: "_redirects"
141
+ });
142
+ }
143
+ }
144
+ return diagnostics;
145
+ }
146
+
147
+ export { diagnoseWranglerSourceConfigs as a, diagnoseStaticAssetRules as b, readStaticAssetRuleFiles as c, discoverWranglerSourceConfigs as d, evaluateWranglerDiagnostics as e, resolveBuildStaticAssetDirectory as f, parseWranglerAllowedWarnings as p, resolveConfigStaticAssetDirectory as r };
@@ -138,6 +138,8 @@ interface WranglerConfigInput extends Record<string, unknown> {
138
138
  };
139
139
  mtls_certificates?: WranglerRemoteBindingInput[];
140
140
  no_bundle?: boolean;
141
+ /** Pages projects name their upload directory here instead of `assets.directory`. */
142
+ pages_build_output_dir?: string;
141
143
  observability?: WranglerObservabilityInput;
142
144
  placement?: WranglerPlacementInput;
143
145
  preview_urls?: boolean;
@@ -169,7 +171,7 @@ interface CloudflareDefaultOptions {
169
171
  versionMetadataBinding?: string;
170
172
  workersCache?: WorkersCachePolicy;
171
173
  }
172
- declare const WRANGLER_DIAGNOSTIC_CODES: readonly ["assets-worker-first", "assets-worker-first-pattern-invalid", "compatibility-date-missing", "compatibility-date-invalid", "container-durable-object-binding-missing", "container-durable-object-not-sqlite", "container-instance-type-deprecated", "cpu-limit-raised", "durable-object-binding-inactive", "durable-object-lifecycle-mixed", "durable-object-lifecycle-unmanaged", "email-binding-unrestricted", "environment-binding-missing", "generated-config-has-env", "keep-vars-enabled", "legacy-module-binding", "missing-nodejs-compat", "nodejs-compat-version-implicit", "observability-disabled", "observability-log-sampling-high", "observability-sampling-implicit", "observability-sampling-out-of-range", "observability-trace-sampling-high", "plaintext-secret-var", "preview-urls-public", "pipeline-binding-deprecated", "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", "remote-binding-not-enabled", "unsafe-hello-world-binding", "version-metadata-missing", "workers-dev-enabled", "workers-dev-implicit", "workers-cache-cross-version-enabled", "workers-cache-assets-billable", "workers-cache-policy-implicit", "wrangler-config-shadowed", "wrangler-config-missing", "wrangler-config-unreadable", "wrangler-jsonc-preferred"];
174
+ declare const WRANGLER_DIAGNOSTIC_CODES: readonly ["assets-worker-first", "assets-worker-first-pattern-invalid", "compatibility-date-missing", "compatibility-date-invalid", "container-durable-object-binding-missing", "container-durable-object-not-sqlite", "container-instance-type-deprecated", "cpu-limit-raised", "durable-object-binding-inactive", "durable-object-lifecycle-mixed", "durable-object-lifecycle-unmanaged", "email-binding-unrestricted", "environment-binding-missing", "generated-config-has-env", "keep-vars-enabled", "legacy-module-binding", "missing-nodejs-compat", "nodejs-compat-version-implicit", "observability-disabled", "observability-log-sampling-high", "observability-sampling-implicit", "observability-sampling-out-of-range", "observability-trace-sampling-high", "plaintext-secret-var", "preview-urls-public", "pipeline-binding-deprecated", "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", "static-headers-rule-limit", "static-redirects-rule-limit", "traces-disabled", "remote-binding-not-enabled", "unsafe-hello-world-binding", "version-metadata-missing", "workers-dev-enabled", "workers-dev-implicit", "workers-cache-cross-version-enabled", "workers-cache-assets-billable", "workers-cache-policy-implicit", "wrangler-config-shadowed", "wrangler-config-missing", "wrangler-config-unreadable", "wrangler-jsonc-preferred"];
173
175
  type WranglerDiagnosticCode = typeof WRANGLER_DIAGNOSTIC_CODES[number];
174
176
  interface WranglerDiagnostic {
175
177
  _tag: 'error' | 'info' | 'warning';
package/dist/wrangler.mjs CHANGED
@@ -94,6 +94,8 @@ const WRANGLER_DIAGNOSTIC_CODES = [
94
94
  "secret-declared-as-var",
95
95
  "source-maps-disabled",
96
96
  "stale-compatibility-date",
97
+ "static-headers-rule-limit",
98
+ "static-redirects-rule-limit",
97
99
  "traces-disabled",
98
100
  "remote-binding-not-enabled",
99
101
  "unsafe-hello-world-binding",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.3.0",
4
+ "version": "0.4.0",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -87,7 +87,7 @@
87
87
  "node": ">=22.12.0"
88
88
  },
89
89
  "peerDependencies": {
90
- "nuxt": ">=4.5.0 <5.0.0",
90
+ "nuxt": ">=4.5.0 <6.0.0",
91
91
  "wrangler": ">=4.120.0 <5.0.0"
92
92
  },
93
93
  "dependencies": {
@@ -113,7 +113,7 @@
113
113
  "unbuild": "^3.6.1",
114
114
  "vitest": "^4.1.10",
115
115
  "wrangler": "^4.120.1",
116
- "@harlan-zw/nuxt-wide-events": "^0.1.3"
116
+ "@harlan-zw/nuxt-wide-events": "^0.1.4"
117
117
  },
118
118
  "scripts": {
119
119
  "build": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxt-module-build build",
@@ -1,77 +0,0 @@
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 };