@harlan-zw/nuxt-cloudflare 0.1.0 → 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 CHANGED
@@ -65,7 +65,39 @@ Cloudflare KV requires TTLs of at least 60 seconds. The cache wrapper raises sho
65
65
 
66
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.
67
67
 
68
- Workers Caching is separate from Nitro's KV-backed cache. The module enables version-isolated caching by default. Rendered HTML always stays private. API and asset responses keep explicit cache policies. Set `workersCache: { _tag: 'disabled' }` to opt out. Choose cross-version caching only with an explicit purge path.
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.
69
101
 
70
102
  ## Cost controls
71
103
 
@@ -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 };
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=4.5.0 <5.0.0"
6
6
  },
7
- "version": "0.1.0",
7
+ "version": "0.2.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "1.0.3",
10
10
  "unbuild": "3.6.1"
package/dist/module.mjs CHANGED
@@ -2,6 +2,7 @@ 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 { resolveHtmlCacheGuarantee, staleDirectivesAreDisabled } from '../dist/runtime/server/utils/workers-cache.js';
5
6
  import { readWranglerJsonFile, diagnoseWranglerConfig, formatWranglerDiagnostics, readAuthoredWranglerConfig, applyCloudflareDefaults } from './wrangler.mjs';
6
7
  import 'node:fs';
7
8
  import 'node:fs/promises';
@@ -291,9 +292,37 @@ function setupCloudflareModule(options, nuxt) {
291
292
  }
292
293
  });
