esa-pcg-cli 0.1.23-beta.2 → 0.1.23-beta.4
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 +69 -11
- package/dist/_inline-overrides.js +4 -4
- package/dist/adapters/wrappers/node-server.js +2 -2
- package/dist/astro/packaging/artifact-layout.js +2 -17
- package/dist/astro-runtime/cache-provider.mjs +2 -2
- package/dist/bin/cli.js +5 -1
- package/dist/build/prepared-project.d.ts +17 -0
- package/dist/build/prepared-project.js +152 -0
- package/dist/commands/build-astro.d.ts +10 -0
- package/dist/commands/build-astro.js +14 -3
- package/dist/commands/build-next.d.ts +13 -0
- package/dist/commands/build-next.js +90 -73
- package/dist/commands/build-nuxt.d.ts +11 -0
- package/dist/commands/build-nuxt.js +12 -6
- package/dist/commands/build.d.ts +1 -0
- package/dist/commands/build.js +3 -2
- package/dist/commands/package.d.ts +9 -0
- package/dist/commands/package.js +170 -0
- package/dist/commands/prepare.d.ts +11 -0
- package/dist/commands/prepare.js +232 -0
- package/dist/config/default-open-next-config.js +6 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +8 -2
- package/dist/nitro-preset/cache-plugin.mjs +15 -0
- package/dist/nitro-preset/driver.mjs +13 -86
- package/dist/nitro-preset/gateway.mjs +56 -0
- package/dist/nitro-preset/image.mjs +122 -0
- package/dist/nitro-preset/index.mjs +85 -5
- package/dist/nitro-preset/isr.d.mts +6 -0
- package/dist/nitro-preset/isr.mjs +288 -0
- package/dist/nitro-preset/package.json +11 -3
- package/dist/runtime/cdn-purge.d.ts +1 -1
- package/dist/runtime/cdn-purge.js +3 -3
- package/dist/runtime/edge-context.d.ts +1 -1
- package/dist/runtime/edge-context.js +3 -3
- package/dist/runtime/efc-observability.cjs +11 -1
- package/dist/runtime/efc-observability.d.cts +1 -0
- package/package.json +1 -1
- package/dist/astro-runtime/request-header-logger.mjs +0 -68
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { useRuntimeConfig } from 'nitropack/runtime';
|
|
2
|
+
import { gwFetch, loadConfig } from './gateway.mjs';
|
|
3
|
+
|
|
4
|
+
const RESPONSE_HEADERS = [
|
|
5
|
+
'content-type', 'content-length', 'content-disposition', 'content-security-policy',
|
|
6
|
+
'cache-control', 'etag', 'last-modified', 'vary', 'x-image-cache',
|
|
7
|
+
];
|
|
8
|
+
const FORMATS = new Set(['avif', 'jpeg', 'jpg', 'png', 'webp', 'svg', 'gif', 'tiff', 'heic', 'bmp']);
|
|
9
|
+
|
|
10
|
+
function parseTransforms(operations, accept) {
|
|
11
|
+
const params = new URLSearchParams();
|
|
12
|
+
if (operations === '_') return params;
|
|
13
|
+
for (const operation of operations.split(/[&,]/)) {
|
|
14
|
+
const decoded = decodeURIComponent(operation);
|
|
15
|
+
const separator = decoded.indexOf('_');
|
|
16
|
+
const name = separator < 0 ? decoded : decoded.slice(0, separator);
|
|
17
|
+
const value = separator < 0 ? '' : decoded.slice(separator + 1);
|
|
18
|
+
if (name === 's' && /^\d+x\d+$/.test(value)) {
|
|
19
|
+
const [width, height] = value.split('x');
|
|
20
|
+
params.set('w', width);
|
|
21
|
+
params.set('h', height);
|
|
22
|
+
} else if (['w', 'h', 'q'].includes(name) && /^\d+$/.test(value)) {
|
|
23
|
+
params.set(name, value);
|
|
24
|
+
} else if (name === 'f' && FORMATS.has(value)) {
|
|
25
|
+
params.set('f', value);
|
|
26
|
+
} else if (name === 'f' && value === 'auto') {
|
|
27
|
+
const accepted = String(accept || '').split(',').map(type => type.trim().split(';'));
|
|
28
|
+
const supported = ['avif', 'webp'].find(format => accepted.some(([type, quality]) =>
|
|
29
|
+
type === `image/${format}` && !/^\s*q=0(?:\.0+)?\s*$/.test(quality || '')
|
|
30
|
+
));
|
|
31
|
+
if (supported) params.set('f', supported);
|
|
32
|
+
} else if (name !== 'fit' || value !== 'cover') {
|
|
33
|
+
throw new Error(`Unsupported IPX modifier: ${name}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return params;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function resolveSource(raw, options, base, prefix) {
|
|
40
|
+
let source = decodeURIComponent(raw);
|
|
41
|
+
if (!/^https?:\/\//i.test(source)) source = `/${source.replace(/^\//, '')}`;
|
|
42
|
+
const alias = Object.keys(options.alias || {}).sort((a, b) => b.length - a.length).find(key =>
|
|
43
|
+
source === key || source.startsWith(`${key.replace(/\/$/, '')}/`)
|
|
44
|
+
);
|
|
45
|
+
if (alias) source = `${options.alias[alias]}${source.slice(alias.length)}`;
|
|
46
|
+
if (/^https?:\/\//i.test(source)) {
|
|
47
|
+
const url = new URL(source);
|
|
48
|
+
const domains = options.http?.domains;
|
|
49
|
+
const allowed = Array.isArray(domains) ? domains : typeof domains === 'string' ? domains.split(',') : [];
|
|
50
|
+
if (url.username || url.password || !allowed.some(domain => domain.trim().toLowerCase() === url.hostname)) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
return { source: url.href, location: url.href };
|
|
54
|
+
}
|
|
55
|
+
if (options.fs === false || !source.startsWith('/') || source.startsWith('//') ||
|
|
56
|
+
/[\\\u0000-\u001f\u007f?#]/.test(source) || source.split('/').some(part => part === '..' || part === '.')) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const path = base && !source.startsWith(`${base}/`) ? `${base}${source}` : source;
|
|
60
|
+
if (path.startsWith(prefix)) return null;
|
|
61
|
+
return { source: path, location: path.split('/').map(encodeURIComponent).join('/') };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export default async function imageHandler(event) {
|
|
65
|
+
const { req, res } = event.node;
|
|
66
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
67
|
+
return new Response(null, { status: 405, headers: { Allow: 'GET, HEAD' } });
|
|
68
|
+
}
|
|
69
|
+
const config = useRuntimeConfig(event);
|
|
70
|
+
const options = config.ipx || {};
|
|
71
|
+
const base = (config.app.baseURL || '/').replace(/\/+$/, '');
|
|
72
|
+
const prefix = `${base}${(options.baseURL || '/_ipx').replace(/\/+$/, '')}/`;
|
|
73
|
+
const pathname = (req.originalUrl || req.url || '').split('?')[0];
|
|
74
|
+
const separator = pathname.indexOf('/', prefix.length);
|
|
75
|
+
if (!pathname.startsWith(prefix) || separator < 0 || separator === pathname.length - 1) {
|
|
76
|
+
return new Response('Invalid IPX image URL', { status: 400 });
|
|
77
|
+
}
|
|
78
|
+
let params;
|
|
79
|
+
let image;
|
|
80
|
+
try {
|
|
81
|
+
params = parseTransforms(pathname.slice(prefix.length, separator), req.headers.accept);
|
|
82
|
+
image = resolveSource(pathname.slice(separator + 1), options, base, prefix);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
return new Response(error.message, { status: 400 });
|
|
85
|
+
}
|
|
86
|
+
if (!image) return new Response('Image source is not allowed', { status: 403 });
|
|
87
|
+
if (!params.toString()) {
|
|
88
|
+
return new Response(null, { status: 302, headers: { Location: image.location, Vary: 'Accept' } });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const gateway = loadConfig();
|
|
92
|
+
if (!gateway) return new Response('Image Gateway is unavailable', { status: 503 });
|
|
93
|
+
params.set('href', image.source);
|
|
94
|
+
const assetsDir = (config.app.buildAssetsDir || '/_nuxt/').replace(/^\/+|\/+$/g, '');
|
|
95
|
+
const assetsBase = `${base}/${assetsDir}/`;
|
|
96
|
+
if (assetsDir && image.source.startsWith('/')) params.set('nuxtAssetsBase', assetsBase);
|
|
97
|
+
const headers = new Headers();
|
|
98
|
+
for (const name of ['accept', 'if-none-match', 'if-modified-since']) {
|
|
99
|
+
if (req.headers[name]) headers.set(name, req.headers[name]);
|
|
100
|
+
}
|
|
101
|
+
const client = new AbortController();
|
|
102
|
+
res.once('close', () => client.abort());
|
|
103
|
+
try {
|
|
104
|
+
const upstream = await gwFetch(gateway, `/image/optimize?${params}`, {
|
|
105
|
+
method: req.method,
|
|
106
|
+
headers,
|
|
107
|
+
signal: client.signal,
|
|
108
|
+
timeoutMs: 15000,
|
|
109
|
+
redirect: 'error',
|
|
110
|
+
});
|
|
111
|
+
const responseHeaders = new Headers();
|
|
112
|
+
for (const name of RESPONSE_HEADERS) {
|
|
113
|
+
if (name === 'content-length' && upstream.headers.has('content-encoding')) continue;
|
|
114
|
+
const value = upstream.headers.get(name);
|
|
115
|
+
if (value !== null) responseHeaders.set(name, value);
|
|
116
|
+
}
|
|
117
|
+
return new Response(upstream.body, { status: upstream.status, headers: responseHeaders });
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.warn(`[pcg nuxt image] Gateway request failed: ${error.message}`);
|
|
120
|
+
return new Response('Image Gateway request failed', { status: 502 });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -32,6 +32,46 @@ import * as fs from 'node:fs/promises';
|
|
|
32
32
|
import * as path from 'node:path';
|
|
33
33
|
|
|
34
34
|
const DRIVER_SPECIFIER = 'esa-nitro-preset/driver.mjs';
|
|
35
|
+
const CACHE_PLUGIN = 'esa-nitro-preset/cache-plugin.mjs';
|
|
36
|
+
const IMAGE_HANDLER = 'esa-nitro-preset/image.mjs';
|
|
37
|
+
|
|
38
|
+
function normalizeIsr(rules) {
|
|
39
|
+
let enabled = false;
|
|
40
|
+
for (const rule of Object.values(rules)) {
|
|
41
|
+
if (rule.cache === false) continue;
|
|
42
|
+
if (rule.isr === false && !rule.cache && rule.swr === undefined) {
|
|
43
|
+
rule.cache = false;
|
|
44
|
+
}
|
|
45
|
+
if (rule.isr !== true && !(Number.isFinite(rule.isr) && rule.isr > 0)) continue;
|
|
46
|
+
const policy = Object.entries(rule.headers || {}).find(([name]) => name.toLowerCase() === 'cache-control');
|
|
47
|
+
if (policy && /\b(?:private|no-store|no-cache)\b/i.test(policy[1])) {
|
|
48
|
+
rule.cache = false;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (rule.swr === undefined) {
|
|
52
|
+
rule.cache = { ...rule.cache, swr: true };
|
|
53
|
+
if (typeof rule.isr === 'number') rule.cache.maxAge = rule.isr;
|
|
54
|
+
}
|
|
55
|
+
enabled ||= Boolean(rule.cache);
|
|
56
|
+
}
|
|
57
|
+
return enabled;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function replaceIpxHandler(options) {
|
|
61
|
+
const ipx = options.runtimeConfig?.ipx;
|
|
62
|
+
if (!ipx || options.dev || options.static || options.preset === 'nitro-prerender') return;
|
|
63
|
+
const route = `${(ipx.baseURL || '/_ipx').replace(/\/+$/, '')}/**`;
|
|
64
|
+
const handler = options.handlers?.find(item => item.route === route &&
|
|
65
|
+
/[/\\]@nuxt[/\\]image[/\\].*[/\\](?:ipx|_ipx(?:\.legacy)?)\.(?:[cm]?[jt]s)$/.test(item.handler));
|
|
66
|
+
if (!handler) return;
|
|
67
|
+
// Replace only the runtime list entry. Nuxt Image also gives a copy of the
|
|
68
|
+
// original handler to the build-time prerenderer.
|
|
69
|
+
options.handlers = options.handlers.map(item =>
|
|
70
|
+
item === handler ? { ...item, handler: IMAGE_HANDLER } : item
|
|
71
|
+
);
|
|
72
|
+
options.routeRules ||= {};
|
|
73
|
+
options.routeRules[route] = { ...options.routeRules[route], cache: false };
|
|
74
|
+
}
|
|
35
75
|
|
|
36
76
|
const esaPreset = {
|
|
37
77
|
_meta: { name: 'esa-nitro-preset' },
|
|
@@ -39,14 +79,54 @@ const esaPreset = {
|
|
|
39
79
|
hooks: {
|
|
40
80
|
'build:before'(nitro) {
|
|
41
81
|
const plugin = 'esa-nitro-preset/function-logs.mjs';
|
|
42
|
-
nitro.options
|
|
43
|
-
|
|
82
|
+
const options = nitro.options;
|
|
83
|
+
options.plugins ||= [];
|
|
84
|
+
if (!options.plugins.includes(plugin)) options.plugins.push(plugin);
|
|
85
|
+
options.externals ||= {};
|
|
86
|
+
options.externals.inline ||= [];
|
|
87
|
+
if (!options.externals.inline.includes('esa-nitro-preset/')) {
|
|
88
|
+
options.externals.inline.push('esa-nitro-preset/');
|
|
89
|
+
}
|
|
44
90
|
// 注入 ESA cache driver 到 nitro.options.storage.cache。
|
|
45
91
|
// 仅当用户未自定义 cache driver 时注入,尊重用户显式配置。
|
|
46
|
-
|
|
47
|
-
if (!
|
|
48
|
-
|
|
92
|
+
options.storage ||= {};
|
|
93
|
+
if (!options.storage.cache?.driver) {
|
|
94
|
+
options.storage.cache = { driver: DRIVER_SPECIFIER };
|
|
49
95
|
}
|
|
96
|
+
const hasIsr = normalizeIsr(options.routeRules || {});
|
|
97
|
+
if (hasIsr && options.storage.cache.driver === DRIVER_SPECIFIER && !options.plugins.includes(CACHE_PLUGIN)) {
|
|
98
|
+
options.plugins.push(CACHE_PLUGIN);
|
|
99
|
+
}
|
|
100
|
+
replaceIpxHandler(options);
|
|
101
|
+
if (options.runtimeConfig?.nitro) options.runtimeConfig.nitro.routeRules = options.routeRules;
|
|
102
|
+
},
|
|
103
|
+
'rollup:before'(nitro, rollup) {
|
|
104
|
+
if (!nitro.options.plugins?.includes(CACHE_PLUGIN)) return;
|
|
105
|
+
let patched = false;
|
|
106
|
+
rollup.plugins.push({
|
|
107
|
+
name: 'pcg-nitro-cache-pending-key',
|
|
108
|
+
transform(code, id) {
|
|
109
|
+
if (!/[/\\]nitropack[/\\]dist[/\\]runtime[/\\](?:internal[/\\])?cache\.m?js$/.test(id) ||
|
|
110
|
+
!code.includes('function defineCachedFunction')) return null;
|
|
111
|
+
const lookup = 'const isPending = pending[key];';
|
|
112
|
+
if (code.split(lookup).length !== 2 || !code.includes('const cacheKey =') ||
|
|
113
|
+
!code.includes('await pending[key]')) {
|
|
114
|
+
this.error('Unsupported Nitro cache runtime for PCG ISR invalidation');
|
|
115
|
+
}
|
|
116
|
+
patched = true;
|
|
117
|
+
// Keep the OSS storage key stable. Only partition Nitro's in-flight promises.
|
|
118
|
+
const transformed = code.replace(lookup,
|
|
119
|
+
`const pcgPendingKey = await getPcgPendingKey(cacheKey, key);\n ${lookup}`
|
|
120
|
+
).replaceAll('pending[key]', 'pending[pcgPendingKey]');
|
|
121
|
+
return {
|
|
122
|
+
code: `import { getPendingCacheKey as getPcgPendingKey } from 'esa-nitro-preset/isr';\n${transformed}`,
|
|
123
|
+
map: null,
|
|
124
|
+
};
|
|
125
|
+
},
|
|
126
|
+
buildEnd(error) {
|
|
127
|
+
if (!error && !patched) this.error('PCG could not isolate in-flight ISR computation in Nitro');
|
|
128
|
+
},
|
|
129
|
+
});
|
|
50
130
|
},
|
|
51
131
|
// 构建后验身份,不进入 PCG 交付根目录,也不生成平台配置。
|
|
52
132
|
async compiled(nitro) {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export function trackNuxtCacheKey(key: string): Promise<void>;
|
|
2
|
+
|
|
3
|
+
export function invalidateNuxtCache(
|
|
4
|
+
target: { path: string; key?: never } | { key: string; path?: never },
|
|
5
|
+
site?: { hostname?: string; siteId?: string | number }
|
|
6
|
+
): Promise<{ originInvalidated: true; cdn: 'submitted' | 'skipped' | 'failed' }>;
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { gwFetch, loadConfig } from './gateway.mjs';
|
|
4
|
+
|
|
5
|
+
const requests = new AsyncLocalStorage();
|
|
6
|
+
const INITIAL_VERSION = '0';
|
|
7
|
+
const MAX_REFERENCES = 64;
|
|
8
|
+
|
|
9
|
+
function normalizeKey(key) {
|
|
10
|
+
return key.split('?')[0].replace(/[/\\]/g, ':').replace(/:+/g, ':').replace(/^:|:$/g, '');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function keyReference(key) {
|
|
14
|
+
if (typeof key !== 'string' || !key || key.length > 4096 || /[\0\r\n]/.test(key)) {
|
|
15
|
+
throw new TypeError('Expected the Nitro storage key relative to the cache mount');
|
|
16
|
+
}
|
|
17
|
+
const normalized = normalizeKey(key);
|
|
18
|
+
if (!normalized) throw new TypeError('Expected a nonempty Nitro storage key');
|
|
19
|
+
return `key:${normalized}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function pagePath(path) {
|
|
23
|
+
return new URL(path, 'http://pcg.local').pathname
|
|
24
|
+
.replace(/%[a-f\d]{2}/gi, segment => segment.toUpperCase())
|
|
25
|
+
.replace(/\/+$/, '')
|
|
26
|
+
.replace(/\/_payload\.(?:json|js)$/, '') || '/';
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function pathReference(path) {
|
|
30
|
+
return `path:${pagePath(path)}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function digest(value) {
|
|
34
|
+
return createHash('sha256').update(value).digest('base64url');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function tableKey(cfg, reference) {
|
|
38
|
+
return `${cfg.version}/nuxt/${digest(reference)}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function primaryKey(cfg, reference) {
|
|
42
|
+
return [
|
|
43
|
+
{ name: 'app_id', value: `${cfg.aliuid}/${cfg.routinename}` },
|
|
44
|
+
{ name: 'tag', value: tableKey(cfg, reference) },
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function edgeTag(cfg, reference) {
|
|
49
|
+
return `pcg-${digest(`${cfg.aliuid}/${cfg.routinename}:${tableKey(cfg, reference)}`)}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function gatewayPost(cfg, path, body) {
|
|
53
|
+
const response = await gwFetch(cfg, path, { method: 'POST', body: JSON.stringify(body) });
|
|
54
|
+
if (!response.ok) throw new Error(`Nuxt cache ${path} failed (${response.status})`);
|
|
55
|
+
return response.json();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function readVersions(cfg, references) {
|
|
59
|
+
if (!cfg) throw new Error('Nuxt cache Gateway configuration is missing');
|
|
60
|
+
const unique = [...new Set(references)];
|
|
61
|
+
if (unique.length > MAX_REFERENCES) throw new Error('Too many Nuxt cache dependencies');
|
|
62
|
+
const keys = new Map(unique.map(reference => [tableKey(cfg, reference), reference]));
|
|
63
|
+
const versions = new Map(unique.map(reference => [reference, INITIAL_VERSION]));
|
|
64
|
+
const result = await gatewayPost(cfg, '/table/batch-get-row', {
|
|
65
|
+
primaryKeys: unique.map(reference => primaryKey(cfg, reference)),
|
|
66
|
+
requireComplete: true,
|
|
67
|
+
});
|
|
68
|
+
if (result.complete !== true || !Array.isArray(result.rows)) {
|
|
69
|
+
throw new Error('Nuxt cache invalidation state is incomplete');
|
|
70
|
+
}
|
|
71
|
+
for (const row of result.rows) {
|
|
72
|
+
const tag = row.primaryKey?.find(column => column.name === 'tag')?.value;
|
|
73
|
+
const version = row.columns?.find(column => column.name === 'generation')?.value;
|
|
74
|
+
if (!keys.has(tag) || typeof version !== 'string' || !version) {
|
|
75
|
+
throw new Error('Invalid Nuxt cache invalidation row');
|
|
76
|
+
}
|
|
77
|
+
versions.set(keys.get(tag), version);
|
|
78
|
+
}
|
|
79
|
+
return versions;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function runCacheRequest(event, group, next) {
|
|
83
|
+
const state = {
|
|
84
|
+
event,
|
|
85
|
+
parent: requests.getStore(),
|
|
86
|
+
group: group ? `${normalizeKey(group)}:` : null,
|
|
87
|
+
path: event.path.split('?')[0],
|
|
88
|
+
dependencies: new Map(),
|
|
89
|
+
route: null,
|
|
90
|
+
response: null,
|
|
91
|
+
};
|
|
92
|
+
return requests.run(state, next);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Call before reading the corresponding cached function or storage item.
|
|
96
|
+
export async function trackNuxtCacheKey(key) {
|
|
97
|
+
const reference = keyReference(key);
|
|
98
|
+
const state = requests.getStore();
|
|
99
|
+
if (!state) return;
|
|
100
|
+
if (state.dependencies.has(reference)) {
|
|
101
|
+
await state.dependencies.get(reference);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const read = readVersions(loadConfig(), [reference])
|
|
105
|
+
.then(versions => versions.get(reference))
|
|
106
|
+
.catch(error => {
|
|
107
|
+
console.warn(`[pcg nuxt cache] ${error.message}`);
|
|
108
|
+
return null;
|
|
109
|
+
});
|
|
110
|
+
for (let current = state; current; current = current.parent) {
|
|
111
|
+
if (!current.dependencies.has(reference)) current.dependencies.set(reference, read);
|
|
112
|
+
}
|
|
113
|
+
await read;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function trackedVersion(state, reference) {
|
|
117
|
+
for (let current = state; current; current = current.parent) {
|
|
118
|
+
const tracked = current.dependencies.get(reference);
|
|
119
|
+
if (tracked) return tracked;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function getPendingCacheKey(cacheKey, key) {
|
|
124
|
+
const state = requests.getStore();
|
|
125
|
+
const normalized = normalizeKey(cacheKey);
|
|
126
|
+
if (!state || !normalized.startsWith('cache:')) return `nitro:${key}`;
|
|
127
|
+
const storageKey = normalized.slice('cache:'.length);
|
|
128
|
+
// A render's data dependencies may only become known while it is running.
|
|
129
|
+
if (state.route?.key === storageKey) return Symbol();
|
|
130
|
+
const tracked = trackedVersion(state, `key:${storageKey}`);
|
|
131
|
+
if (!tracked) return `nitro:${key}`;
|
|
132
|
+
const generation = await tracked;
|
|
133
|
+
return generation == null ? Symbol() : `pcg:${generation}:${key}`;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function cacheScope(key) {
|
|
137
|
+
const state = requests.getStore();
|
|
138
|
+
if (!state) return null;
|
|
139
|
+
const reference = `key:${key}`;
|
|
140
|
+
if (state.group && key.startsWith(state.group)) {
|
|
141
|
+
const route = { state, key, reference, path: pathReference(state.path), versions: null };
|
|
142
|
+
state.route = route;
|
|
143
|
+
return route;
|
|
144
|
+
}
|
|
145
|
+
const tracked = trackedVersion(state, reference);
|
|
146
|
+
return tracked ? { state, reference, tracked } : null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function storedVersions(envelope) {
|
|
150
|
+
const entries = Object.entries(envelope?.pcg?.versions || {});
|
|
151
|
+
if (entries.length > MAX_REFERENCES || entries.some(([ref, value]) =>
|
|
152
|
+
!/^(?:key|path):.+$/.test(ref) || typeof value !== 'string' || !value
|
|
153
|
+
)) return [];
|
|
154
|
+
return entries;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function cacheMiss(scope) {
|
|
158
|
+
if (scope?.path) {
|
|
159
|
+
// Nitro can end a 304 before beforeResponse. An invalidated response must
|
|
160
|
+
// not renew a downstream cache via its old validators.
|
|
161
|
+
const headers = scope.state.event.node.req.headers;
|
|
162
|
+
delete headers['if-none-match'];
|
|
163
|
+
delete headers['if-modified-since'];
|
|
164
|
+
}
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function cacheRead(cfg, scope, envelope) {
|
|
169
|
+
if (!scope && !envelope?.pcg) return envelope?.value ?? null;
|
|
170
|
+
const own = scope?.path ? [scope.path, scope.reference] : scope ? [scope.reference] : [];
|
|
171
|
+
const stored = storedVersions(envelope);
|
|
172
|
+
try {
|
|
173
|
+
const current = scope?.tracked
|
|
174
|
+
? new Map([[scope.reference, await scope.tracked]])
|
|
175
|
+
: await readVersions(cfg, [...own, ...stored.map(([reference]) => reference)]);
|
|
176
|
+
if (scope?.path) scope.versions = new Map(own.map(reference => [reference, current.get(reference)]));
|
|
177
|
+
if (!stored.length || own.some(reference => !stored.some(([name]) => name === reference)) ||
|
|
178
|
+
stored.some(([reference, version]) => current.get(reference) !== version)) return cacheMiss(scope);
|
|
179
|
+
if (scope?.path) {
|
|
180
|
+
scope.state.response = { cfg, envelope, hit: true };
|
|
181
|
+
setCacheHeaders(scope.state.event.node.res, cfg, envelope);
|
|
182
|
+
}
|
|
183
|
+
return envelope.value ?? null;
|
|
184
|
+
} catch (error) {
|
|
185
|
+
console.warn(`[pcg nuxt cache] ${error.message}`);
|
|
186
|
+
return cacheMiss(scope);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export async function cacheWrite(cfg, key, envelope) {
|
|
191
|
+
const state = requests.getStore();
|
|
192
|
+
if (!state) return true;
|
|
193
|
+
const route = state.route?.key === key ? state.route : null;
|
|
194
|
+
const reference = `key:${key}`;
|
|
195
|
+
if (route) {
|
|
196
|
+
const headers = envelope.value?.value?.headers;
|
|
197
|
+
if (headers && Object.entries(headers).some(([name, value]) =>
|
|
198
|
+
name.toLowerCase() === 'set-cookie' ||
|
|
199
|
+
name.toLowerCase() === 'cache-control' && /\b(?:private|no-cache|no-store)\b/i.test(value)
|
|
200
|
+
)) return false;
|
|
201
|
+
if (!route.versions || state.dependencies.size > MAX_REFERENCES - route.versions.size) return false;
|
|
202
|
+
const ready = Promise.all([...state.dependencies].map(async ([dependency, read]) => [dependency, await read]))
|
|
203
|
+
.then(async dependencies => {
|
|
204
|
+
if (dependencies.some(([, version]) => version == null)) return false;
|
|
205
|
+
envelope.pcg = {
|
|
206
|
+
path: pagePath(state.path),
|
|
207
|
+
versions: Object.fromEntries([...route.versions, ...dependencies]),
|
|
208
|
+
};
|
|
209
|
+
return canWriteCache(cfg, envelope);
|
|
210
|
+
});
|
|
211
|
+
if (!state.response) state.response = { cfg, envelope, hit: false, ready };
|
|
212
|
+
return ready;
|
|
213
|
+
}
|
|
214
|
+
const tracked = trackedVersion(state, reference);
|
|
215
|
+
if (!tracked) return true;
|
|
216
|
+
const version = await tracked;
|
|
217
|
+
if (version == null) return false;
|
|
218
|
+
envelope.pcg = { versions: { [reference]: version } };
|
|
219
|
+
return canWriteCache(cfg, envelope);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function setCacheHeaders(res, cfg, envelope) {
|
|
223
|
+
const tags = Object.keys(envelope.pcg.versions).map(reference => edgeTag(cfg, reference));
|
|
224
|
+
const existing = res.getHeader('Cache-Tag');
|
|
225
|
+
if (existing) tags.push(...String(existing).split(','));
|
|
226
|
+
res.setHeader('Cache-Tag', [...new Set(tags)].join(','));
|
|
227
|
+
const storedAt = Number.isFinite(envelope.value?.mtime) ? envelope.value.mtime : envelope.lastModified;
|
|
228
|
+
res.setHeader('Age', String(Math.max(0, Math.floor((Date.now() - storedAt) / 1000))));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export async function applyCacheHeaders(event) {
|
|
232
|
+
const state = requests.getStore();
|
|
233
|
+
const res = event.node.res;
|
|
234
|
+
if (state?.event !== event || !state.route || res.headersSent) return;
|
|
235
|
+
const policy = String(res.getHeader('Cache-Control') || '');
|
|
236
|
+
if (res.statusCode >= 400 || res.hasHeader('Set-Cookie') || /\b(?:private|no-store|no-cache)\b/i.test(policy)) return;
|
|
237
|
+
const response = state.response;
|
|
238
|
+
if (response) {
|
|
239
|
+
const { cfg, envelope, hit, ready } = response;
|
|
240
|
+
if (hit || await ready) {
|
|
241
|
+
setCacheHeaders(res, cfg, envelope);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
res.removeHeader('Cache-Tag');
|
|
246
|
+
res.removeHeader('CDN-Cache-Control');
|
|
247
|
+
res.removeHeader('Age');
|
|
248
|
+
res.setHeader('Cache-Control', 'private, no-store');
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function canWriteCache(cfg, envelope) {
|
|
252
|
+
const stored = Object.entries(envelope.pcg.versions);
|
|
253
|
+
try {
|
|
254
|
+
const current = await readVersions(cfg, stored.map(([reference]) => reference));
|
|
255
|
+
return stored.every(([reference, version]) => current.get(reference) === version);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
console.warn(`[pcg nuxt cache] ${error.message}`);
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export async function invalidateNuxtCache({ path, key }, target = {}) {
|
|
263
|
+
if ((path === undefined) === (key === undefined)) throw new TypeError('Provide exactly one cache path or key');
|
|
264
|
+
if (path !== undefined && (typeof path !== 'string' || !/^\/(?!\/)[^?#\\\0\r\n]*$/.test(path))) {
|
|
265
|
+
throw new TypeError('Expected an absolute site pathname including the app baseURL');
|
|
266
|
+
}
|
|
267
|
+
const reference = path === undefined ? keyReference(key) : pathReference(path);
|
|
268
|
+
const cfg = loadConfig();
|
|
269
|
+
if (!cfg) throw new Error('Nuxt cache Gateway configuration is missing');
|
|
270
|
+
const result = await gatewayPost(cfg, '/table/batch-write', {
|
|
271
|
+
rows: [{
|
|
272
|
+
primaryKey: primaryKey(cfg, reference),
|
|
273
|
+
columns: [{ name: 'generation', value: randomUUID() }],
|
|
274
|
+
}],
|
|
275
|
+
});
|
|
276
|
+
if (result.written !== 1) throw new Error('Nuxt cache invalidation was not written');
|
|
277
|
+
const headers = requests.getStore()?.event.node.req.headers;
|
|
278
|
+
const hostname = target.hostname ?? headers?.host;
|
|
279
|
+
const siteId = target.siteId ?? headers?.['ali-esa-origin-site-id'];
|
|
280
|
+
if (!hostname || !siteId) return { originInvalidated: true, cdn: 'skipped' };
|
|
281
|
+
try {
|
|
282
|
+
await gatewayPost(cfg, '/cache/refresh', { hostname, siteId, cacheTags: [edgeTag(cfg, reference)] });
|
|
283
|
+
return { originInvalidated: true, cdn: 'submitted' };
|
|
284
|
+
} catch (error) {
|
|
285
|
+
console.warn(`[pcg nuxt cache] ${error.message}`);
|
|
286
|
+
return { originInvalidated: true, cdn: 'failed' };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
@@ -7,15 +7,23 @@
|
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./index.mjs",
|
|
9
9
|
"./driver.mjs": "./driver.mjs",
|
|
10
|
-
"./function-logs.mjs": "./function-logs.mjs"
|
|
10
|
+
"./function-logs.mjs": "./function-logs.mjs",
|
|
11
|
+
"./cache-plugin.mjs": "./cache-plugin.mjs",
|
|
12
|
+
"./image.mjs": "./image.mjs",
|
|
13
|
+
"./isr": "./isr.mjs"
|
|
11
14
|
},
|
|
12
15
|
"files": [
|
|
13
16
|
"index.mjs",
|
|
14
17
|
"driver.mjs",
|
|
15
|
-
"function-logs.mjs"
|
|
18
|
+
"function-logs.mjs",
|
|
19
|
+
"gateway.mjs",
|
|
20
|
+
"cache-plugin.mjs",
|
|
21
|
+
"image.mjs",
|
|
22
|
+
"isr.mjs",
|
|
23
|
+
"isr.d.mts"
|
|
16
24
|
],
|
|
17
25
|
"scripts": {
|
|
18
|
-
"test": "node smoke.mjs"
|
|
26
|
+
"test": "node smoke.mjs && node --test isr.test.mjs"
|
|
19
27
|
},
|
|
20
28
|
"keywords": [
|
|
21
29
|
"nitro",
|
|
@@ -51,7 +51,7 @@ export interface CdnPurgeClient {
|
|
|
51
51
|
* 加载 purge 配置。
|
|
52
52
|
*
|
|
53
53
|
* hostname / siteId 不再从 env 取,改由 node-server wrapper 在入口
|
|
54
|
-
* runWithEdgeContext(headers, …) 把请求头里的 host 与
|
|
54
|
+
* runWithEdgeContext(headers, …) 把请求头里的 host 与 ali-esa-origin-site-id 注入
|
|
55
55
|
* AsyncLocalStorage,refreshBatch 时即时读取。原因:
|
|
56
56
|
* - 一个 routine 可能服务多 site / 多 hostname,启动期 env 无法表达
|
|
57
57
|
* - 本地 dev 若没带头,这次 purge 直接 skip + warn,不再静默生效
|