@harlan-zw/nuxt-cloudflare 0.0.18 → 0.2.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 +45 -5
- package/dist/bindings.d.mts +40 -4
- package/dist/bindings.mjs +18 -2
- package/dist/cache.d.mts +69 -0
- package/dist/cache.mjs +38 -0
- package/dist/chunks/binding-types.mjs +7 -13
- package/dist/cli/index.mjs +12 -2
- package/dist/module.d.mts +26 -3
- package/dist/module.json +1 -1
- package/dist/module.mjs +73 -20
- package/dist/runtime/server/plugins/runtime-config.d.ts +9 -0
- package/dist/runtime/server/plugins/runtime-config.js +5 -0
- package/dist/runtime/server/plugins/workers-cache.js +84 -8
- package/dist/runtime/server/utils/workers-cache.d.ts +162 -2
- package/dist/runtime/server/utils/workers-cache.js +133 -10
- package/dist/types.d.mts +2 -2
- package/dist/wrangler.d.mts +53 -3
- package/dist/wrangler.mjs +62 -25
- package/package.json +12 -4
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@ The module extracts production patterns already proven in Nuxt SEO and gscdump.
|
|
|
6
6
|
|
|
7
7
|
## Defaults
|
|
8
8
|
|
|
9
|
+
Every default below yields to a value you wrote. The root `wrangler.jsonc`, `wrangler.json`, or `wrangler.toml` is authored config, and so is `nitro.cloudflare.wrangler`. A module default applies only where neither names the key. Workers Caching is the one exception: the module owns that policy because it also registers the caching plugin.
|
|
10
|
+
|
|
9
11
|
- Cloudflare module preset, generated Wrangler config, and Node compatibility
|
|
10
12
|
- Static assets remain asset first by default. Blanket `assets.run_worker_first: true` warns because valid authentication and transform use cases exist
|
|
11
13
|
- Workers Logs sampled at 1%, traces at 1%, both overridable
|
|
@@ -15,7 +17,8 @@ The module extracts production patterns already proven in Nuxt SEO and gscdump.
|
|
|
15
17
|
- Smart Placement enabled unless the project chooses a placement
|
|
16
18
|
- Workers Caching enabled with version isolation
|
|
17
19
|
- Rendered HTML forced to `private, no-store`; explicit non-HTML cache policies remain intact
|
|
18
|
-
- Source-map upload when the Nitro build emits maps;
|
|
20
|
+
- Source-map upload when the Nitro build emits maps; an authored value is preserved
|
|
21
|
+
- `nodejs_compat` added unless the config chooses `nodejs_compat_v2`, which Cloudflare rejects alongside it
|
|
19
22
|
- Module-wide `secrets.required` names copied to each environment; source root secrets remain scoped to the root
|
|
20
23
|
- Version metadata is skipped when `CF_VERSION_METADATA` already names another binding
|
|
21
24
|
- Raw `cloudflare-kv-binding` on Nitro's `cache` mount upgraded to a 30-day physical expiry
|
|
@@ -62,7 +65,39 @@ Cloudflare KV requires TTLs of at least 60 seconds. The cache wrapper raises sho
|
|
|
62
65
|
|
|
63
66
|
Keep server runtime secret defaults empty. Nuxt reads matching `NUXT_*` values from Worker secret bindings at runtime. The production build guard rejects secret build environment values before Nitro can include them in the bundle. Nuxt Scripts proxy signing remains allowed because that module registers its security plugin during the build.
|
|
64
67
|
|
|
65
|
-
Workers Caching is separate from Nitro's KV-backed cache. The module enables version-isolated caching by default.
|
|
68
|
+
Workers Caching is separate from Nitro's KV-backed cache. The module enables version-isolated caching by default. Set `workersCache: { _tag: 'disabled' }` to opt out. Choose cross-version caching only with an explicit purge path.
|
|
69
|
+
|
|
70
|
+
The module writes a fail-closed `private, no-store` before routing, so a response nobody described is never cached. It never rewrites a policy you set on a response that is not a rendered document, so asset and API route rules are yours.
|
|
71
|
+
|
|
72
|
+
For a rendered document it applies `workersCache.html`:
|
|
73
|
+
|
|
74
|
+
| Value | Behaviour |
|
|
75
|
+
| --- | --- |
|
|
76
|
+
| `auto` (default) | Honour your `cache-control`, clamped to a retention window another module publishes. Falls back to `no-store` when nothing publishes one. |
|
|
77
|
+
| `app` | Always honour your `cache-control`. You own the version-skew risk. |
|
|
78
|
+
| `no-store` | Always overwrite it. |
|
|
79
|
+
|
|
80
|
+
A cached document can name build chunks a later deploy deleted, which is why `auto` needs a guarantee. [`nuxt-skew-protection`](https://github.com/harlan-zw/nuxt-skew-protection) publishes one when you set `skewProtection: { htmlCache: true }`.
|
|
81
|
+
|
|
82
|
+
Four things are refused whatever you configure, because a shared cache keys on the URL: a request carrying credentials, a response setting a cookie, a status other than 200, and a response varying on `Cookie` or `Authorization`.
|
|
83
|
+
|
|
84
|
+
### Writing cache rules
|
|
85
|
+
|
|
86
|
+
`edgeCache` builds the headers for a route rule:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { edgeCache, NO_STORE } from '@harlan-zw/nuxt-cloudflare/cache'
|
|
90
|
+
|
|
91
|
+
export default defineNuxtConfig({
|
|
92
|
+
routeRules: {
|
|
93
|
+
'/api/feed': edgeCache({ maxAge: 60 }),
|
|
94
|
+
'/api/reports': edgeCache({ maxAge: 3600, staleWhileRevalidate: 86400, browser: 'revalidate' }),
|
|
95
|
+
'/api/private': NO_STORE,
|
|
96
|
+
},
|
|
97
|
+
})
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
It emits `max-age`, never `s-maxage`. Cloudflare reads `s-maxage` as implying `proxy-revalidate`, which disables `stale-while-revalidate` and `stale-if-error`, so a policy that looks like it serves stale blocks on revalidation instead. The module warns at build if a route rule you wrote by hand hits that.
|
|
66
101
|
|
|
67
102
|
## Cost controls
|
|
68
103
|
|
|
@@ -184,7 +219,8 @@ D1 allows 100 bound parameters per statement, including each statement inside `d
|
|
|
184
219
|
### Bindings
|
|
185
220
|
|
|
186
221
|
```ts
|
|
187
|
-
import {
|
|
222
|
+
import type { H3Event } from 'h3'
|
|
223
|
+
import { createCloudflareBindings, useCloudflareRuntimeConfig } from '@harlan-zw/nuxt-cloudflare/bindings'
|
|
188
224
|
|
|
189
225
|
const cloudflare = createCloudflareBindings()
|
|
190
226
|
|
|
@@ -192,14 +228,18 @@ function requireDatabase(source?: unknown) {
|
|
|
192
228
|
return cloudflare.require('DB', source)
|
|
193
229
|
}
|
|
194
230
|
|
|
195
|
-
|
|
196
|
-
|
|
231
|
+
// `event` on the request path, nothing in a queue, scheduled, email, or task handler.
|
|
232
|
+
function apiToken(event?: H3Event) {
|
|
233
|
+
return useCloudflareRuntimeConfig(event).apiToken
|
|
234
|
+
}
|
|
197
235
|
```
|
|
198
236
|
|
|
199
237
|
`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.
|
|
200
238
|
|
|
201
239
|
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.
|
|
202
240
|
|
|
241
|
+
`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.
|
|
242
|
+
|
|
203
243
|
### Scoped secrets file
|
|
204
244
|
|
|
205
245
|
```ts
|
package/dist/bindings.d.mts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { H3Event } from 'h3';
|
|
2
|
+
import { NitroRuntimeConfig } from 'nitropack/types';
|
|
3
|
+
|
|
1
4
|
type BindingName<Environment extends object> = Extract<keyof Environment, string>;
|
|
2
5
|
declare global {
|
|
3
6
|
interface CloudflareBindings {
|
|
@@ -21,8 +24,41 @@ declare function resolveCloudflareBindings<Environment extends object = Cloudfla
|
|
|
21
24
|
declare function setCloudflareBindings<Environment extends object>(env: Environment | undefined): void;
|
|
22
25
|
/** Merges binding sources into the eventless environment. Later sources win. */
|
|
23
26
|
declare function mergeCloudflareBindings<Environment extends object = CloudflareBindings>(...sources: Array<Partial<Environment> | undefined>): Environment;
|
|
24
|
-
/**
|
|
25
|
-
|
|
27
|
+
/**
|
|
28
|
+
* Creates the event-shaped source Nitro runtime config resolution requires.
|
|
29
|
+
*
|
|
30
|
+
* `useRuntimeConfig` writes the resolved config onto `context.nitro`, so a
|
|
31
|
+
* source without that object throws for every read that reaches it. Two
|
|
32
|
+
* production incidents came from a source that omitted it.
|
|
33
|
+
*
|
|
34
|
+
* The return type includes `H3Event` because that is the parameter
|
|
35
|
+
* `useRuntimeConfig` declares, and this value carries every field it reads.
|
|
36
|
+
* It is a config source, never a request: no other H3 helper may receive it.
|
|
37
|
+
*/
|
|
38
|
+
declare function runtimeConfigSource<Environment extends object>(env: Environment): CloudflareRuntimeConfigSource<Environment> & H3Event;
|
|
39
|
+
/** Reads Nitro runtime config for one event, or the shared config without one. */
|
|
40
|
+
type NitroRuntimeConfigReader = (event?: H3Event) => NitroRuntimeConfig;
|
|
41
|
+
/**
|
|
42
|
+
* Provides Nitro's `useRuntimeConfig` to `useCloudflareRuntimeConfig`.
|
|
43
|
+
*
|
|
44
|
+
* The module's own Nitro plugin calls this. The reader is injected rather than
|
|
45
|
+
* imported because this file is also loaded outside a Nitro bundle, where a
|
|
46
|
+
* module-top `nitropack/runtime` import resolves virtual specifiers that only
|
|
47
|
+
* exist inside the Nitro build and crashes the development server at boot.
|
|
48
|
+
*/
|
|
49
|
+
declare function provideCloudflareRuntimeConfig(read: NitroRuntimeConfigReader | undefined): void;
|
|
50
|
+
/**
|
|
51
|
+
* Reads Nitro runtime config from Cloudflare request and eventless contexts.
|
|
52
|
+
*
|
|
53
|
+
* Pass the request event on the request path. Off it, in queue consumers,
|
|
54
|
+
* scheduled handlers, email handlers, and Nitro tasks, there is no event and a
|
|
55
|
+
* bare `useRuntimeConfig()` returns build-time defaults: the deployment's
|
|
56
|
+
* `NUXT_*` Worker vars and secrets bind onto runtime config only through an
|
|
57
|
+
* event. The Cloudflare entry assigns the live environment to
|
|
58
|
+
* `globalThis.__env__` in every handler, so the eventless path reads that and
|
|
59
|
+
* wraps it as a runtime config source.
|
|
60
|
+
*/
|
|
61
|
+
declare function useCloudflareRuntimeConfig(event?: H3Event): NitroRuntimeConfig;
|
|
26
62
|
/**
|
|
27
63
|
* Creates typed binding access for the generated `CloudflareBindings` environment.
|
|
28
64
|
*
|
|
@@ -31,5 +67,5 @@ declare function runtimeConfigSource<Environment extends object>(env: Environmen
|
|
|
31
67
|
*/
|
|
32
68
|
declare function createCloudflareBindings<Environment extends object = CloudflareBindings>(): CloudflareBindingAccessor<Environment>;
|
|
33
69
|
|
|
34
|
-
export { createCloudflareBindings, mergeCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource, setCloudflareBindings };
|
|
35
|
-
export type { CloudflareBindingAccessor, CloudflareRuntimeConfigSource };
|
|
70
|
+
export { createCloudflareBindings, mergeCloudflareBindings, provideCloudflareRuntimeConfig, resolveCloudflareBindings, runtimeConfigSource, setCloudflareBindings, useCloudflareRuntimeConfig };
|
|
71
|
+
export type { CloudflareBindingAccessor, CloudflareRuntimeConfigSource, NitroRuntimeConfigReader };
|
package/dist/bindings.mjs
CHANGED
|
@@ -24,12 +24,28 @@ function mergeCloudflareBindings(...sources) {
|
|
|
24
24
|
return merged;
|
|
25
25
|
}
|
|
26
26
|
function runtimeConfigSource(env) {
|
|
27
|
-
|
|
27
|
+
const source = {
|
|
28
28
|
context: {
|
|
29
29
|
nitro: {},
|
|
30
30
|
cloudflare: { env }
|
|
31
31
|
}
|
|
32
32
|
};
|
|
33
|
+
return source;
|
|
34
|
+
}
|
|
35
|
+
let nitroRuntimeConfigReader;
|
|
36
|
+
function provideCloudflareRuntimeConfig(read) {
|
|
37
|
+
nitroRuntimeConfigReader = read;
|
|
38
|
+
}
|
|
39
|
+
function useCloudflareRuntimeConfig(event) {
|
|
40
|
+
if (!nitroRuntimeConfigReader) {
|
|
41
|
+
throw new Error(
|
|
42
|
+
"[nuxt-cloudflare] No Nitro runtime config reader is available. Keep the module enabled, or call provideCloudflareRuntimeConfig() at the host boundary."
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
if (event)
|
|
46
|
+
return nitroRuntimeConfigReader(event);
|
|
47
|
+
const env = resolveCloudflareBindings();
|
|
48
|
+
return nitroRuntimeConfigReader(env ? runtimeConfigSource(env) : void 0);
|
|
33
49
|
}
|
|
34
50
|
function createCloudflareBindings() {
|
|
35
51
|
function get(name, source) {
|
|
@@ -49,4 +65,4 @@ function createCloudflareBindings() {
|
|
|
49
65
|
};
|
|
50
66
|
}
|
|
51
67
|
|
|
52
|
-
export { createCloudflareBindings, mergeCloudflareBindings, resolveCloudflareBindings, runtimeConfigSource, setCloudflareBindings };
|
|
68
|
+
export { createCloudflareBindings, mergeCloudflareBindings, provideCloudflareRuntimeConfig, resolveCloudflareBindings, runtimeConfigSource, setCloudflareBindings, useCloudflareRuntimeConfig };
|
package/dist/cache.d.mts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache headers for a Cloudflare route rule.
|
|
3
|
+
*
|
|
4
|
+
* Written for `nuxt.config.ts`, so it is a pure value producer with no runtime
|
|
5
|
+
* and no side effects. It returns the same plain literal you would write by
|
|
6
|
+
* hand, which means the module's build validator and its `beforeResponse`
|
|
7
|
+
* contract see exactly what they would have seen anyway. There is no marker, no
|
|
8
|
+
* exemption, and no second source of truth.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* routeRules: {
|
|
12
|
+
* '/api/feed': edgeCache({ maxAge: 60 }),
|
|
13
|
+
* '/api/reports': edgeCache({ maxAge: 3600, staleWhileRevalidate: 86400, browser: 'revalidate' }),
|
|
14
|
+
* '/api/private': NO_STORE,
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* The reason it exists is one rule that is easy to get wrong and silent when
|
|
19
|
+
* you do: **never emit `s-maxage`**. Cloudflare reads it as implying
|
|
20
|
+
* `proxy-revalidate`, which disables `stale-while-revalidate` and
|
|
21
|
+
* `stale-if-error` outright, so a policy that looks like it serves stale
|
|
22
|
+
* quietly blocks on revalidation instead. Three separate sites hand-wrote this
|
|
23
|
+
* pattern and all three left a comment about the same trap.
|
|
24
|
+
*/
|
|
25
|
+
interface EdgeCacheOptions {
|
|
26
|
+
/**
|
|
27
|
+
* Seconds a shared cache serves this without revalidating.
|
|
28
|
+
*
|
|
29
|
+
* Emitted as `max-age`, never `s-maxage`, for the reason above. Cloudflare
|
|
30
|
+
* falls back to `max-age` for the edge when `s-maxage` is absent, so this
|
|
31
|
+
* bounds the edge either way.
|
|
32
|
+
*/
|
|
33
|
+
maxAge: number;
|
|
34
|
+
/** Seconds a stale copy may be served while a fresh one is fetched behind it. */
|
|
35
|
+
staleWhileRevalidate?: number;
|
|
36
|
+
/** Seconds a stale copy may be served while the origin is failing. */
|
|
37
|
+
staleIfError?: number;
|
|
38
|
+
/**
|
|
39
|
+
* What browsers get.
|
|
40
|
+
*
|
|
41
|
+
* - `'no-store'` (default) emits no `cache-control`, so the module's own
|
|
42
|
+
* fail-closed floor stands and only the edge caches.
|
|
43
|
+
* - `'revalidate'` emits `public, max-age=0`, so a browser always asks but
|
|
44
|
+
* the edge usually answers.
|
|
45
|
+
* - `{ maxAge }` gives browsers a real lifetime of their own.
|
|
46
|
+
*/
|
|
47
|
+
browser?: 'no-store' | 'revalidate' | {
|
|
48
|
+
maxAge: number;
|
|
49
|
+
immutable?: boolean;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Append `private="set-cookie"`.
|
|
53
|
+
*
|
|
54
|
+
* A qualified `private` names the fields a shared cache must drop rather than
|
|
55
|
+
* refusing the response, so a response that sets a cookie is still storable
|
|
56
|
+
* with the cookie stripped from the stored copy. Without it, any `Set-Cookie`
|
|
57
|
+
* makes the response unstorable.
|
|
58
|
+
*/
|
|
59
|
+
dropSetCookie?: boolean;
|
|
60
|
+
}
|
|
61
|
+
interface EdgeCacheRule {
|
|
62
|
+
headers: Record<string, string>;
|
|
63
|
+
}
|
|
64
|
+
/** Never stored anywhere. The explicit form of the module's default. */
|
|
65
|
+
declare const NO_STORE: EdgeCacheRule;
|
|
66
|
+
declare function edgeCache(options: EdgeCacheOptions): EdgeCacheRule;
|
|
67
|
+
|
|
68
|
+
export { NO_STORE, edgeCache };
|
|
69
|
+
export type { EdgeCacheOptions, EdgeCacheRule };
|
package/dist/cache.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const NO_STORE = {
|
|
2
|
+
headers: { "cache-control": "private, no-store" }
|
|
3
|
+
};
|
|
4
|
+
function directives(parts) {
|
|
5
|
+
return parts.filter((part) => Boolean(part)).join(", ");
|
|
6
|
+
}
|
|
7
|
+
function edgeCache(options) {
|
|
8
|
+
if (!Number.isFinite(options.maxAge) || options.maxAge <= 0) {
|
|
9
|
+
throw new Error(
|
|
10
|
+
`[nuxt-cloudflare] edgeCache needs a positive maxAge, received ${options.maxAge}. Use NO_STORE for a route that must never be cached.`
|
|
11
|
+
);
|
|
12
|
+
}
|
|
13
|
+
const qualified = options.dropSetCookie ? 'private="set-cookie"' : void 0;
|
|
14
|
+
const edge = directives([
|
|
15
|
+
"public",
|
|
16
|
+
`max-age=${Math.floor(options.maxAge)}`,
|
|
17
|
+
options.staleWhileRevalidate ? `stale-while-revalidate=${Math.floor(options.staleWhileRevalidate)}` : void 0,
|
|
18
|
+
options.staleIfError ? `stale-if-error=${Math.floor(options.staleIfError)}` : void 0,
|
|
19
|
+
qualified
|
|
20
|
+
]);
|
|
21
|
+
const headers = { "cloudflare-cdn-cache-control": edge };
|
|
22
|
+
const browser = options.browser ?? "no-store";
|
|
23
|
+
if (browser === "revalidate") {
|
|
24
|
+
headers["cache-control"] = directives(["public", "max-age=0", qualified]);
|
|
25
|
+
} else if (typeof browser === "object") {
|
|
26
|
+
if (!Number.isFinite(browser.maxAge) || browser.maxAge < 0)
|
|
27
|
+
throw new Error(`[nuxt-cloudflare] edgeCache browser.maxAge must be zero or more, received ${browser.maxAge}.`);
|
|
28
|
+
headers["cache-control"] = directives([
|
|
29
|
+
"public",
|
|
30
|
+
`max-age=${Math.floor(browser.maxAge)}`,
|
|
31
|
+
browser.immutable ? "immutable" : void 0,
|
|
32
|
+
qualified
|
|
33
|
+
]);
|
|
34
|
+
}
|
|
35
|
+
return { headers };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export { NO_STORE, edgeCache };
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
2
|
import { resolve } from 'pathe';
|
|
3
3
|
import { experimental_generateTypes } from 'wrangler';
|
|
4
|
-
import {
|
|
5
|
-
import { readWranglerConfigFile } from '../wrangler.mjs';
|
|
4
|
+
import { readAuthoredWranglerConfig } from '../wrangler.mjs';
|
|
6
5
|
import 'node:fs';
|
|
7
6
|
import 'confbox';
|
|
8
7
|
|
|
@@ -70,16 +69,11 @@ function canonicalizeBindingEnvironment(environment) {
|
|
|
70
69
|
function createBindingTypeSignature(environment, runtime) {
|
|
71
70
|
return `${canonicalizeBindingEnvironment(environment)}\0${runtime.replaceAll("\r\n", "\n")}`;
|
|
72
71
|
}
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
if (
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
if (loaded._tag === "loaded")
|
|
79
|
-
return loaded.config;
|
|
80
|
-
if (loaded._tag === "missing")
|
|
81
|
-
return {};
|
|
82
|
-
throw new SyntaxError(`Invalid Wrangler config "${path}": ${loaded.reason}`);
|
|
72
|
+
function readAuthoredConfig(rootDir) {
|
|
73
|
+
const authored = readAuthoredWranglerConfig(rootDir);
|
|
74
|
+
if (authored._tag === "invalid")
|
|
75
|
+
throw new SyntaxError(`Invalid Wrangler config "${authored.path}": ${authored.reason}`);
|
|
76
|
+
return authored._tag === "authored" ? authored.config : {};
|
|
83
77
|
}
|
|
84
78
|
async function generateCloudflareBindingTypes(options) {
|
|
85
79
|
const directory = resolve(options.buildDir, "nuxt-cloudflare");
|
|
@@ -103,7 +97,7 @@ async function generateCloudflareBindingTypes(options) {
|
|
|
103
97
|
};
|
|
104
98
|
}
|
|
105
99
|
async function prepareCloudflareBindingTypes(options) {
|
|
106
|
-
const authored =
|
|
100
|
+
const authored = readAuthoredConfig(options.rootDir);
|
|
107
101
|
const config = mergeDefaults(options.wrangler, authored);
|
|
108
102
|
return generateCloudflareBindingTypes({ ...options, config });
|
|
109
103
|
}
|
package/dist/cli/index.mjs
CHANGED
|
@@ -5,7 +5,8 @@ import { resolve } from 'pathe';
|
|
|
5
5
|
import { d as discoverWranglerSourceConfigs, a as diagnoseWranglerSourceConfigs, p as parseWranglerAllowedWarnings, e as evaluateWranglerDiagnostics } from '../shared/nuxt-cloudflare.6X-qzF_b.mjs';
|
|
6
6
|
import { diagnoseWranglerConfig, formatWranglerDiagnostics } from '../wrangler.mjs';
|
|
7
7
|
import { readProjectWranglerConfig } from '../chunks/wrangler-reader.mjs';
|
|
8
|
-
import 'node:fs';
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
9
10
|
import 'node:fs/promises';
|
|
10
11
|
import 'confbox';
|
|
11
12
|
import 'wrangler';
|
|
@@ -47,6 +48,15 @@ function diagnoseWranglerProject(options) {
|
|
|
47
48
|
};
|
|
48
49
|
}
|
|
49
50
|
|
|
51
|
+
function readCliVersion() {
|
|
52
|
+
const path = fileURLToPath(new URL("../../package.json", import.meta.url));
|
|
53
|
+
const manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
54
|
+
const version = manifest !== null && typeof manifest === "object" ? manifest.version : void 0;
|
|
55
|
+
if (typeof version !== "string")
|
|
56
|
+
throw new TypeError(`Package manifest "${path}" declares no version.`);
|
|
57
|
+
return version;
|
|
58
|
+
}
|
|
59
|
+
|
|
50
60
|
const doctor = defineCommand({
|
|
51
61
|
meta: { name: "doctor", description: "Audit the effective Wrangler configuration" },
|
|
52
62
|
args: {
|
|
@@ -104,7 +114,7 @@ const doctor = defineCommand({
|
|
|
104
114
|
const main = defineCommand({
|
|
105
115
|
meta: {
|
|
106
116
|
name: "nuxt-cloudflare",
|
|
107
|
-
version:
|
|
117
|
+
version: readCliVersion(),
|
|
108
118
|
description: "Cloudflare deployment defaults and diagnostics for Nuxt"
|
|
109
119
|
},
|
|
110
120
|
subCommands: { doctor }
|
package/dist/module.d.mts
CHANGED
|
@@ -41,9 +41,32 @@ interface NitroCloudflareShape {
|
|
|
41
41
|
storage?: Record<string, NitroStorageMount>;
|
|
42
42
|
}
|
|
43
43
|
declare function findPopulatedRuntimeSecretPaths(config: unknown, environment: Readonly<Record<string, string | undefined>>): string[];
|
|
44
|
-
|
|
44
|
+
interface NitroCloudflareContext {
|
|
45
|
+
/** The project directory Wrangler and Nitro read the authored config from. */
|
|
46
|
+
rootDir?: string;
|
|
47
|
+
/** Whether Nuxt emits server source maps. */
|
|
48
|
+
serverSourceMaps?: boolean;
|
|
49
|
+
}
|
|
50
|
+
declare function configureNitroCloudflare(nitro: NitroCloudflareShape, options: ModuleOptions, context?: NitroCloudflareContext): void;
|
|
51
|
+
type BindingTypeAudit = {
|
|
52
|
+
_tag: 'compare';
|
|
53
|
+
signature: string;
|
|
54
|
+
} | {
|
|
55
|
+
_tag: 'missing';
|
|
56
|
+
} | {
|
|
57
|
+
_tag: 'skipped';
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* Decides whether the build compares generated binding types with the final
|
|
61
|
+
* Wrangler config.
|
|
62
|
+
*
|
|
63
|
+
* The signature exists only after the type template regenerates. A build that
|
|
64
|
+
* reuses a cached template must fail, not skip: a skipped comparison reports a
|
|
65
|
+
* clean build for types that no longer match the deployed config.
|
|
66
|
+
*/
|
|
67
|
+
declare function resolveBindingTypeAudit(bindingTypes: boolean | undefined, signature: string | undefined): BindingTypeAudit;
|
|
45
68
|
declare function setupCloudflareModule(options: ModuleOptions, nuxt: Nuxt): void;
|
|
46
69
|
declare const _default: any;
|
|
47
70
|
|
|
48
|
-
export { configureNitroCloudflare, _default as default, findPopulatedRuntimeSecretPaths, setupCloudflareModule };
|
|
49
|
-
export type { ModuleOptions, NitroCloudflareShape };
|
|
71
|
+
export { configureNitroCloudflare, _default as default, findPopulatedRuntimeSecretPaths, resolveBindingTypeAudit, setupCloudflareModule };
|
|
72
|
+
export type { BindingTypeAudit, ModuleOptions, NitroCloudflareContext, NitroCloudflareShape };
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import process from 'node:process';
|
|
|
2
2
|
import { useLogger, defineNuxtModule, hasNuxtModule, addTypeTemplate } from '@nuxt/kit';
|
|
3
3
|
import { resolve } from 'pathe';
|
|
4
4
|
import { a as diagnoseWranglerSourceConfigs, d as discoverWranglerSourceConfigs, e as evaluateWranglerDiagnostics } from './shared/nuxt-cloudflare.6X-qzF_b.mjs';
|
|
5
|
-
import {
|
|
5
|
+
import { resolveHtmlCacheGuarantee, staleDirectivesAreDisabled } from '../dist/runtime/server/utils/workers-cache.js';
|
|
6
|
+
import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, applyCloudflareDefaults } from './wrangler.mjs';
|
|
6
7
|
import 'node:fs';
|
|
7
8
|
import 'node:fs/promises';
|
|
8
9
|
import 'confbox';
|
|
@@ -105,6 +106,10 @@ const wideEventsPluginPath = resolve(
|
|
|
105
106
|
import.meta.dirname,
|
|
106
107
|
import.meta.url.endsWith(".ts") ? "runtime/server/plugins/wide-events.ts" : "runtime/server/plugins/wide-events.js"
|
|
107
108
|
);
|
|
109
|
+
const runtimeConfigPluginPath = resolve(
|
|
110
|
+
import.meta.dirname,
|
|
111
|
+
import.meta.url.endsWith(".ts") ? "runtime/server/plugins/runtime-config.ts" : "runtime/server/plugins/runtime-config.js"
|
|
112
|
+
);
|
|
108
113
|
const WIDE_EVENT_FIELDS = [
|
|
109
114
|
"cf.colo",
|
|
110
115
|
"cf.country",
|
|
@@ -144,7 +149,15 @@ function findPopulatedRuntimeSecretPaths(config, environment) {
|
|
|
144
149
|
visit(config, []);
|
|
145
150
|
return paths;
|
|
146
151
|
}
|
|
147
|
-
function
|
|
152
|
+
function addNitroPlugin(nitro, path) {
|
|
153
|
+
nitro.plugins ??= [];
|
|
154
|
+
if (!nitro.plugins.includes(path))
|
|
155
|
+
nitro.plugins.push(path);
|
|
156
|
+
}
|
|
157
|
+
function configureNitroCloudflare(nitro, options, context = {}) {
|
|
158
|
+
const authored = readAuthoredWranglerConfig(context.rootDir);
|
|
159
|
+
if (authored._tag === "invalid")
|
|
160
|
+
throw new Error(`[nuxt-cloudflare] Wrangler config "${authored.path}" cannot be parsed: ${authored.reason}`);
|
|
148
161
|
nitro.preset ??= "cloudflare-module";
|
|
149
162
|
nitro.cloudflare ??= {};
|
|
150
163
|
nitro.cloudflare.deployConfig = true;
|
|
@@ -154,15 +167,13 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
|
|
|
154
167
|
logsSampleRate: options.logsSampleRate,
|
|
155
168
|
requiredSecrets: options.requiredSecrets,
|
|
156
169
|
tracesSampleRate: options.tracesSampleRate,
|
|
157
|
-
uploadSourceMaps: options.sourceMaps ?? nitro.sourceMap ??
|
|
170
|
+
uploadSourceMaps: options.sourceMaps ?? nitro.sourceMap ?? context.serverSourceMaps ?? false,
|
|
158
171
|
versionMetadataBinding: options.versionMetadataBinding,
|
|
159
172
|
workersCache: resolveModuleWorkersCachePolicy(options)
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
nitro.plugins.push(workersCachePluginPath);
|
|
165
|
-
}
|
|
173
|
+
}, authored._tag === "authored" ? authored.config : {});
|
|
174
|
+
addNitroPlugin(nitro, runtimeConfigPluginPath);
|
|
175
|
+
if (nitro.cloudflare.wrangler.cache?.enabled)
|
|
176
|
+
addNitroPlugin(nitro, workersCachePluginPath);
|
|
166
177
|
if (options.kvCache === false)
|
|
167
178
|
return;
|
|
168
179
|
const cache = nitro.storage?.cache;
|
|
@@ -177,6 +188,11 @@ function configureNitroCloudflare(nitro, options, nuxtServerSourceMaps) {
|
|
|
177
188
|
defaultTtl: configuredCache?.defaultTtl ?? 30 * 24 * 60 * 60
|
|
178
189
|
};
|
|
179
190
|
}
|
|
191
|
+
function resolveBindingTypeAudit(bindingTypes, signature) {
|
|
192
|
+
if (bindingTypes === false)
|
|
193
|
+
return { _tag: "skipped" };
|
|
194
|
+
return signature ? { _tag: "compare", signature } : { _tag: "missing" };
|
|
195
|
+
}
|
|
180
196
|
async function auditGeneratedWranglerConfig(nitro, options, buildDir, rootDir, bindingTypeSignature) {
|
|
181
197
|
const path = resolve(nitro.options.output.serverDir, "wrangler.json");
|
|
182
198
|
const result = await readWranglerJsonFile(path);
|
|
@@ -188,13 +204,19 @@ async function auditGeneratedWranglerConfig(nitro, options, buildDir, rootDir, b
|
|
|
188
204
|
const validated = readProjectWranglerConfig({ config: path, cwd: rootDir });
|
|
189
205
|
if (validated._tag === "invalid")
|
|
190
206
|
throw new Error("[nuxt-cloudflare] Generated Wrangler config fails Wrangler schema validation. Run Wrangler locally for validation details.");
|
|
191
|
-
|
|
207
|
+
const audit = resolveBindingTypeAudit(options.bindingTypes, bindingTypeSignature);
|
|
208
|
+
if (audit._tag === "missing") {
|
|
209
|
+
throw new Error(
|
|
210
|
+
"[nuxt-cloudflare] Cloudflare binding types were not generated during this build, so the drift check could not run. Run `nuxt prepare`, or set `bindingTypes: false` when another tool owns the declaration."
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
if (audit._tag === "compare") {
|
|
192
214
|
const { assertCloudflareBindingTypesCurrent } = await import('./chunks/binding-types.mjs');
|
|
193
215
|
await assertCloudflareBindingTypesCurrent({
|
|
194
216
|
buildDir,
|
|
195
217
|
compatibilityDate: result.config.compatibility_date,
|
|
196
218
|
config: result.config,
|
|
197
|
-
expectedSignature:
|
|
219
|
+
expectedSignature: audit.signature,
|
|
198
220
|
nodeCompat: Boolean(nitro.options.cloudflare?.nodeCompat)
|
|
199
221
|
});
|
|
200
222
|
}
|
|
@@ -225,17 +247,17 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
225
247
|
const configure = () => configureNitroCloudflare(
|
|
226
248
|
nuxt.options.nitro,
|
|
227
249
|
options,
|
|
228
|
-
|
|
250
|
+
{
|
|
251
|
+
rootDir: nuxt.options.rootDir,
|
|
252
|
+
serverSourceMaps: Boolean(nuxt.options.sourcemap.server)
|
|
253
|
+
}
|
|
229
254
|
);
|
|
230
255
|
const registerWideEventFields = nuxt.hook;
|
|
231
256
|
registerWideEventFields("wide-events:fields", (registry) => {
|
|
232
257
|
registry.add("@harlan-zw/nuxt-cloudflare", [...WIDE_EVENT_FIELDS]);
|
|
233
258
|
});
|
|
234
259
|
if (Array.isArray(nuxt.options.modules) && hasNuxtModule("@harlan-zw/nuxt-wide-events", nuxt)) {
|
|
235
|
-
|
|
236
|
-
wideEventsNitro.plugins ??= [];
|
|
237
|
-
if (!wideEventsNitro.plugins.includes(wideEventsPluginPath))
|
|
238
|
-
wideEventsNitro.plugins.push(wideEventsPluginPath);
|
|
260
|
+
addNitroPlugin(nuxt.options.nitro, wideEventsPluginPath);
|
|
239
261
|
}
|
|
240
262
|
let bindingTypeSignature;
|
|
241
263
|
if (options.bindingTypes !== false) {
|
|
@@ -270,9 +292,37 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
270
292
|
}
|
|
271
293
|
});
|
|
272
294
|
nuxt.hook("nitro:config", (nitroConfig) => {
|
|
273
|
-
|
|
295
|
+
const policy = resolveModuleWorkersCachePolicy(options);
|
|
296
|
+
if (policy._tag === "disabled")
|
|
274
297
|
return;
|
|
275
|
-
const
|
|
298
|
+
const mode = policy.html ?? "auto";
|
|
299
|
+
const guarantee = resolveHtmlCacheGuarantee(nuxt.options.runtimeConfig.htmlCacheCapabilities);
|
|
300
|
+
nuxt.options.runtimeConfig.nuxtCloudflare = {
|
|
301
|
+
...typeof nuxt.options.runtimeConfig.nuxtCloudflare === "object" ? nuxt.options.runtimeConfig.nuxtCloudflare : {},
|
|
302
|
+
htmlCacheMode: mode
|
|
303
|
+
};
|
|
304
|
+
if (mode === "app") {
|
|
305
|
+
logger.info("Workers Cache honours your HTML cache rules. You own the version-skew risk.");
|
|
306
|
+
} else if (guarantee._tag === "bounded" && mode === "auto") {
|
|
307
|
+
logger.info(`${guarantee.by} guarantees chunks for ${guarantee.ceilingSeconds}s. Workers Cache honours your HTML cache rules up to that limit.`);
|
|
308
|
+
} else {
|
|
309
|
+
logger.info("Workers Cache is on. HTML documents get `private, no-store`. A module must guarantee chunk retention to change this.");
|
|
310
|
+
}
|
|
311
|
+
if (mode === "app" || guarantee._tag === "bounded")
|
|
312
|
+
logger.info("A shared cache keys on the URL. If a page changes with a request header, set `Vary` on it. Responses varying on Cookie or Authorization are never shared.");
|
|
313
|
+
for (const [route, rule] of Object.entries(nitroConfig.routeRules ?? {})) {
|
|
314
|
+
const headers = rule?.headers;
|
|
315
|
+
if (!headers)
|
|
316
|
+
continue;
|
|
317
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
318
|
+
if (!name.toLowerCase().endsWith("cache-control"))
|
|
319
|
+
continue;
|
|
320
|
+
if (staleDirectivesAreDisabled(value))
|
|
321
|
+
logger.warn(`routeRules['${route}'] sets \`${name}: ${value}\`. Cloudflare disables stale serving when \`s-maxage\`, \`must-revalidate\` or \`proxy-revalidate\` is present. Use \`max-age\` for the edge freshness window instead.`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const relaxable = mode === "app" || guarantee._tag === "bounded";
|
|
325
|
+
const violations = findHtmlCacheRouteRuleViolations(nitroConfig.routeRules).filter((violation) => !(relaxable && violation._tag === "html-cache-header"));
|
|
276
326
|
const warnings = violations.filter((violation) => violation.severity === "warning");
|
|
277
327
|
const errors = violations.filter((violation) => violation.severity === "error");
|
|
278
328
|
if (warnings.length > 0)
|
|
@@ -280,12 +330,15 @@ function setupCloudflareModule(options, nuxt) {
|
|
|
280
330
|
if (errors.length > 0) {
|
|
281
331
|
throw new Error(
|
|
282
332
|
`[nuxt-cloudflare] HTML route rules conflict with Workers Caching:
|
|
283
|
-
${formatHtmlCacheRouteRuleViolations(errors)}
|
|
333
|
+
${formatHtmlCacheRouteRuleViolations(errors)}
|
|
334
|
+
A chunk-retention guarantee does not cover these. A prerendered route is served by Workers Assets, and a cache/swr/isr rule stores the response in nitro's own path-keyed cache. Use a plain \`cache-control\` header rule instead, or set \`nuxtCloudflare.workersCache.html: 'app'\` to own the risk.`
|
|
284
335
|
);
|
|
285
336
|
}
|
|
286
337
|
});
|
|
287
338
|
if (!nuxt.options.dev) {
|
|
288
339
|
nuxt.hook("nitro:init", (nitro) => {
|
|
340
|
+
if (!nitro.options.preset?.includes("cloudflare"))
|
|
341
|
+
return;
|
|
289
342
|
nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(
|
|
290
343
|
nitro,
|
|
291
344
|
options,
|
|
@@ -315,4 +368,4 @@ const module$1 = defineNuxtModule({
|
|
|
315
368
|
setup: setupCloudflareModule
|
|
316
369
|
});
|
|
317
370
|
|
|
318
|
-
export { configureNitroCloudflare, module$1 as default, findPopulatedRuntimeSecretPaths, setupCloudflareModule };
|
|
371
|
+
export { configureNitroCloudflare, module$1 as default, findPopulatedRuntimeSecretPaths, resolveBindingTypeAudit, setupCloudflareModule };
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hands Nitro's runtime config reader to `useCloudflareRuntimeConfig`.
|
|
3
|
+
*
|
|
4
|
+
* Nitro bundles its plugins, so this file resolves `nitropack/runtime`. The
|
|
5
|
+
* bindings module cannot: applications import it outside a Nitro bundle, where
|
|
6
|
+
* that specifier fails to resolve.
|
|
7
|
+
*/
|
|
8
|
+
declare const _default: import("nitropack").NitroAppPlugin;
|
|
9
|
+
export default _default;
|