293
294
  nuxt.hook("nitro:config", (nitroConfig) => {
294
- if (resolveModuleWorkersCachePolicy(options)._tag === "disabled")
295
+ const policy = resolveModuleWorkersCachePolicy(options);
296
+ if (policy._tag === "disabled")
295
297
  return;
296
- const violations = findHtmlCacheRouteRuleViolations(nitroConfig.routeRules);
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"));
297
326
  const warnings = violations.filter((violation) => violation.severity === "warning");
298
327
  const errors = violations.filter((violation) => violation.severity === "error");
299
328
  if (warnings.length > 0)
@@ -301,12 +330,15 @@ function setupCloudflareModule(options, nuxt) {
301
330
  if (errors.length > 0) {
302
331
  throw new Error(
303
332
  `[nuxt-cloudflare] HTML route rules conflict with Workers Caching:
304
- ${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.`
305
335
  );
306
336
  }
307
337
  });
308
338
  if (!nuxt.options.dev) {
309
339
  nuxt.hook("nitro:init", (nitro) => {
340
+ if (!nitro.options.preset?.includes("cloudflare"))
341
+ return;
310
342
  nitro.hooks.hook("compiled", () => auditGeneratedWranglerConfig(
311
343
  nitro,
312
344
  options,
@@ -1,14 +1,90 @@
1
- import { getResponseHeader, setResponseHeader } from "h3";
2
- import { defineNitroPlugin } from "nitropack/runtime";
3
- import { hasExplicitCachePolicy, withHtmlNoStoreHeaders } from "../utils/workers-cache.js";
1
+ import { getHeader, getResponseHeader, getResponseStatus, setResponseHeader } from "h3";
2
+ import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
3
+ import {
4
+ clampSharedCacheSeconds,
5
+ NO_STORE_BROWSER,
6
+ NO_STORE_EDGE,
7
+ resolveHtmlCacheGuarantee,
8
+ responseCacheDecision,
9
+ sharedCacheSeconds,
10
+ statedPolicy
11
+ } from "../utils/workers-cache.js";
12
+ const warned = /* @__PURE__ */ new Set();
13
+ const WARN_LIMIT = 200;
14
+ function warnOnce(kind, path, message) {
15
+ const key = `${kind}:${path.split("?")[0]}`;
16
+ if (warned.has(key))
17
+ return;
18
+ if (warned.size >= WARN_LIMIT)
19
+ return;
20
+ warned.add(key);
21
+ console.warn(`[nuxt-cloudflare] ${message}`);
22
+ }
23
+ const CREDENTIAL_HEADERS = [
24
+ "cookie",
25
+ "authorization",
26
+ "proxy-authorization",
27
+ "cf-access-jwt-assertion",
28
+ "cf-access-client-id",
29
+ "x-api-key"
30
+ ];
31
+ function isAuthenticated(event) {
32
+ return CREDENTIAL_HEADERS.some((name) => Boolean(getHeader(event, name)));
33
+ }
34
+ const DOCUMENT_TYPE_RE = /^(?:text\/html|application\/xhtml\+xml)\s*(?:;|$)/i;
35
+ function isDocumentResponse(event) {
36
+ const type = getResponseHeader(event, "content-type");
37
+ return typeof type === "string" && DOCUMENT_TYPE_RE.test(type);
38
+ }
4
39
  export default defineNitroPlugin((nitroApp) => {
5
- nitroApp.hooks.hook("render:response", (response) => {
6
- response.headers = withHtmlNoStoreHeaders(response.headers);
40
+ nitroApp.hooks.hook("request", (event) => {
41
+ setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
7
42
  });
8
43
  nitroApp.hooks.hook("beforeResponse", (event) => {
9
- if (hasExplicitCachePolicy((name) => getResponseHeader(event, name)))
44
+ const config = useRuntimeConfig(event);
45
+ const mode = config.nuxtCloudflare?.htmlCacheMode ?? "auto";
46
+ const edge = getResponseHeader(event, "cloudflare-cdn-cache-control") ?? getResponseHeader(event, "cdn-cache-control");
47
+ const browser = getResponseHeader(event, "cache-control");
48
+ const appBrowser = browser === NO_STORE_BROWSER ? void 0 : browser;
49
+ const carrier = edge ?? appBrowser;
50
+ const decision = responseCacheDecision({
51
+ mode,
52
+ guarantee: resolveHtmlCacheGuarantee(config.htmlCacheCapabilities),
53
+ isDocument: isDocumentResponse(event),
54
+ stated: statedPolicy((name) => name === "cache-control" ? appBrowser : getResponseHeader(event, name)),
55
+ requestedSeconds: sharedCacheSeconds(carrier),
56
+ status: getResponseStatus(event),
57
+ authenticated: isAuthenticated(event),
58
+ setsCookie: Boolean(getResponseHeader(event, "set-cookie")),
59
+ vary: getResponseHeader(event, "vary")
60
+ });
61
+ if (decision._tag === "leave")
10
62
  return;
11
- setResponseHeader(event, "cache-control", "private, no-store");
12
- setResponseHeader(event, "cloudflare-cdn-cache-control", "no-store");
63
+ if (decision._tag === "floor") {
64
+ setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
65
+ setResponseHeader(event, "cloudflare-cdn-cache-control", NO_STORE_EDGE);
66
+ return;
67
+ }
68
+ if (decision._tag === "clamp") {
69
+ if (edge) {
70
+ setResponseHeader(event, "cloudflare-cdn-cache-control", clampSharedCacheSeconds(String(edge), decision.toSeconds));
71
+ }
72
+ if (appBrowser) {
73
+ setResponseHeader(event, "cache-control", clampSharedCacheSeconds(String(appBrowser), decision.toSeconds));
74
+ }
75
+ warnOnce(
76
+ "clamp",
77
+ event.path,
78
+ `Route ${event.path.split("?")[0]} asked to be cached for ${decision.fromSeconds}s. ${decision.by} covers ${decision.toSeconds}s. The value was lowered.`
79
+ );
80
+ return;
81
+ }
82
+ warnOnce(
83
+ "override",
84
+ event.path,
85
+ `The response for ${event.path.split("?")[0]} set \`cache-control: ${String(carrier)}\`. Workers Cache replaced it because ${decision.reason}. To keep your value, set \`nuxtCloudflare.workersCache.html: 'app'\`.`
86
+ );
87
+ setResponseHeader(event, "cache-control", NO_STORE_BROWSER);
88
+ setResponseHeader(event, "cloudflare-cdn-cache-control", NO_STORE_EDGE);
13
89
  });
14
90
  });
@@ -1,2 +1,162 @@
1
- export declare function hasExplicitCachePolicy(getHeader: (name: string) => unknown): boolean;
2
- export declare function withHtmlNoStoreHeaders(headers?: Record<string, string>): Record<string, string>;
1
+ /**
2
+ * Who owns `Cache-Control` on an HTML document.
3
+ *
4
+ * Workers Cache makes a headerless 200 cacheable for two hours, so a document
5
+ * with no policy has to be given one. This module supplies that floor. What it
6
+ * must not do is overwrite a policy the app wrote on purpose, which is what an
7
+ * earlier version did from `render:response`: that hook receives a plain headers
8
+ * object and no event, so it cannot see what a route rule set, and being unable
9
+ * to check is exactly why it overwrote unconditionally.
10
+ *
11
+ * The floor now lives on the `request` hook and the decisions live here, at
12
+ * `beforeResponse`, where the whole response is visible.
13
+ *
14
+ * Two headers, two audiences, and only one of them carries version skew:
15
+ *
16
+ * - `Cloudflare-CDN-Cache-Control` feeds Workers Cache, whose key includes the
17
+ * Worker version at `cross_version_cache: false`. A deploy makes every stored
18
+ * response unreachable, so a cached document can never outlive its chunks.
19
+ * - `Cache-Control` reaches browsers, the zone cache and third-party CDNs, none
20
+ * of which know a deploy happened. That one needs a retention guarantee.
21
+ */
22
+ export declare const NO_STORE_BROWSER = "private, no-store";
23
+ export declare const NO_STORE_EDGE = "no-store";
24
+ /**
25
+ * How `Cache-Control` on an HTML document is resolved.
26
+ *
27
+ * - `no-store` always overwrite. The behaviour before any of this existed.
28
+ * - `auto` honour the app when a module guarantees chunk retention, clamped
29
+ * to what that module promises.
30
+ * - `app` always honour the app. You own the skew risk.
31
+ */
32
+ export type HtmlCacheMode = 'no-store' | 'auto' | 'app';
33
+ /**
34
+ * Published by any module that can promise a document outlives its build.
35
+ *
36
+ * Duplicated verbatim in `nuxt-skew-protection`. Kept to a versioned,
37
+ * field-only interface so the two copies cannot drift in behaviour, only in
38
+ * whether they know a version. An unknown `v` is ignored rather than guessed
39
+ * at, so a newer producer degrades to today's behaviour instead of to a wrong
40
+ * guarantee.
41
+ */
42
+ export interface HtmlCacheCapability {
43
+ v: 1;
44
+ by: string;
45
+ /** Seconds a document may outlive its build and still resolve every chunk. */
46
+ documentTtlCeilingSeconds: number;
47
+ basis: 'observed-retained-builds' | 'retention-days' | 'none';
48
+ /** Requests for a retired build's chunks resolve instead of 404. */
49
+ assetRecovery: boolean;
50
+ }
51
+ export type HtmlCacheGuarantee = {
52
+ _tag: 'none';
53
+ reason: 'no-capability' | 'no-asset-recovery' | 'zero-ceiling' | 'unknown-version';
54
+ } | {
55
+ _tag: 'bounded';
56
+ ceilingSeconds: number;
57
+ by: string;
58
+ };
59
+ /**
60
+ * The weakest promise across every publisher.
61
+ *
62
+ * Minimum rather than maximum: a guarantee is only as good as the module least
63
+ * able to keep it, and one publisher without asset recovery means a retired
64
+ * chunk 404s whatever the others retain.
65
+ */
66
+ export declare function resolveHtmlCacheGuarantee(capabilities: unknown): HtmlCacheGuarantee;
67
+ /**
68
+ * Seconds a shared cache may serve this response, or null if it was refused.
69
+ *
70
+ * Counts the stale window, because a stale response is still served. `no-cache`
71
+ * counts as a refusal: it permits storage but forbids reuse without
72
+ * revalidation, which is not what "the app asked for shared caching" means.
73
+ */
74
+ export declare function sharedCacheSeconds(cacheControl: unknown): number | null;
75
+ /** Whether the app stated any cache policy at all, however restrictive. */
76
+ export declare function statedPolicy(getHeader: (name: string) => unknown): boolean;
77
+ export type CacheDecision = {
78
+ _tag: 'leave';
79
+ } | {
80
+ _tag: 'floor';
81
+ } | {
82
+ _tag: 'clamp';
83
+ toSeconds: number;
84
+ fromSeconds: number;
85
+ by: string;
86
+ } | {
87
+ _tag: 'override';
88
+ reason: string;
89
+ };
90
+ export interface CacheDecisionInput {
91
+ mode: HtmlCacheMode;
92
+ guarantee: HtmlCacheGuarantee;
93
+ /** True only for a rendered HTML document, from the response content type. */
94
+ isDocument: boolean;
95
+ /** Whether the app set any cache header at all. */
96
+ stated: boolean;
97
+ /** The lifetime the app asked a shared cache for, if any. */
98
+ requestedSeconds: number | null;
99
+ status: number;
100
+ /** A credential on the request that could personalise the response. */
101
+ authenticated: boolean;
102
+ /** The response mints a cookie, so it carries state a shared copy must not. */
103
+ setsCookie: boolean;
104
+ /** The response's own `Vary`, if it set one. */
105
+ vary: string | undefined;
106
+ }
107
+ /**
108
+ * Whether a `Vary` can be satisfied by a cache keyed on the URL.
109
+ *
110
+ * A shared cache does not key on `Cookie` or `Authorization`, so a response
111
+ * asking it to vary on either is asking for something it cannot do, and storing
112
+ * it anyway serves one person's copy to everyone. `*` means never store.
113
+ *
114
+ * This module deliberately does not invent a `Vary` where the app set none.
115
+ * Injecting `Accept` or `Accept-Language` would collapse the hit rate for every
116
+ * route that does not negotiate, and would hide the app's own bug on the ones
117
+ * that do. The route rule asking for shared caching is the app's assertion that
118
+ * the route does not vary, and the build log says so out loud.
119
+ */
120
+ export declare function varyIsSatisfiable(vary: string | undefined): boolean;
121
+ /**
122
+ * What to do with one response.
123
+ *
124
+ * Only rendered documents are subject to the version-skew policy, because only
125
+ * a document names build chunks. Everything else, assets, API payloads,
126
+ * sitemaps, is the app's business and is left exactly as the app wrote it. An
127
+ * earlier revision of this applied the document rules to every response and
128
+ * rewrote nitro's own `/_nuxt/**` immutable rule to `private, no-store`.
129
+ *
130
+ * `leave` means untouched. `floor` means nobody stated a policy, so the safe
131
+ * default applies and nothing was taken. `override` means the app stated one
132
+ * and this module replaced it, which is the only outcome that owes a warning.
133
+ */
134
+ export declare function responseCacheDecision(input: CacheDecisionInput): CacheDecision;
135
+ /**
136
+ * The header with its total served lifetime brought inside the ceiling.
137
+ *
138
+ * Every directive that keeps a response servable is lowered, not just the
139
+ * freshness one. An earlier version rewrote `s-maxage` alone, so
140
+ * `s-maxage=300, stale-while-revalidate=86400` came back byte-identical while
141
+ * the code logged "the value was lowered": a shared cache would still serve
142
+ * that document for a day past the window the ceiling promises.
143
+ *
144
+ * `max-age` is lowered even when `s-maxage` is present. `s-maxage` decides what
145
+ * a shared cache does, but `max-age` still governs browsers and any cache that
146
+ * does not implement `s-maxage`, and those are the caches with no notion of a
147
+ * deploy.
148
+ *
149
+ * The stale window gets whatever budget is left after freshness, so
150
+ * `freshness + stale` can never exceed the ceiling.
151
+ */
152
+ export declare function clampSharedCacheSeconds(cacheControl: string, seconds: number): string;
153
+ /**
154
+ * Whether this header asks for stale serving that Cloudflare will ignore.
155
+ *
156
+ * `s-maxage`, `must-revalidate` and `proxy-revalidate` each forbid serving
157
+ * stale content, so pairing any of them with `stale-while-revalidate` or
158
+ * `stale-if-error` means those directives do nothing. All three sites that
159
+ * hand-wrote this policy left a comment about the trap, which is a good sign it
160
+ * deserves a warning rather than a comment.
161
+ */
162
+ export declare function staleDirectivesAreDisabled(cacheControl: unknown): boolean;
@@ -4,17 +4,140 @@ const CACHE_POLICY_HEADER_NAMES = [
4
4
  "cloudflare-cdn-cache-control",
5
5
  "expires"
6
6
  ];
7
- const HTML_CACHE_HEADER_NAMES = new Set(CACHE_POLICY_HEADER_NAMES.slice(0, 3));
8
- export function hasExplicitCachePolicy(getHeader) {
7
+ export const NO_STORE_BROWSER = "private, no-store";
8
+ export const NO_STORE_EDGE = "no-store";
9
+ function parseCapability(entry) {
10
+ if (!entry || typeof entry !== "object")
11
+ return null;
12
+ const candidate = entry;
13
+ if (candidate.v !== 1)
14
+ return null;
15
+ if (typeof candidate.documentTtlCeilingSeconds !== "number")
16
+ return null;
17
+ if (!Number.isInteger(candidate.documentTtlCeilingSeconds) || candidate.documentTtlCeilingSeconds <= 0)
18
+ return null;
19
+ if (typeof candidate.assetRecovery !== "boolean")
20
+ return null;
21
+ if (typeof candidate.by !== "string" || !candidate.by)
22
+ return null;
23
+ if (candidate.basis !== "observed-retained-builds" && candidate.basis !== "retention-days")
24
+ return null;
25
+ return {
26
+ v: 1,
27
+ by: candidate.by,
28
+ documentTtlCeilingSeconds: candidate.documentTtlCeilingSeconds,
29
+ basis: candidate.basis,
30
+ assetRecovery: candidate.assetRecovery
31
+ };
32
+ }
33
+ export function resolveHtmlCacheGuarantee(capabilities) {
34
+ if (!Array.isArray(capabilities) || capabilities.length === 0)
35
+ return { _tag: "none", reason: "no-capability" };
36
+ const known = capabilities.map(parseCapability);
37
+ if (known.includes(null))
38
+ return { _tag: "none", reason: "unknown-version" };
39
+ const parsed = known;
40
+ if (parsed.some((entry) => !entry.assetRecovery))
41
+ return { _tag: "none", reason: "no-asset-recovery" };
42
+ const ceiling = Math.min(...parsed.map((entry) => entry.documentTtlCeilingSeconds));
43
+ if (!Number.isFinite(ceiling) || ceiling <= 0)
44
+ return { _tag: "none", reason: "zero-ceiling" };
45
+ return { _tag: "bounded", ceilingSeconds: ceiling, by: parsed.map((entry) => entry.by).join(", ") };
46
+ }
47
+ function directive(value, name) {
48
+ const match = value.match(new RegExp(`(?:^|[,\\s])${name}\\s*=\\s*(\\d+)`, "gi"));
49
+ if (!match)
50
+ return void 0;
51
+ return Math.min(...match.map((part) => Number(part.replace(/\D+/g, ""))));
52
+ }
53
+ const MAX_SANE_SECONDS = 31536e3;
54
+ function unqualify(value) {
55
+ return value.replace(/=\s*"[^"]*"/g, '=""');
56
+ }
57
+ export function sharedCacheSeconds(cacheControl) {
58
+ const raw = Array.isArray(cacheControl) ? cacheControl.join(", ") : cacheControl;
59
+ if (typeof raw !== "string" || !raw)
60
+ return null;
61
+ const value = unqualify(raw.toLowerCase());
62
+ if (/(?:^|,)\s*no-store\s*(?:,|$)/.test(value))
63
+ return null;
64
+ if (/(?:^|,)\s*no-cache\s*(?:,|$)/.test(value))
65
+ return null;
66
+ if (/(?:^|,)\s*private\s*(?:,|$)/.test(value))
67
+ return null;
68
+ const shared = directive(value, "s-maxage") ?? directive(value, "max-age");
69
+ if (shared === void 0 || shared <= 0)
70
+ return null;
71
+ return Math.min(shared + (directive(value, "stale-while-revalidate") ?? 0), MAX_SANE_SECONDS);
72
+ }
73
+ export function statedPolicy(getHeader) {
9
74
  return CACHE_POLICY_HEADER_NAMES.some((name) => Boolean(getHeader(name)));
10
75
  }
11
- export function withHtmlNoStoreHeaders(headers = {}) {
12
- const preserved = Object.fromEntries(
13
- Object.entries(headers).filter(([name]) => !HTML_CACHE_HEADER_NAMES.has(name.toLowerCase()))
76
+ export function varyIsSatisfiable(vary) {
77
+ if (!vary)
78
+ return true;
79
+ const fields = vary.toLowerCase().split(",").map((field) => field.trim());
80
+ if (fields.includes("*"))
81
+ return false;
82
+ return !fields.includes("cookie") && !fields.includes("authorization");
83
+ }
84
+ const PRESERVED_STATUSES = /* @__PURE__ */ new Set([301, 304, 308]);
85
+ export function responseCacheDecision(input) {
86
+ if (!input.stated)
87
+ return { _tag: "floor" };
88
+ if (!input.isDocument)
89
+ return { _tag: "leave" };
90
+ if (PRESERVED_STATUSES.has(input.status))
91
+ return { _tag: "leave" };
92
+ if (input.requestedSeconds === null)
93
+ return { _tag: "leave" };
94
+ if (input.authenticated)
95
+ return { _tag: "override", reason: "the request carried credentials" };
96
+ if (input.setsCookie)
97
+ return { _tag: "override", reason: "the response set a cookie" };
98
+ if (!varyIsSatisfiable(input.vary))
99
+ return { _tag: "override", reason: `the response varies on \`${input.vary}\`, which a shared cache cannot key on` };
100
+ if (input.status !== 200)
101
+ return { _tag: "override", reason: `the response status was ${input.status}` };
102
+ if (input.mode === "no-store")
103
+ return { _tag: "override", reason: "workersCache.html is set to no-store" };
104
+ if (input.mode === "app")
105
+ return { _tag: "leave" };
106
+ if (input.guarantee._tag === "none")
107
+ return { _tag: "override", reason: `no module guarantees chunk retention (${input.guarantee.reason})` };
108
+ if (input.requestedSeconds > input.guarantee.ceilingSeconds) {
109
+ return {
110
+ _tag: "clamp",
111
+ toSeconds: input.guarantee.ceilingSeconds,
112
+ fromSeconds: input.requestedSeconds,
113
+ by: input.guarantee.by
114
+ };
115
+ }
116
+ return { _tag: "leave" };
117
+ }
118
+ export function clampSharedCacheSeconds(cacheControl, seconds) {
119
+ const lower = (name, limit, source) => source.replace(
120
+ new RegExp(`((?:^|[,\\s])${name}\\s*=\\s*)(\\d+)`, "gi"),
121
+ (whole, lead, value) => Number(value) > limit ? `${lead}${limit}` : whole
14
122
  );
15
- return {
16
- ...preserved,
17
- "cache-control": "private, no-store",
18
- "cloudflare-cdn-cache-control": "no-store"
19
- };
123
+ let out = lower("s-maxage", seconds, cacheControl);
124
+ out = lower("max-age", seconds, out);
125
+ const freshness = Math.min(
126
+ directive(unqualify(out.toLowerCase()), "s-maxage") ?? directive(unqualify(out.toLowerCase()), "max-age") ?? seconds,
127
+ seconds
128
+ );
129
+ const staleBudget = Math.max(0, seconds - freshness);
130
+ out = lower("stale-while-revalidate", staleBudget, out);
131
+ out = lower("stale-if-error", seconds, out);
132
+ return out;
133
+ }
134
+ export function staleDirectivesAreDisabled(cacheControl) {
135
+ const raw = Array.isArray(cacheControl) ? cacheControl.join(", ") : cacheControl;
136
+ if (typeof raw !== "string")
137
+ return false;
138
+ const value = unqualify(raw.toLowerCase());
139
+ const wantsStale = /stale-while-revalidate\s*=|stale-if-error\s*=/.test(value);
140
+ if (!wantsStale)
141
+ return false;
142
+ return /(?:^|,)\s*(?:s-maxage\s*=|must-revalidate|proxy-revalidate)/.test(value);
20
143
  }
@@ -77,6 +77,24 @@ type WorkersCachePolicy = {
77
77
  } | {
78
78
  _tag: 'enabled';
79
79
  crossVersion: boolean;
80
+ /**
81
+ * How `Cache-Control` on an HTML document is resolved.
82
+ *
83
+ * - `no-store` always overwrite it. The behaviour before the contract.
84
+ * - `auto` honour the app when a module guarantees chunk retention,
85
+ * clamped to what that module promises. Falls back to `no-store` when
86
+ * nothing publishes a guarantee, so an app without skew protection
87
+ * behaves exactly as it does today.
88
+ * - `app` always honour the app. You own the version-skew risk.
89
+ *
90
+ * This governs `Cache-Control` only. `Cloudflare-CDN-Cache-Control` is
91
+ * always honoured, because Workers Cache keys on the Worker version at
92
+ * `cross_version_cache: false`, so a deploy already makes every stored
93
+ * response unreachable and no document can outlive its chunks there.
94
+ *
95
+ * @default 'auto'
96
+ */
97
+ html?: 'no-store' | 'auto' | 'app';
80
98
  };
81
99
  interface WranglerObservabilityInput {
82
100
  enabled?: boolean;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@harlan-zw/nuxt-cloudflare",
3
3
  "type": "module",
4
- "version": "0.1.0",
4
+ "version": "0.2.0",
5
5
  "description": "Opinionated Cloudflare deployment defaults and diagnostics for Nuxt.",
6
6
  "author": {
7
7
  "name": "Harlan Wilton",
@@ -47,6 +47,10 @@
47
47
  "./wrangler": {
48
48
  "types": "./dist/wrangler.d.mts",
49
49
  "import": "./dist/wrangler.mjs"
50
+ },
51
+ "./cache": {
52
+ "types": "./dist/cache.d.mts",
53
+ "import": "./dist/cache.mjs"
50
54
  }
51
55
  },
52
56
  "main": "./dist/module.mjs",
@@ -56,6 +60,9 @@
56
60
  "bindings": [
57
61
  "dist/bindings.d.mts"
58
62
  ],
63
+ "cache": [
64
+ "dist/cache.d.mts"
65
+ ],
59
66
  "d1": [
60
67
  "dist/d1.d.mts"
61
68
  ],
@@ -113,10 +120,11 @@
113
120
  "dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare",
114
121
  "lint": "eslint .",
115
122
  "lint:fix": "eslint . --fix",
116
- "test": "pnpm run build && vitest run && pnpm run test:fixture",
123
+ "test": "pnpm run build && vitest run --exclude \"**/*.nitro.test.ts\" && pnpm run test:fixture && pnpm run test:contract",
117
124
  "test:fixture": "nuxi prepare tests/fixtures/basic && nuxt typecheck tests/fixtures/basic && nuxt build tests/fixtures/basic && node dist/cli/index.mjs doctor --cwd tests/fixtures/basic",
118
125
  "typecheck": "nuxt typecheck && tsc --noEmit -p tsconfig.check.json",
119
126
  "test:attw": "attw --pack",
120
- "test:pack": "rm -rf .pack && pnpm pack --pack-destination .pack && tar -tf .pack/*.tgz"
127
+ "test:pack": "rm -rf .pack && pnpm pack --pack-destination .pack && tar -tf .pack/*.tgz",
128
+ "test:contract": "nuxt build tests/fixtures/cache-contract && vitest run tests/cache-contract.nitro.test.ts"
121
129
  }
122
130
  }