esa-pcg-cli 0.1.22 → 0.1.23-beta.1
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 +29 -0
- package/dist/_inline-overrides.js +4 -4
- package/dist/artifacts/efc-observability.js +6 -2
- package/dist/artifacts/nuxt.d.ts +1 -0
- package/dist/artifacts/nuxt.js +11 -2
- package/dist/astro-runtime/gateway-client.mjs +17 -2
- package/dist/commands/build-nuxt.d.ts +1 -0
- package/dist/commands/build-nuxt.js +172 -19
- package/dist/commands/build.js +13 -2
- package/dist/commands/deploy.js +8 -5
- package/dist/nitro-preset/driver.mjs +22 -13
- package/dist/nitro-preset/index.mjs +16 -2
- package/dist/nuxt/compatibility.d.ts +6 -0
- package/dist/nuxt/compatibility.js +98 -0
- package/dist/nuxt/config.d.ts +14 -0
- package/dist/nuxt/config.js +128 -0
- package/dist/nuxt/metadata.d.ts +3 -0
- package/dist/nuxt/metadata.js +67 -0
- package/dist/runtime/debug-network-log.cjs +123 -0
- package/dist/runtime/debug-network-log.d.cts +11 -0
- package/dist/runtime/efc-observability.cjs +31 -11
- package/dist/runtime/efc-observability.d.cts +2 -0
- package/dist/runtime/gateway-auth.js +2 -1
- package/package.json +5 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
exports.INLINE_OVERRIDES = {
|
|
3
|
-
"runtime/efc-observability.cjs": "\"use strict\";\n\n// dist/runtime/efc-observability.cjs\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar { AsyncLocalStorage } = require(\"node:async_hooks\");\nvar diagnostics = require(\"node:diagnostics_channel\");\nvar http = require(\"node:http\");\nvar { randomUUID } = require(\"node:crypto\");\nvar { performance } = require(\"node:perf_hooks\");\nvar { Console } = require(\"node:console\");\nvar KEY = Symbol.for(\"pcg.efc.observability\");\nvar state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n});\nvar LOG_LIMIT = 32 * 1024;\nvar BODY_LIMIT = 64 * 1024;\nvar DEADLINE_MS = 5e3;\nvar diagnosticConsole;\nfunction warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n}\nfunction safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n}\nfunction validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n}\nfunction validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n}\nfunction traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n}\nfunction safePath(value) {\n const path = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n}\nfunction notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n for (const done of state.waiters)\n done(true);\n}\nfunction drop(reason) {\n state.counts.dropped++;\n warning(reason);\n}\nfunction rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n}\nfunction snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n}\nfunction finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n}\nfunction closeRoot(ctx) {\n if (ctx.closed || !ctx.report)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n}\nfunction complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n}\nfunction responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n}\nfunction installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call)\n complete(call);\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]);\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!enabled && !trace)\n return;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n ctx = {\n trace,\n metadata,\n report,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!report) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path = safePath(req.url);\n if (validText(path, 2048))\n metadata.path = path;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http.Server.prototype.emit === observedEmit)\n http.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n}\nasync function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n if (ctx && ctx.trace)\n init.headers.set(\"eagleeye-traceid\", ctx.trace);\n if (!ctx || !ctx.report || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n return response;\n } catch (error) {\n safe(() => complete(call));\n throw error;\n }\n}\nfunction markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n}\nfunction send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n}\nfunction pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n}\nfunction flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n}\nfunction getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n}\nfunction getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n}\nstate.observeGatewayFetch = observeGatewayFetch;\nstate.flushFunctionLogs = flushFunctionLogs;\nstate.getEfcTraceId = getEfcTraceId;\nmodule.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId\n};\n",
|
|
4
|
-
"adapters/wrappers/node-server.js": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod2) => function __require() {\n return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;\n};\n\n// dist/adapters/converters/node-request.js\nvar require_node_request = __commonJS({\n \"dist/adapters/converters/node-request.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.convertNodeRequest = void 0;\n function firstHeaderValue(value) {\n var _a;\n const raw = Array.isArray(value) ? value.join(\",\") : value;\n const first = (_a = raw === null || raw === void 0 ? void 0 : raw.split(\",\")[0]) === null || _a === void 0 ? void 0 : _a.trim();\n return first || void 0;\n }\n async function convertNodeRequest(req, converter) {\n var _a, _b, _c;\n const protocol = (_a = firstHeaderValue(req.headers[\"x-forwarded-proto\"])) !== null && _a !== void 0 ? _a : \"http\";\n req.protocol = protocol;\n let rejectRequest;\n const requestFailed = new Promise((_, reject) => {\n rejectRequest = reject;\n });\n const onError = (error) => rejectRequest(error);\n const onAborted = () => rejectRequest(new Error(\"Request aborted\"));\n req.once(\"error\", onError);\n req.once(\"aborted\", onAborted);\n let converted;\n try {\n converted = await Promise.race([\n converter.convertFrom(req),\n requestFailed\n ]);\n } finally {\n req.removeListener(\"error\", onError);\n req.removeListener(\"aborted\", onAborted);\n }\n const rawUrl = req.url || \"/\";\n const host = converted.headers.host || `localhost:${(_b = process.env.PORT) !== null && _b !== void 0 ? _b : \"3000\"}`;\n const absoluteUrl = new URL(`${protocol}://${host}${rawUrl}`);\n const remoteAddress = firstHeaderValue(converted.headers[\"x-forwarded-for\"]) || converted.headers[\"x-real-ip\"] || ((_c = req.socket) === null || _c === void 0 ? void 0 : _c.remoteAddress) || \"127.0.0.1\";\n return {\n ...converted,\n rawPath: absoluteUrl.pathname,\n url: absoluteUrl.href,\n remoteAddress\n };\n }\n exports2.convertNodeRequest = convertNodeRequest;\n }\n});\n\n// dist/runtime/efc-observability.cjs\nvar require_efc_observability = __commonJS({\n \"dist/runtime/efc-observability.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var { AsyncLocalStorage } = require(\"node:async_hooks\");\n var diagnostics = require(\"node:diagnostics_channel\");\n var http2 = require(\"node:http\");\n var { randomUUID } = require(\"node:crypto\");\n var { performance } = require(\"node:perf_hooks\");\n var { Console } = require(\"node:console\");\n var KEY = Symbol.for(\"pcg.efc.observability\");\n var state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n });\n var LOG_LIMIT = 32 * 1024;\n var BODY_LIMIT = 64 * 1024;\n var DEADLINE_MS = 5e3;\n var diagnosticConsole;\n function warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n }\n function safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n }\n function validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n }\n function validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n }\n function traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n }\n function safePath(value) {\n const path3 = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path3.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n }\n function notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n for (const done of state.waiters)\n done(true);\n }\n function drop(reason) {\n state.counts.dropped++;\n warning(reason);\n }\n function rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n }\n function snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n }\n function finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n }\n function closeRoot(ctx) {\n if (ctx.closed || !ctx.report)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n }\n function complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n }\n function responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n }\n function installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http2.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call)\n complete(call);\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]);\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!enabled && !trace)\n return;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n ctx = {\n trace,\n metadata,\n report,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!report) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path3 = safePath(req.url);\n if (validText(path3, 2048))\n metadata.path = path3;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http2.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http2.Server.prototype.emit === observedEmit)\n http2.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n }\n async function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n if (ctx && ctx.trace)\n init.headers.set(\"eagleeye-traceid\", ctx.trace);\n if (!ctx || !ctx.report || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n return response;\n } catch (error) {\n safe(() => complete(call));\n throw error;\n }\n }\n function markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n }\n function send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http2.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n }\n function pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n }\n function flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n }\n function getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n }\n function getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n }\n state.observeGatewayFetch = observeGatewayFetch;\n state.flushFunctionLogs = flushFunctionLogs;\n state.getEfcTraceId = getEfcTraceId;\n module2.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId\n };\n }\n});\n\n// dist/runtime/gateway-auth.js\nvar require_gateway_auth = __commonJS({\n \"dist/runtime/gateway-auth.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.gatewayFetch = exports2.signGatewayHeaders = exports2.loadGatewayAuthConfig = void 0;\n var crypto_1 = require(\"crypto\");\n var efc_observability_cjs_12 = require_efc_observability();\n var DEFAULT_TTL_MS = 5 * 60 * 1e3;\n var DEFAULT_TIMEOUT_MS = 5e3;\n function _fetch(input, init) {\n var _a, _b;\n const gatewayGlobalFetch = globalThis.fetch;\n const fn = gatewayGlobalFetch.__nextPatched ? (_b = (_a = gatewayGlobalFetch._nextOriginalFetch) !== null && _a !== void 0 ? _a : globalThis.__originalFetch) !== null && _b !== void 0 ? _b : gatewayGlobalFetch : gatewayGlobalFetch;\n return fn(input, init);\n }\n function loadGatewayAuthConfig() {\n const gatewayUrl = process.env.ESA_CACHE_GW_GATEWAY_ENDPOINT;\n const authKey = process.env.ESA_CACHE_GW_AUTH_KEY;\n const aliuid = process.env.ESA_CACHE_GW_ALIUID;\n const routinename = process.env.ESA_CACHE_GW_FUNCTIONNAME;\n const version = process.env.ESA_CACHE_GW_VERSION;\n const missing = [];\n if (!gatewayUrl)\n missing.push(\"ESA_CACHE_GW_GATEWAY_ENDPOINT\");\n if (!authKey)\n missing.push(\"ESA_CACHE_GW_AUTH_KEY\");\n if (!aliuid)\n missing.push(\"ESA_CACHE_GW_ALIUID\");\n if (!routinename)\n missing.push(\"ESA_CACHE_GW_FUNCTIONNAME\");\n if (!version)\n missing.push(\"ESA_CACHE_GW_VERSION\");\n if (missing.length > 0) {\n console.error(`[gateway-auth] \\u7F3A\\u5C11\\u5FC5\\u9700\\u7684\\u73AF\\u5883\\u53D8\\u91CF: ${missing.join(\", \")}`);\n return null;\n }\n return {\n gatewayUrl: gatewayUrl.replace(/\\/+$/, \"\"),\n secret: authKey,\n aliuid,\n routinename,\n version\n };\n }\n exports2.loadGatewayAuthConfig = loadGatewayAuthConfig;\n function signGatewayHeaders(cfg, ttlMs = DEFAULT_TTL_MS) {\n const expires = String(Date.now() + ttlMs);\n const md5Hash = (0, crypto_1.createHash)(\"md5\").update(`${cfg.secret}${expires}${cfg.aliuid}${cfg.routinename}${cfg.version}`).digest(\"hex\");\n return {\n authorization: `${expires}-${md5Hash}`,\n aliuid: cfg.aliuid,\n routinename: cfg.routinename,\n version: cfg.version\n };\n }\n exports2.signGatewayHeaders = signGatewayHeaders;\n async function gatewayFetch(cfg, pathOrUrl, init) {\n var _a, _b;\n const url = pathOrUrl.startsWith(\"/\") ? `${cfg.gatewayUrl}${pathOrUrl}` : pathOrUrl;\n const signed = signGatewayHeaders(cfg);\n const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);\n headers.set(\"Authorization\", signed.authorization);\n headers.set(\"AliUid\", signed.aliuid);\n headers.set(\"RoutineName\", signed.routinename);\n headers.set(\"Version\", signed.version);\n const timeoutMs = (_a = init === null || init === void 0 ? void 0 : init.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await (0, efc_observability_cjs_12.observeGatewayFetch)(url, {\n ...init,\n headers,\n signal: (_b = init === null || init === void 0 ? void 0 : init.signal) !== null && _b !== void 0 ? _b : controller.signal\n }, _fetch);\n } finally {\n clearTimeout(timer);\n }\n }\n exports2.gatewayFetch = gatewayFetch;\n }\n});\n\n// dist/runtime/image-config.js\nvar require_image_config = __commonJS({\n \"dist/runtime/image-config.js\"(exports, module) {\n \"use strict\";\n var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });\n var __importStar = exports && exports.__importStar || function(mod2) {\n if (mod2 && mod2.__esModule) return mod2;\n var result = {};\n if (mod2 != null) {\n for (var k in mod2) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);\n }\n __setModuleDefault(result, mod2);\n return result;\n };\n Object.defineProperty(exports, \"__esModule\", { value: true });\n exports._setMatcherForTests = exports._resetImageConfigCacheForTests = exports.validateImageUrl = void 0;\n var fs = __importStar(require(\"fs\"));\n var path = __importStar(require(\"path\"));\n var cachedConfig;\n var cachedMatcher;\n var warnedMatcherMissing = false;\n function configFilePath() {\n return path.resolve(process.cwd(), \".next\", \"required-server-files.json\");\n }\n function loadImageConfig() {\n var _a, _b, _c;\n if (cachedConfig !== void 0)\n return cachedConfig;\n const filePath = configFilePath();\n let raw;\n try {\n raw = fs.readFileSync(filePath, \"utf-8\");\n } catch (err) {\n console.warn(`[image-config] required-server-files.json not found at ${filePath} \\u2014 allowing all image URLs (${(_a = err.code) !== null && _a !== void 0 ? _a : err.message})`);\n cachedConfig = { mode: \"config-missing\" };\n return cachedConfig;\n }\n try {\n const parsed = JSON.parse(raw);\n const images = (_c = (_b = parsed === null || parsed === void 0 ? void 0 : parsed.config) === null || _b === void 0 ? void 0 : _b.images) !== null && _c !== void 0 ? _c : {};\n cachedConfig = {\n mode: \"loaded\",\n images: {\n remotePatterns: Array.isArray(images.remotePatterns) ? images.remotePatterns : [],\n domains: Array.isArray(images.domains) ? images.domains : [],\n unoptimized: images.unoptimized === true\n }\n };\n return cachedConfig;\n } catch (err) {\n console.warn(`[image-config] failed to parse ${filePath}: ${err.message} \\u2014 allowing all image URLs`);\n cachedConfig = { mode: \"config-missing\" };\n return cachedConfig;\n }\n }\n function loadMatcher() {\n if (cachedMatcher !== void 0)\n return cachedMatcher;\n try {\n const dynamicRequire = eval(\"require\");\n const mod = dynamicRequire(\"next/dist/shared/lib/match-remote-pattern\");\n const hasRemoteMatch = mod === null || mod === void 0 ? void 0 : mod.hasRemoteMatch;\n if (typeof hasRemoteMatch !== \"function\") {\n throw new Error(\"hasRemoteMatch not exported\");\n }\n cachedMatcher = hasRemoteMatch;\n return cachedMatcher;\n } catch (err) {\n if (!warnedMatcherMissing) {\n warnedMatcherMissing = true;\n console.warn(`[image-config] cannot load next/dist/shared/lib/match-remote-pattern (${err.message}) \\u2014 falling back to deny-external-only mode`);\n }\n cachedMatcher = null;\n return null;\n }\n }\n function validateImageUrl(absoluteUrl, hostHeader) {\n const cfg = loadImageConfig();\n if (cfg.mode === \"config-missing\") {\n return { ok: true, reason: \"config-missing\" };\n }\n const { images } = cfg;\n if (images.unoptimized) {\n return { ok: true, reason: \"unoptimized\" };\n }\n const reqHost = hostHeader.toLowerCase();\n const urlHost = absoluteUrl.host.toLowerCase();\n if (reqHost && reqHost === urlHost) {\n return { ok: true, reason: \"same-origin\" };\n }\n const matcher = loadMatcher();\n if (matcher === null) {\n return { ok: false, reason: \"matcher-unavailable\" };\n }\n if (matcher(images.domains, images.remotePatterns, absoluteUrl)) {\n return { ok: true, reason: \"pattern-match\" };\n }\n return { ok: false, reason: \"remote-pattern-not-matched\" };\n }\n exports.validateImageUrl = validateImageUrl;\n function _resetImageConfigCacheForTests() {\n cachedConfig = void 0;\n cachedMatcher = void 0;\n warnedMatcherMissing = false;\n }\n exports._resetImageConfigCacheForTests = _resetImageConfigCacheForTests;\n function _setMatcherForTests(impl) {\n cachedMatcher = impl;\n }\n exports._setMatcherForTests = _setMatcherForTests;\n }\n});\n\n// dist/runtime/image-proxy.js\nvar require_image_proxy = __commonJS({\n \"dist/runtime/image-proxy.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.handleImageProxy = void 0;\n var stream_1 = require(\"stream\");\n var gateway_auth_1 = require_gateway_auth();\n var image_config_1 = require_image_config();\n var GATEWAY_TIMEOUT_MS = 1e4;\n var PASSTHROUGH_HEADERS = [\n \"content-type\",\n \"content-length\",\n \"cache-control\",\n \"etag\",\n \"vary\",\n \"last-modified\",\n \"content-security-policy\"\n ];\n function isExternalImageUrl(url) {\n return url.startsWith(\"http://\") || url.startsWith(\"https://\");\n }\n function normalizeImageUrl(rawUrl) {\n if (rawUrl.startsWith(\"http://\") || rawUrl.startsWith(\"https://\")) {\n return rawUrl;\n }\n return rawUrl.startsWith(\"/\") ? rawUrl : `/${rawUrl}`;\n }\n function writeJson(res, status, body) {\n res.statusCode = status;\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(body));\n }\n async function handleImageProxy(req, res) {\n const reqUrl = req.url || \"\";\n const qIdx = reqUrl.indexOf(\"?\");\n if (qIdx === -1) {\n return writeJson(res, 400, { error: \"Missing query parameters\" });\n }\n const params = new URLSearchParams(reqUrl.slice(qIdx + 1));\n const rawUrl = params.get(\"url\");\n const w = params.get(\"w\");\n const q = params.get(\"q\");\n if (!rawUrl || !w) {\n return writeJson(res, 400, {\n error: \"Missing required parameters: url, w\"\n });\n }\n const imageUrl = normalizeImageUrl(rawUrl);\n if (isExternalImageUrl(imageUrl)) {\n let parsedUrl;\n try {\n parsedUrl = new URL(imageUrl);\n } catch (_a) {\n return writeJson(res, 400, { error: \"Invalid url parameter\" });\n }\n const hostHeader = req.headers[\"host\"] || \"\";\n const verdict = (0, image_config_1.validateImageUrl)(parsedUrl, hostHeader);\n if (!verdict.ok) {\n return writeJson(res, 400, { error: \"url not allowed\" });\n }\n }\n const cfg = (0, gateway_auth_1.loadGatewayAuthConfig)();\n if (!cfg) {\n return writeJson(res, 500, {\n error: \"Gateway auth config missing\"\n });\n }\n const upstreamParams = new URLSearchParams({ url: imageUrl, w });\n if (q)\n upstreamParams.set(\"q\", q);\n const upstreamPath = `/image/optimize?${upstreamParams}`;\n const ifNoneMatch = req.headers[\"if-none-match\"];\n const upstreamHeaders = {};\n if (typeof ifNoneMatch === \"string\") {\n upstreamHeaders[\"if-none-match\"] = ifNoneMatch;\n }\n const accept = req.headers[\"accept\"];\n if (typeof accept === \"string\") {\n upstreamHeaders[\"accept\"] = accept;\n }\n let upstream;\n try {\n upstream = await (0, gateway_auth_1.gatewayFetch)(cfg, upstreamPath, {\n method: \"GET\",\n headers: upstreamHeaders,\n timeoutMs: GATEWAY_TIMEOUT_MS\n });\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[image-proxy] Gateway timeout after ${GATEWAY_TIMEOUT_MS}ms: ${imageUrl}`);\n return writeJson(res, 504, { error: \"Upstream timeout\" });\n }\n console.warn(`[image-proxy] Gateway fetch error: ${err.message} (url=${imageUrl})`);\n return writeJson(res, 502, { error: \"Bad gateway\" });\n }\n res.statusCode = upstream.status;\n for (const name of PASSTHROUGH_HEADERS) {\n const value = upstream.headers.get(name);\n if (value !== null) {\n res.setHeader(name, value);\n }\n }\n if (upstream.status === 304 || !upstream.body) {\n res.end();\n return;\n }\n try {\n const nodeStream = stream_1.Readable.fromWeb(upstream.body);\n nodeStream.on(\"error\", (err) => {\n console.warn(`[image-proxy] Stream error: ${err.message}`);\n if (!res.writableEnded)\n res.end();\n });\n nodeStream.pipe(res);\n } catch (err) {\n console.warn(`[image-proxy] Pipe setup failed: ${err.message}`);\n if (!res.headersSent) {\n writeJson(res, 502, { error: \"Stream setup failed\" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n }\n exports2.handleImageProxy = handleImageProxy;\n }\n});\n\n// dist/runtime/edge-context.js\nvar require_edge_context = __commonJS({\n \"dist/runtime/edge-context.js\"(exports2) {\n \"use strict\";\n var _a;\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.getCacheTags = exports2.setCacheTags = exports2.getEdgeContext = exports2.runWithEdgeContext = exports2.buildEdgeContextFromHeaders = void 0;\n var node_async_hooks_1 = require(\"node:async_hooks\");\n var ALS_KEY = Symbol.for(\"pcg.edgeContext.als\");\n var globalRef = globalThis;\n var storage = (_a = globalRef[ALS_KEY]) !== null && _a !== void 0 ? _a : globalRef[ALS_KEY] = new node_async_hooks_1.AsyncLocalStorage();\n var SITE_ID_HEADER = \"x-er-origin-site-id\";\n var HOSTNAME_HEADER = \"host\";\n var FORWARDED_HOSTNAME_HEADER = \"x-forwarded-host\";\n function pickHeader(headers, name) {\n var _a2;\n return (_a2 = headers[name]) !== null && _a2 !== void 0 ? _a2 : headers[name.toLowerCase()];\n }\n function parseHostname(raw) {\n var _a2;\n if (!raw)\n return void 0;\n const first = (_a2 = raw.split(\",\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\n return first || void 0;\n }\n function parseSiteId(raw) {\n if (!raw)\n return void 0;\n const trimmed = raw.trim();\n if (!trimmed)\n return void 0;\n const n = Number(trimmed);\n return Number.isFinite(n) && trimmed === String(n) ? n : trimmed;\n }\n function buildEdgeContextFromHeaders(headers) {\n var _a2;\n const ctx = {};\n const siteId = parseSiteId(pickHeader(headers, SITE_ID_HEADER));\n if (siteId !== void 0)\n ctx.siteId = siteId;\n const hostname = (_a2 = parseHostname(pickHeader(headers, HOSTNAME_HEADER))) !== null && _a2 !== void 0 ? _a2 : parseHostname(pickHeader(headers, FORWARDED_HOSTNAME_HEADER));\n if (hostname)\n ctx.hostname = hostname;\n return ctx;\n }\n exports2.buildEdgeContextFromHeaders = buildEdgeContextFromHeaders;\n function runWithEdgeContext(headers, fn) {\n const ctx = buildEdgeContextFromHeaders(headers);\n return storage.run(ctx, fn);\n }\n exports2.runWithEdgeContext = runWithEdgeContext;\n function getEdgeContext() {\n var _a2;\n return (_a2 = storage.getStore()) !== null && _a2 !== void 0 ? _a2 : {};\n }\n exports2.getEdgeContext = getEdgeContext;\n function setCacheTags(tags) {\n const store = storage.getStore();\n if (store)\n store.cacheTags = tags;\n }\n exports2.setCacheTags = setCacheTags;\n function getCacheTags() {\n var _a2;\n return (_a2 = storage.getStore()) === null || _a2 === void 0 ? void 0 : _a2.cacheTags;\n }\n exports2.getCacheTags = getCacheTags;\n }\n});\n\n// dist/adapters/wrappers/node-server.js\nvar __createBinding2 = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault2 = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar2 = exports && exports.__importStar || function(mod2) {\n if (mod2 && mod2.__esModule) return mod2;\n var result = {};\n if (mod2 != null) {\n for (var k in mod2) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding2(result, mod2, k);\n }\n __setModuleDefault2(result, mod2);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bridgeOpenNextHandler = void 0;\nvar http = __importStar2(require(\"http\"));\nvar fs2 = __importStar2(require(\"fs\"));\nvar path2 = __importStar2(require(\"path\"));\nvar node_request_1 = require_node_request();\nvar image_proxy_1 = require_image_proxy();\nvar edge_context_1 = require_edge_context();\nvar efc_observability_cjs_1 = require_efc_observability();\nvar PCG_DEFAULT_LOG_FILE = \"/tmp/pcg.log\";\nfunction setupFileLogger() {\n const logFile = process.env.PCG_LOG_FILE || PCG_DEFAULT_LOG_FILE;\n const logDir = path2.dirname(logFile);\n try {\n fs2.mkdirSync(logDir, { recursive: true });\n } catch (_a) {\n }\n let stream;\n try {\n stream = fs2.createWriteStream(logFile, { flags: \"a\" });\n stream.on(\"error\", () => {\n stream = void 0;\n });\n } catch (_b) {\n }\n const timestamp = () => {\n const d = /* @__PURE__ */ new Date();\n return d.toISOString().replace(\"T\", \" \").replace(\"Z\", \"\");\n };\n const origLog = console.log.bind(console);\n const origError = console.error.bind(console);\n const origWarn = console.warn.bind(console);\n const writeToFile = (level, args) => {\n if (!stream)\n return;\n try {\n const msg = args.map((a) => typeof a === \"string\" ? a : JSON.stringify(a, null, 2)).join(\" \");\n stream.write(`${timestamp()} [${level}] ${msg}\n`);\n } catch (_a) {\n }\n };\n console.log = (...args) => {\n origLog(...args);\n writeToFile(\"INFO\", args);\n };\n console.error = (...args) => {\n origError(...args);\n writeToFile(\"ERROR\", args);\n };\n console.warn = (...args) => {\n origWarn(...args);\n writeToFile(\"WARN\", args);\n };\n process.on(\"uncaughtException\", (err) => {\n writeToFile(\"FATAL\", [`Uncaught Exception: ${err.stack || err.message}`]);\n if (!stream) {\n origError(err);\n process.exit(1);\n return;\n }\n stream.end(() => process.exit(1));\n setTimeout(() => process.exit(1), 1e3).unref();\n });\n process.on(\"unhandledRejection\", (reason) => {\n writeToFile(\"ERROR\", [`Unhandled Rejection: ${reason}`]);\n });\n}\nsetupFileLogger();\n(0, efc_observability_cjs_1.installEfcObservability)();\nvar MIME_TYPES = {\n \".js\": \"application/javascript\",\n \".mjs\": \"application/javascript\",\n \".css\": \"text/css\",\n \".html\": \"text/html\",\n \".json\": \"application/json\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".map\": \"application/json\",\n \".txt\": \"text/plain\",\n \".webp\": \"image/webp\"\n};\nfunction serveStaticFile(assetsDir, req, res) {\n var _a, _b;\n const urlPath = (_b = (_a = req.url) === null || _a === void 0 ? void 0 : _a.split(\"?\")[0]) !== null && _b !== void 0 ? _b : \"/\";\n if (urlPath === \"/\" || !urlPath.startsWith(\"/\"))\n return false;\n const filePath = path2.join(assetsDir, urlPath);\n const normalizedPath = path2.normalize(filePath);\n if (!normalizedPath.startsWith(assetsDir)) {\n res.writeHead(403);\n res.end();\n return true;\n }\n let stat;\n try {\n stat = fs2.statSync(normalizedPath);\n } catch (_c) {\n return false;\n }\n if (!stat.isFile())\n return false;\n const ext = path2.extname(normalizedPath);\n const contentType = MIME_TYPES[ext] || \"application/octet-stream\";\n const isHashedAsset = urlPath.startsWith(\"/_next/static/\");\n res.writeHead(200, {\n \"Content-Type\": contentType,\n \"Content-Length\": stat.size,\n \"Cache-Control\": isHashedAsset ? \"public, max-age=31536000, immutable\" : \"public, max-age=60\"\n });\n fs2.createReadStream(normalizedPath).pipe(res);\n return true;\n}\nfunction bridgeOpenNextHandler(handler, converter) {\n return async (req, res) => {\n try {\n const event = await (0, node_request_1.convertNodeRequest)(req, converter);\n const abortController = new AbortController();\n res.on(\"close\", () => abortController.abort());\n const streamCreator = {\n writeHeaders(prelude) {\n const cacheTags = (0, edge_context_1.getCacheTags)();\n if (cacheTags) {\n res.setHeader(\"Cache-Tag\", cacheTags);\n }\n delete prelude.headers[\"x-next-cache-tags\"];\n res.setHeader(\"Set-Cookie\", prelude.cookies);\n res.writeHead(prelude.statusCode, prelude.headers);\n (0, efc_observability_cjs_1.markResponseStreaming)(prelude.statusCode);\n res.flushHeaders();\n return res;\n },\n abortSignal: abortController.signal\n };\n await (0, edge_context_1.runWithEdgeContext)(event.headers, () => handler(event, { streamCreator }));\n } catch (err) {\n console.error(`[pcg-node] ${req.method} ${req.url} 500:`, err.stack || err.message || err);\n if (!res.headersSent) {\n const isDev = process.env.NODE_ENV !== \"production\";\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({\n error: \"Internal Server Error\",\n ...isDev && { message: err.message, stack: err.stack }\n }));\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n };\n}\nexports.bridgeOpenNextHandler = bridgeOpenNextHandler;\nasync function wrapper(handler, converter) {\n var _a;\n const port = parseInt((_a = process.env.PORT) !== null && _a !== void 0 ? _a : \"3000\", 10);\n const host = process.env.HOST || \"0.0.0.0\";\n const assetsDir = path2.resolve(process.cwd(), \"..\", \"..\", \"assets\");\n const logFile = process.env.PCG_LOG_FILE || PCG_DEFAULT_LOG_FILE;\n console.log(`[pcg-node] File logger \\u2192 ${logFile}`);\n if (!fs2.existsSync(assetsDir)) {\n console.warn(`[pcg-node] assets directory not found at ${assetsDir} \\u2014 static file requests will fall through to Next handler`);\n }\n const dispatchToNext = bridgeOpenNextHandler(handler, converter);\n const server = http.createServer(async (req, res) => {\n var _a2, _b;\n const urlPath = (_b = (_a2 = req.url) === null || _a2 === void 0 ? void 0 : _a2.split(\"?\")[0]) !== null && _b !== void 0 ? _b : \"/\";\n if (urlPath !== \"/__health\") {\n console.log(`[pcg-node] --> ${req.method} ${req.url}\n` + JSON.stringify(req.headers, null, 2));\n }\n if (urlPath === \"/__health\") {\n res.writeHead(200, { \"Content-Type\": \"text/plain\" });\n res.end(\"OK\");\n return;\n }\n if (urlPath === \"/_next/image\") {\n try {\n await (0, image_proxy_1.handleImageProxy)(req, res);\n } catch (err) {\n console.error(\"[pcg-node] image-proxy error:\", err);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image proxy failed\" }));\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n if (serveStaticFile(assetsDir, req, res))\n return;\n await dispatchToNext(req, res);\n });\n let shuttingDown = false;\n const shutdown = (signal) => {\n if (shuttingDown)\n return;\n shuttingDown = true;\n console.log(`[pcg-node] ${signal} received, shutting down...`);\n server.close(() => {\n void (0, efc_observability_cjs_1.flushFunctionLogs)(1e4).then(() => process.exit(0), () => process.exit(0));\n });\n setTimeout(() => process.exit(0), 11e3).unref();\n };\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n await new Promise((resolve) => {\n server.listen(port, host, () => {\n console.log(`[pcg-node] Listening on ${host}:${port}`);\n console.log(`[pcg-node] assets: ${assetsDir}`);\n console.log(\"[pcg-node] routes: /__health, /_next/image, /_next/static/*, <next>\");\n resolve();\n });\n });\n return () => {\n server.close();\n };\n}\nvar wrapperDef = {\n wrapper,\n name: \"pcg-node\",\n supportStreaming: true\n};\nexports.default = wrapperDef;\n",
|
|
5
|
-
"overrides/incrementalCache/gateway.js": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\n\n// dist/_protocol/types.js\nvar require_types = __commonJS({\n \"dist/_protocol/types.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n }\n});\n\n// dist/_protocol/keys.js\nvar require_keys = __commonJS({\n \"dist/_protocol/keys.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.buildAstroSessionKey = exports2.buildAstroRouteCacheTagKey = exports2.buildAstroRouteCacheOssKey = exports2.buildPageMetadataKey = exports2.buildTagKey = exports2.buildStaticAssetKey = exports2.buildOssKey = void 0;\n function stripLeadingSlash(s) {\n return s.replace(/^\\/+/, \"\");\n }\n function buildOssKey(params) {\n const { appId, buildId, cacheType = \"cache\" } = params;\n const key = stripLeadingSlash(params.key);\n if (cacheType === \"fetch\") {\n return `${appId}/__fetch/${buildId}/${key}`;\n }\n if (cacheType === \"composable\") {\n return `${appId}/${buildId}/${key}.composable`;\n }\n return `${appId}/${buildId}/${key}.cache`;\n }\n exports2.buildOssKey = buildOssKey;\n function buildStaticAssetKey(params) {\n const p = stripLeadingSlash(params.path);\n return `${params.appId}/_next/static/${p}`;\n }\n exports2.buildStaticAssetKey = buildStaticAssetKey;\n function buildTagKey(params) {\n return {\n app_id: params.appId,\n tag: `${params.buildId}/${params.tag}`,\n path: `${params.buildId}/${params.path}`\n };\n }\n exports2.buildTagKey = buildTagKey;\n function buildPageMetadataKey(params) {\n return {\n app_id: params.appId,\n url: params.url\n };\n }\n exports2.buildPageMetadataKey = buildPageMetadataKey;\n function buildAstroRouteCacheOssKey(params) {\n return `${params.appId}/${params.buildId}/__astro-route/${params.digest}.cache`;\n }\n exports2.buildAstroRouteCacheOssKey = buildAstroRouteCacheOssKey;\n function buildAstroRouteCacheTagKey(params) {\n return `${params.buildId}/astro/${params.digest}`;\n }\n exports2.buildAstroRouteCacheTagKey = buildAstroRouteCacheTagKey;\n function buildAstroSessionKey(params) {\n return `astro:session:${params.namespace}:${params.appId}:${params.sessionDigest}`;\n }\n exports2.buildAstroSessionKey = buildAstroSessionKey;\n }\n});\n\n// dist/_protocol/endpoints.js\nvar require_endpoints = __commonJS({\n \"dist/_protocol/endpoints.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.buildCentralEndpoints = void 0;\n function stripTrailingSlashes(s) {\n return s.replace(/\\/+$/, \"\");\n }\n function buildCentralEndpoints(base) {\n const b = stripTrailingSlashes(base);\n return {\n base: b,\n cache: `${b}/cache`,\n cacheRefresh: `${b}/cache/refresh`,\n revalidateTag: `${b}/revalidate/tag`,\n revalidatePath: `${b}/revalidate/path`,\n tagByTag: `${b}/tag/by-tag`,\n tagByPath: `${b}/tag/by-path`,\n tagLastModified: `${b}/tag/last-modified`,\n tagWrite: `${b}/tag/write`,\n deploySts: `${b}/deploy/sts-token`,\n deployTags: `${b}/deploy/tags`,\n astroSession: (sessionId) => `${b}/astro/v1/sessions/${encodeURIComponent(sessionId)}`\n };\n }\n exports2.buildCentralEndpoints = buildCentralEndpoints;\n }\n});\n\n// dist/_protocol/index.js\nvar require_protocol = __commonJS({\n \"dist/_protocol/index.js\"(exports2) {\n \"use strict\";\n var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);\n };\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n __exportStar(require_types(), exports2);\n __exportStar(require_keys(), exports2);\n __exportStar(require_endpoints(), exports2);\n }\n});\n\n// dist/runtime/efc-observability.cjs\nvar require_efc_observability = __commonJS({\n \"dist/runtime/efc-observability.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var { AsyncLocalStorage } = require(\"node:async_hooks\");\n var diagnostics = require(\"node:diagnostics_channel\");\n var http = require(\"node:http\");\n var { randomUUID } = require(\"node:crypto\");\n var { performance } = require(\"node:perf_hooks\");\n var { Console } = require(\"node:console\");\n var KEY = Symbol.for(\"pcg.efc.observability\");\n var state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n });\n var LOG_LIMIT = 32 * 1024;\n var BODY_LIMIT = 64 * 1024;\n var DEADLINE_MS = 5e3;\n var diagnosticConsole;\n function warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n }\n function safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n }\n function validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n }\n function validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n }\n function traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n }\n function safePath(value) {\n const path2 = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path2.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n }\n function notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n for (const done of state.waiters)\n done(true);\n }\n function drop(reason) {\n state.counts.dropped++;\n warning(reason);\n }\n function rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n }\n function snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n }\n function finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n }\n function closeRoot(ctx) {\n if (ctx.closed || !ctx.report)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n }\n function complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n }\n function responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n }\n function installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call)\n complete(call);\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]);\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!enabled && !trace)\n return;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n ctx = {\n trace,\n metadata,\n report,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!report) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path2 = safePath(req.url);\n if (validText(path2, 2048))\n metadata.path = path2;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http.Server.prototype.emit === observedEmit)\n http.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n }\n async function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n if (ctx && ctx.trace)\n init.headers.set(\"eagleeye-traceid\", ctx.trace);\n if (!ctx || !ctx.report || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n return response;\n } catch (error) {\n safe(() => complete(call));\n throw error;\n }\n }\n function markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n }\n function send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n }\n function pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n }\n function flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n }\n function getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n }\n function getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n }\n state.observeGatewayFetch = observeGatewayFetch;\n state.flushFunctionLogs = flushFunctionLogs;\n state.getEfcTraceId = getEfcTraceId;\n module2.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId\n };\n }\n});\n\n// dist/runtime/gateway-auth.js\nvar require_gateway_auth = __commonJS({\n \"dist/runtime/gateway-auth.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.gatewayFetch = exports2.signGatewayHeaders = exports2.loadGatewayAuthConfig = void 0;\n var crypto_1 = require(\"crypto\");\n var efc_observability_cjs_1 = require_efc_observability();\n var DEFAULT_TTL_MS = 5 * 60 * 1e3;\n var DEFAULT_TIMEOUT_MS = 5e3;\n function _fetch(input, init) {\n var _a, _b;\n const gatewayGlobalFetch = globalThis.fetch;\n const fn = gatewayGlobalFetch.__nextPatched ? (_b = (_a = gatewayGlobalFetch._nextOriginalFetch) !== null && _a !== void 0 ? _a : globalThis.__originalFetch) !== null && _b !== void 0 ? _b : gatewayGlobalFetch : gatewayGlobalFetch;\n return fn(input, init);\n }\n function loadGatewayAuthConfig() {\n const gatewayUrl = process.env.ESA_CACHE_GW_GATEWAY_ENDPOINT;\n const authKey = process.env.ESA_CACHE_GW_AUTH_KEY;\n const aliuid = process.env.ESA_CACHE_GW_ALIUID;\n const routinename = process.env.ESA_CACHE_GW_FUNCTIONNAME;\n const version = process.env.ESA_CACHE_GW_VERSION;\n const missing = [];\n if (!gatewayUrl)\n missing.push(\"ESA_CACHE_GW_GATEWAY_ENDPOINT\");\n if (!authKey)\n missing.push(\"ESA_CACHE_GW_AUTH_KEY\");\n if (!aliuid)\n missing.push(\"ESA_CACHE_GW_ALIUID\");\n if (!routinename)\n missing.push(\"ESA_CACHE_GW_FUNCTIONNAME\");\n if (!version)\n missing.push(\"ESA_CACHE_GW_VERSION\");\n if (missing.length > 0) {\n console.error(`[gateway-auth] \\u7F3A\\u5C11\\u5FC5\\u9700\\u7684\\u73AF\\u5883\\u53D8\\u91CF: ${missing.join(\", \")}`);\n return null;\n }\n return {\n gatewayUrl: gatewayUrl.replace(/\\/+$/, \"\"),\n secret: authKey,\n aliuid,\n routinename,\n version\n };\n }\n exports2.loadGatewayAuthConfig = loadGatewayAuthConfig;\n function signGatewayHeaders(cfg, ttlMs = DEFAULT_TTL_MS) {\n const expires = String(Date.now() + ttlMs);\n const md5Hash = (0, crypto_1.createHash)(\"md5\").update(`${cfg.secret}${expires}${cfg.aliuid}${cfg.routinename}${cfg.version}`).digest(\"hex\");\n return {\n authorization: `${expires}-${md5Hash}`,\n aliuid: cfg.aliuid,\n routinename: cfg.routinename,\n version: cfg.version\n };\n }\n exports2.signGatewayHeaders = signGatewayHeaders;\n async function gatewayFetch(cfg, pathOrUrl, init) {\n var _a, _b;\n const url = pathOrUrl.startsWith(\"/\") ? `${cfg.gatewayUrl}${pathOrUrl}` : pathOrUrl;\n const signed = signGatewayHeaders(cfg);\n const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);\n headers.set(\"Authorization\", signed.authorization);\n headers.set(\"AliUid\", signed.aliuid);\n headers.set(\"RoutineName\", signed.routinename);\n headers.set(\"Version\", signed.version);\n const timeoutMs = (_a = init === null || init === void 0 ? void 0 : init.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await (0, efc_observability_cjs_1.observeGatewayFetch)(url, {\n ...init,\n headers,\n signal: (_b = init === null || init === void 0 ? void 0 : init.signal) !== null && _b !== void 0 ? _b : controller.signal\n }, _fetch);\n } finally {\n clearTimeout(timer);\n }\n }\n exports2.gatewayFetch = gatewayFetch;\n }\n});\n\n// dist/runtime/edge-context.js\nvar require_edge_context = __commonJS({\n \"dist/runtime/edge-context.js\"(exports2) {\n \"use strict\";\n var _a;\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.getCacheTags = exports2.setCacheTags = exports2.getEdgeContext = exports2.runWithEdgeContext = exports2.buildEdgeContextFromHeaders = void 0;\n var node_async_hooks_1 = require(\"node:async_hooks\");\n var ALS_KEY = Symbol.for(\"pcg.edgeContext.als\");\n var globalRef = globalThis;\n var storage = (_a = globalRef[ALS_KEY]) !== null && _a !== void 0 ? _a : globalRef[ALS_KEY] = new node_async_hooks_1.AsyncLocalStorage();\n var SITE_ID_HEADER = \"x-er-origin-site-id\";\n var HOSTNAME_HEADER = \"host\";\n var FORWARDED_HOSTNAME_HEADER = \"x-forwarded-host\";\n function pickHeader(headers, name) {\n var _a2;\n return (_a2 = headers[name]) !== null && _a2 !== void 0 ? _a2 : headers[name.toLowerCase()];\n }\n function parseHostname(raw) {\n var _a2;\n if (!raw)\n return void 0;\n const first = (_a2 = raw.split(\",\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\n return first || void 0;\n }\n function parseSiteId(raw) {\n if (!raw)\n return void 0;\n const trimmed = raw.trim();\n if (!trimmed)\n return void 0;\n const n = Number(trimmed);\n return Number.isFinite(n) && trimmed === String(n) ? n : trimmed;\n }\n function buildEdgeContextFromHeaders(headers) {\n var _a2;\n const ctx = {};\n const siteId = parseSiteId(pickHeader(headers, SITE_ID_HEADER));\n if (siteId !== void 0)\n ctx.siteId = siteId;\n const hostname = (_a2 = parseHostname(pickHeader(headers, HOSTNAME_HEADER))) !== null && _a2 !== void 0 ? _a2 : parseHostname(pickHeader(headers, FORWARDED_HOSTNAME_HEADER));\n if (hostname)\n ctx.hostname = hostname;\n return ctx;\n }\n exports2.buildEdgeContextFromHeaders = buildEdgeContextFromHeaders;\n function runWithEdgeContext(headers, fn) {\n const ctx = buildEdgeContextFromHeaders(headers);\n return storage.run(ctx, fn);\n }\n exports2.runWithEdgeContext = runWithEdgeContext;\n function getEdgeContext() {\n var _a2;\n return (_a2 = storage.getStore()) !== null && _a2 !== void 0 ? _a2 : {};\n }\n exports2.getEdgeContext = getEdgeContext;\n function setCacheTags(tags) {\n const store = storage.getStore();\n if (store)\n store.cacheTags = tags;\n }\n exports2.setCacheTags = setCacheTags;\n function getCacheTags() {\n var _a2;\n return (_a2 = storage.getStore()) === null || _a2 === void 0 ? void 0 : _a2.cacheTags;\n }\n exports2.getCacheTags = getCacheTags;\n }\n});\n\n// dist/overrides/incrementalCache/gateway.js\nvar __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = exports && exports.__importStar || function(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) {\n for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n }\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar fs = __importStar(require(\"fs\"));\nvar path = __importStar(require(\"path\"));\nvar protocol_1 = require_protocol();\nvar gateway_auth_1 = require_gateway_auth();\nvar edge_context_1 = require_edge_context();\nvar GET_TIMEOUT = 5e3;\nvar SET_TIMEOUT = 1e4;\nvar DELETE_TIMEOUT = 5e3;\nfunction normalizeCacheType(value) {\n if (value === true || value === \"fetch\")\n return \"fetch\";\n if (value === \"composable\")\n return \"composable\";\n return \"cache\";\n}\nfunction buildKey(config, key, cacheTypeInput) {\n return (0, protocol_1.buildOssKey)({\n appId: `${config.aliuid}/${config.routinename}`,\n buildId: config.version,\n key,\n cacheType: normalizeCacheType(cacheTypeInput)\n });\n}\nvar GatewayIncrementalCache = class {\n constructor() {\n this.name = \"gateway-incremental-cache\";\n this.config = null;\n this.configLoaded = false;\n }\n /**\n * 延迟加载配置,避免在构造函数中因环境变量缺失而阻塞 Function 启动。\n */\n getConfig() {\n if (!this.configLoaded) {\n this.config = (0, gateway_auth_1.loadGatewayAuthConfig)();\n this.configLoaded = true;\n }\n return this.config;\n }\n /**\n * 从 Gateway 读取缓存。\n * Gateway 不可用时降级读 .open-next/cache/ 下的预构建文件(本地开发)。\n */\n async get(key, cacheType) {\n var _a, _b;\n const config = this.getConfig();\n if (!config)\n return this.getFromLocalCache(key, cacheType);\n const ossKey = buildKey(config, key, cacheType);\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, `/storage/${ossKey}`, {\n method: \"GET\",\n timeoutMs: GET_TIMEOUT\n });\n if (res.status === 404)\n return null;\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[incrementalCache] GET \\u88AB\\u62D2\\u7EDD: key=\"${ossKey}\" (${res.status})\\uFF0C\\u8BF7\\u68C0\\u67E5\\u7B7E\\u540D secret \\u6216 key \\u524D\\u7F00`);\n } else {\n console.warn(`[incrementalCache] GET \\u5931\\u8D25: key=\"${ossKey}\", \\u72B6\\u6001\\u7801=${res.status}`);\n }\n return null;\n }\n const body = await res.text();\n let envelope;\n try {\n envelope = JSON.parse(body);\n } catch (_c) {\n console.warn(`[incrementalCache] JSON \\u89E3\\u6790\\u5931\\u8D25: key=\"${ossKey}\"`);\n return null;\n }\n if (!envelope || typeof envelope !== \"object\" || typeof envelope.lastModified !== \"number\") {\n console.warn(`[incrementalCache] envelope \\u683C\\u5F0F\\u5F02\\u5E38\\u6216\\u7F3A lastModified: key=\"${ossKey}\"`);\n return null;\n }\n const val = envelope.value;\n const tags = (_b = (_a = val === null || val === void 0 ? void 0 : val.meta) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[\"x-next-cache-tags\"];\n if (typeof tags === \"string\") {\n (0, edge_context_1.setCacheTags)(tags);\n }\n return { value: envelope.value, lastModified: envelope.lastModified };\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[incrementalCache] GET \\u8D85\\u65F6: key=\"${ossKey}\" (${GET_TIMEOUT}ms)`);\n } else {\n console.warn(`[incrementalCache] GET \\u5F02\\u5E38: key=\"${ossKey}\", ${err.message}`);\n }\n return null;\n }\n }\n /**\n * 向 Gateway 写入缓存。\n * Gateway 不可用时降级写入本地 runtime cache 目录(本地开发)。\n */\n async set(key, value, cacheType) {\n var _a, _b;\n const tags = (_b = (_a = value === null || value === void 0 ? void 0 : value.meta) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[\"x-next-cache-tags\"];\n if (typeof tags === \"string\") {\n (0, edge_context_1.setCacheTags)(tags);\n }\n const config = this.getConfig();\n if (!config) {\n this.setToLocalCache(key, value, cacheType);\n return;\n }\n const ossKey = buildKey(config, key, cacheType);\n const body = JSON.stringify({ lastModified: Date.now(), value });\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, `/storage/${ossKey}`, {\n method: \"PUT\",\n headers: { \"Content-Type\": \"application/json\" },\n body,\n timeoutMs: SET_TIMEOUT\n });\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[incrementalCache] PUT \\u88AB\\u62D2\\u7EDD: key=\"${ossKey}\" (${res.status})\\uFF0C\\u8BF7\\u68C0\\u67E5\\u7B7E\\u540D secret \\u6216 key \\u524D\\u7F00`);\n } else {\n console.warn(`[incrementalCache] PUT \\u5931\\u8D25: key=\"${ossKey}\", \\u72B6\\u6001\\u7801=${res.status}`);\n }\n }\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[incrementalCache] PUT \\u8D85\\u65F6: key=\"${ossKey}\" (${SET_TIMEOUT}ms)`);\n } else {\n console.warn(`[incrementalCache] PUT \\u5F02\\u5E38: key=\"${ossKey}\", ${err.message}`);\n }\n }\n }\n // ---------------------------------------------------------------------------\n // 本地缓存目录解析\n // ---------------------------------------------------------------------------\n /**\n * 解析 .open-next/cache 根目录。\n * process.cwd() 在 pcg serve 时是 .open-next/server-functions/default/,\n * 向上两级即 .open-next/cache。\n */\n getCacheRoot() {\n return path.resolve(process.cwd(), \"..\", \"..\", \"cache\");\n }\n /**\n * 将旧 boolean 参数或新版字符串参数统一为缓存类型标识。\n */\n resolveTypeLabel(cacheType) {\n return normalizeCacheType(cacheType);\n }\n // ---------------------------------------------------------------------------\n // 本地读缓存\n // ---------------------------------------------------------------------------\n /**\n * 本地开发降级读缓存,仅在 Gateway 不可用时启用。\n *\n * 查找顺序:\n * 1. 运行时缓存: .open-next/cache/__runtime/{type}/{key}.cache\n * (set() 在本地模式下写入的 composable/fetch/cache 缓存)\n * 2. 预构建缓存: .open-next/cache/{buildId}/{key}.cache\n * (pcg build 生成的页面级别缓存)\n * 3. 预构建 fetch 缓存: .open-next/cache/__fetch/{buildId}/{key}\n * (pcg build 生成的 fetch 数据缓存)\n */\n getFromLocalCache(key, cacheTypeInput) {\n const cacheRoot = this.getCacheRoot();\n const cacheType = this.resolveTypeLabel(cacheTypeInput);\n const runtimeResult = this.readRuntimeCache(cacheRoot, cacheType, key);\n if (runtimeResult)\n return runtimeResult;\n if (cacheType === \"cache\") {\n return this.readPrebuildCache(cacheRoot, key);\n }\n if (cacheType === \"fetch\") {\n return this.readPrebuildFetchCache(cacheRoot, key);\n }\n return null;\n }\n /** 读运行时缓存: __runtime/{type}/{key}.cache */\n readRuntimeCache(cacheRoot, typeLabel, key) {\n try {\n const filePath = path.join(cacheRoot, \"__runtime\", typeLabel, `${key}.cache`);\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const envelope = JSON.parse(raw);\n if (envelope && typeof envelope === \"object\" && typeof envelope.lastModified === \"number\") {\n console.log(`[incrementalCache] runtime cache HIT: type=\"${typeLabel}\" key=\"${key}\"`);\n return { value: envelope.value, lastModified: envelope.lastModified };\n }\n } catch (_a) {\n }\n return null;\n }\n /** 读预构建缓存: {buildId}/{key}.cache */\n readPrebuildCache(cacheRoot, key) {\n var _a, _b;\n try {\n const entries = fs.readdirSync(cacheRoot).filter((d) => {\n if (d.startsWith(\"__\"))\n return false;\n try {\n return fs.statSync(path.join(cacheRoot, d)).isDirectory();\n } catch (_a2) {\n return false;\n }\n });\n for (const bid of entries) {\n const filePath = path.join(cacheRoot, bid, `${key}.cache`);\n try {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const value = JSON.parse(raw);\n const stat = fs.statSync(filePath);\n const tags = (_b = (_a = value === null || value === void 0 ? void 0 : value.meta) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[\"x-next-cache-tags\"];\n if (typeof tags === \"string\") {\n (0, edge_context_1.setCacheTags)(tags);\n }\n console.log(`[incrementalCache] local cache HIT: key=\"${key}\" tags=${tags !== null && tags !== void 0 ? tags : \"\\u2205\"}`);\n return { value, lastModified: stat.mtimeMs };\n } catch (_c) {\n continue;\n }\n }\n } catch (_d) {\n }\n return null;\n }\n /** 读预构建 fetch 缓存: __fetch/{buildId}/{key} (无 .cache 后缀) */\n readPrebuildFetchCache(cacheRoot, key) {\n try {\n const fetchDir = path.join(cacheRoot, \"__fetch\");\n const buildIds = fs.readdirSync(fetchDir).filter((d) => {\n try {\n return fs.statSync(path.join(fetchDir, d)).isDirectory();\n } catch (_a) {\n return false;\n }\n });\n for (const bid of buildIds) {\n const filePath = path.join(fetchDir, bid, key);\n try {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const value = JSON.parse(raw);\n const stat = fs.statSync(filePath);\n console.log(`[incrementalCache] local fetch cache HIT: key=\"${key}\"`);\n return { value, lastModified: stat.mtimeMs };\n } catch (_a) {\n continue;\n }\n }\n } catch (_b) {\n }\n return null;\n }\n // ---------------------------------------------------------------------------\n // 本地写缓存\n // ---------------------------------------------------------------------------\n /**\n * 本地开发降级写缓存。\n * 将 envelope { lastModified, value } 写入\n * .open-next/cache/__runtime/{type}/{key}.cache,\n * 供后续 getFromLocalCache() 读取。\n */\n setToLocalCache(key, value, cacheTypeInput) {\n try {\n const cacheRoot = this.getCacheRoot();\n const typeLabel = this.resolveTypeLabel(cacheTypeInput);\n const dir = path.join(cacheRoot, \"__runtime\", typeLabel);\n const filePath = path.join(dir, `${key}.cache`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n const envelope = JSON.stringify({ lastModified: Date.now(), value });\n fs.writeFileSync(filePath, envelope, \"utf-8\");\n console.log(`[incrementalCache] runtime cache SET: type=\"${typeLabel}\" key=\"${key}\"`);\n } catch (err) {\n console.warn(`[incrementalCache] runtime cache SET failed: key=\"${key}\", ${err.message}`);\n }\n }\n /**\n * 通过 Gateway 删除缓存。\n */\n async delete(key, cacheType) {\n const config = this.getConfig();\n if (!config)\n return;\n const ossKey = buildKey(config, key, cacheType);\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, `/storage/${ossKey}`, {\n method: \"DELETE\",\n timeoutMs: DELETE_TIMEOUT\n });\n if (res.status === 404)\n return;\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[incrementalCache] DELETE \\u88AB\\u62D2\\u7EDD: key=\"${ossKey}\" (${res.status})\\uFF0C\\u8BF7\\u68C0\\u67E5\\u7B7E\\u540D secret \\u6216 key \\u524D\\u7F00`);\n } else {\n console.warn(`[incrementalCache] DELETE \\u5931\\u8D25: key=\"${ossKey}\", \\u72B6\\u6001\\u7801=${res.status}`);\n }\n }\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[incrementalCache] DELETE \\u8D85\\u65F6: key=\"${ossKey}\" (${DELETE_TIMEOUT}ms)`);\n } else {\n console.warn(`[incrementalCache] DELETE \\u5F02\\u5E38: key=\"${ossKey}\", ${err.message}`);\n }\n }\n }\n};\nexports.default = GatewayIncrementalCache;\n",
|
|
6
|
-
"overrides/tagCache/gateway.js": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\n\n// dist/runtime/efc-observability.cjs\nvar require_efc_observability = __commonJS({\n \"dist/runtime/efc-observability.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var { AsyncLocalStorage } = require(\"node:async_hooks\");\n var diagnostics = require(\"node:diagnostics_channel\");\n var http = require(\"node:http\");\n var { randomUUID } = require(\"node:crypto\");\n var { performance } = require(\"node:perf_hooks\");\n var { Console } = require(\"node:console\");\n var KEY = Symbol.for(\"pcg.efc.observability\");\n var state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n });\n var LOG_LIMIT = 32 * 1024;\n var BODY_LIMIT = 64 * 1024;\n var DEADLINE_MS = 5e3;\n var diagnosticConsole;\n function warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n }\n function safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n }\n function validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n }\n function validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n }\n function traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n }\n function safePath(value) {\n const path = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n }\n function notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n for (const done of state.waiters)\n done(true);\n }\n function drop(reason) {\n state.counts.dropped++;\n warning(reason);\n }\n function rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n }\n function snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n }\n function finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n }\n function closeRoot(ctx) {\n if (ctx.closed || !ctx.report)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n }\n function complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n }\n function responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n }\n function installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call)\n complete(call);\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]);\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!enabled && !trace)\n return;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n ctx = {\n trace,\n metadata,\n report,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!report) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path = safePath(req.url);\n if (validText(path, 2048))\n metadata.path = path;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http.Server.prototype.emit === observedEmit)\n http.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n }\n async function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n if (ctx && ctx.trace)\n init.headers.set(\"eagleeye-traceid\", ctx.trace);\n if (!ctx || !ctx.report || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n return response;\n } catch (error) {\n safe(() => complete(call));\n throw error;\n }\n }\n function markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n }\n function send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n }\n function pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n }\n function flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n }\n function getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n }\n function getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n }\n state.observeGatewayFetch = observeGatewayFetch;\n state.flushFunctionLogs = flushFunctionLogs;\n state.getEfcTraceId = getEfcTraceId;\n module2.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId\n };\n }\n});\n\n// dist/runtime/gateway-auth.js\nvar require_gateway_auth = __commonJS({\n \"dist/runtime/gateway-auth.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.gatewayFetch = exports2.signGatewayHeaders = exports2.loadGatewayAuthConfig = void 0;\n var crypto_1 = require(\"crypto\");\n var efc_observability_cjs_1 = require_efc_observability();\n var DEFAULT_TTL_MS = 5 * 60 * 1e3;\n var DEFAULT_TIMEOUT_MS = 5e3;\n function _fetch(input, init) {\n var _a, _b;\n const gatewayGlobalFetch = globalThis.fetch;\n const fn = gatewayGlobalFetch.__nextPatched ? (_b = (_a = gatewayGlobalFetch._nextOriginalFetch) !== null && _a !== void 0 ? _a : globalThis.__originalFetch) !== null && _b !== void 0 ? _b : gatewayGlobalFetch : gatewayGlobalFetch;\n return fn(input, init);\n }\n function loadGatewayAuthConfig() {\n const gatewayUrl = process.env.ESA_CACHE_GW_GATEWAY_ENDPOINT;\n const authKey = process.env.ESA_CACHE_GW_AUTH_KEY;\n const aliuid = process.env.ESA_CACHE_GW_ALIUID;\n const routinename = process.env.ESA_CACHE_GW_FUNCTIONNAME;\n const version = process.env.ESA_CACHE_GW_VERSION;\n const missing = [];\n if (!gatewayUrl)\n missing.push(\"ESA_CACHE_GW_GATEWAY_ENDPOINT\");\n if (!authKey)\n missing.push(\"ESA_CACHE_GW_AUTH_KEY\");\n if (!aliuid)\n missing.push(\"ESA_CACHE_GW_ALIUID\");\n if (!routinename)\n missing.push(\"ESA_CACHE_GW_FUNCTIONNAME\");\n if (!version)\n missing.push(\"ESA_CACHE_GW_VERSION\");\n if (missing.length > 0) {\n console.error(`[gateway-auth] \\u7F3A\\u5C11\\u5FC5\\u9700\\u7684\\u73AF\\u5883\\u53D8\\u91CF: ${missing.join(\", \")}`);\n return null;\n }\n return {\n gatewayUrl: gatewayUrl.replace(/\\/+$/, \"\"),\n secret: authKey,\n aliuid,\n routinename,\n version\n };\n }\n exports2.loadGatewayAuthConfig = loadGatewayAuthConfig;\n function signGatewayHeaders(cfg, ttlMs = DEFAULT_TTL_MS) {\n const expires = String(Date.now() + ttlMs);\n const md5Hash = (0, crypto_1.createHash)(\"md5\").update(`${cfg.secret}${expires}${cfg.aliuid}${cfg.routinename}${cfg.version}`).digest(\"hex\");\n return {\n authorization: `${expires}-${md5Hash}`,\n aliuid: cfg.aliuid,\n routinename: cfg.routinename,\n version: cfg.version\n };\n }\n exports2.signGatewayHeaders = signGatewayHeaders;\n async function gatewayFetch(cfg, pathOrUrl, init) {\n var _a, _b;\n const url = pathOrUrl.startsWith(\"/\") ? `${cfg.gatewayUrl}${pathOrUrl}` : pathOrUrl;\n const signed = signGatewayHeaders(cfg);\n const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);\n headers.set(\"Authorization\", signed.authorization);\n headers.set(\"AliUid\", signed.aliuid);\n headers.set(\"RoutineName\", signed.routinename);\n headers.set(\"Version\", signed.version);\n const timeoutMs = (_a = init === null || init === void 0 ? void 0 : init.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await (0, efc_observability_cjs_1.observeGatewayFetch)(url, {\n ...init,\n headers,\n signal: (_b = init === null || init === void 0 ? void 0 : init.signal) !== null && _b !== void 0 ? _b : controller.signal\n }, _fetch);\n } finally {\n clearTimeout(timer);\n }\n }\n exports2.gatewayFetch = gatewayFetch;\n }\n});\n\n// dist/runtime/edge-context.js\nvar require_edge_context = __commonJS({\n \"dist/runtime/edge-context.js\"(exports2) {\n \"use strict\";\n var _a;\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.getCacheTags = exports2.setCacheTags = exports2.getEdgeContext = exports2.runWithEdgeContext = exports2.buildEdgeContextFromHeaders = void 0;\n var node_async_hooks_1 = require(\"node:async_hooks\");\n var ALS_KEY = Symbol.for(\"pcg.edgeContext.als\");\n var globalRef = globalThis;\n var storage = (_a = globalRef[ALS_KEY]) !== null && _a !== void 0 ? _a : globalRef[ALS_KEY] = new node_async_hooks_1.AsyncLocalStorage();\n var SITE_ID_HEADER = \"x-er-origin-site-id\";\n var HOSTNAME_HEADER = \"host\";\n var FORWARDED_HOSTNAME_HEADER = \"x-forwarded-host\";\n function pickHeader(headers, name) {\n var _a2;\n return (_a2 = headers[name]) !== null && _a2 !== void 0 ? _a2 : headers[name.toLowerCase()];\n }\n function parseHostname(raw) {\n var _a2;\n if (!raw)\n return void 0;\n const first = (_a2 = raw.split(\",\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\n return first || void 0;\n }\n function parseSiteId(raw) {\n if (!raw)\n return void 0;\n const trimmed = raw.trim();\n if (!trimmed)\n return void 0;\n const n = Number(trimmed);\n return Number.isFinite(n) && trimmed === String(n) ? n : trimmed;\n }\n function buildEdgeContextFromHeaders(headers) {\n var _a2;\n const ctx = {};\n const siteId = parseSiteId(pickHeader(headers, SITE_ID_HEADER));\n if (siteId !== void 0)\n ctx.siteId = siteId;\n const hostname = (_a2 = parseHostname(pickHeader(headers, HOSTNAME_HEADER))) !== null && _a2 !== void 0 ? _a2 : parseHostname(pickHeader(headers, FORWARDED_HOSTNAME_HEADER));\n if (hostname)\n ctx.hostname = hostname;\n return ctx;\n }\n exports2.buildEdgeContextFromHeaders = buildEdgeContextFromHeaders;\n function runWithEdgeContext(headers, fn) {\n const ctx = buildEdgeContextFromHeaders(headers);\n return storage.run(ctx, fn);\n }\n exports2.runWithEdgeContext = runWithEdgeContext;\n function getEdgeContext() {\n var _a2;\n return (_a2 = storage.getStore()) !== null && _a2 !== void 0 ? _a2 : {};\n }\n exports2.getEdgeContext = getEdgeContext;\n function setCacheTags(tags) {\n const store = storage.getStore();\n if (store)\n store.cacheTags = tags;\n }\n exports2.setCacheTags = setCacheTags;\n function getCacheTags() {\n var _a2;\n return (_a2 = storage.getStore()) === null || _a2 === void 0 ? void 0 : _a2.cacheTags;\n }\n exports2.getCacheTags = getCacheTags;\n }\n});\n\n// dist/runtime/build-id.js\nvar require_build_id = __commonJS({\n \"dist/runtime/build-id.js\"(exports2) {\n \"use strict\";\n var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });\n var __importStar = exports2 && exports2.__importStar || function(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) {\n for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n }\n __setModuleDefault(result, mod);\n return result;\n };\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.__setBuildIdForTest = exports2.__resetBuildIdCache = exports2.loadBuildId = void 0;\n var fs = __importStar(require(\"fs\"));\n var path = __importStar(require(\"path\"));\n var cached;\n function loadBuildId() {\n var _a;\n if (cached !== void 0)\n return cached;\n const p = path.join(__dirname, \".next\", \"BUILD_ID\");\n try {\n const v = fs.readFileSync(p, \"utf-8\").trim();\n cached = v || null;\n } catch (err) {\n if ((err === null || err === void 0 ? void 0 : err.code) !== \"ENOENT\") {\n console.warn(`[build-id] BUILD_ID read error ${p}: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n } else {\n console.warn(`[build-id] BUILD_ID not found at ${p}`);\n }\n cached = null;\n }\n return cached;\n }\n exports2.loadBuildId = loadBuildId;\n function __resetBuildIdCache() {\n cached = void 0;\n }\n exports2.__resetBuildIdCache = __resetBuildIdCache;\n function __setBuildIdForTest(v) {\n cached = v;\n }\n exports2.__setBuildIdForTest = __setBuildIdForTest;\n }\n});\n\n// dist/runtime/cdn-purge.js\nvar require_cdn_purge = __commonJS({\n \"dist/runtime/cdn-purge.js\"(exports2) {\n \"use strict\";\n var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });\n var __importStar = exports2 && exports2.__importStar || function(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) {\n for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n }\n __setModuleDefault(result, mod);\n return result;\n };\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.createCdnPurgeClient = exports2.loadCdnPurgeConfig = void 0;\n var fs = __importStar(require(\"fs\"));\n var path = __importStar(require(\"path\"));\n var gateway_auth_12 = require_gateway_auth();\n var edge_context_12 = require_edge_context();\n var build_id_1 = require_build_id();\n var REFRESH_TIMEOUT_MS = 15e3;\n var URL_BATCH_SIZE = 100;\n var REFRESH_CONCURRENCY = 4;\n var TAG_MANIFEST_FILENAME = \"__pcg_tag_manifest.json\";\n function stripLeadingSlash2(s) {\n return s.replace(/^\\/+/, \"\");\n }\n function ensureLeadingSlash(s) {\n return s.startsWith(\"/\") ? s : `/${s}`;\n }\n function loadCdnPurgeConfig() {\n const base = (0, gateway_auth_12.loadGatewayAuthConfig)();\n if (!base)\n return null;\n return { ...base };\n }\n exports2.loadCdnPurgeConfig = loadCdnPurgeConfig;\n function createCdnPurgeClient(cfg) {\n var _a, _b;\n const buildId = (_a = cfg.buildId) !== null && _a !== void 0 ? _a : (0, build_id_1.loadBuildId)();\n const pathPrefix = buildId ? `${buildId}/` : null;\n const manifestPath = (_b = cfg.manifestPath) !== null && _b !== void 0 ? _b : path.join(__dirname, TAG_MANIFEST_FILENAME);\n let manifestPromise = null;\n async function loadManifest() {\n if (manifestPromise)\n return manifestPromise;\n manifestPromise = (async () => {\n var _a2, _b2, _c, _d;\n const map = /* @__PURE__ */ new Map();\n let raw;\n try {\n raw = await fs.promises.readFile(manifestPath, \"utf-8\");\n } catch (err) {\n if ((err === null || err === void 0 ? void 0 : err.code) !== \"ENOENT\") {\n console.warn(`[cdn-purge] manifest read error ${manifestPath}: ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n }\n return /* @__PURE__ */ new Map();\n }\n let rows;\n try {\n const parsed = JSON.parse(raw);\n rows = Array.isArray(parsed) ? parsed : [];\n } catch (err) {\n console.warn(`[cdn-purge] manifest parse error ${manifestPath}: ${(_b2 = err === null || err === void 0 ? void 0 : err.message) !== null && _b2 !== void 0 ? _b2 : err}`);\n return /* @__PURE__ */ new Map();\n }\n for (const row of rows) {\n const tagPk = (_c = row === null || row === void 0 ? void 0 : row.tag) === null || _c === void 0 ? void 0 : _c.S;\n const pathPk = (_d = row === null || row === void 0 ? void 0 : row.path) === null || _d === void 0 ? void 0 : _d.S;\n if (typeof tagPk !== \"string\" || typeof pathPk !== \"string\")\n continue;\n let tag;\n let p;\n if (pathPrefix) {\n if (!tagPk.startsWith(pathPrefix))\n continue;\n if (!pathPk.startsWith(pathPrefix))\n continue;\n tag = tagPk.slice(pathPrefix.length);\n p = pathPk.slice(pathPrefix.length);\n } else {\n const tIdx = tagPk.indexOf(\"/\");\n const pIdx = pathPk.indexOf(\"/\");\n if (tIdx < 0 || pIdx < 0)\n continue;\n if (tagPk.slice(0, tIdx) !== pathPk.slice(0, pIdx))\n continue;\n tag = tagPk.slice(tIdx + 1);\n p = pathPk.slice(pIdx + 1);\n }\n if (!tag || !p)\n continue;\n let bucket = map.get(tag);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n map.set(tag, bucket);\n }\n bucket.add(p);\n }\n const result = /* @__PURE__ */ new Map();\n let totalEntries = 0;\n for (const [tag, set] of map) {\n result.set(tag, Array.from(set));\n totalEntries += set.size;\n }\n console.log(`[cdn-purge] manifest loaded: buildId=${buildId !== null && buildId !== void 0 ? buildId : \"(auto)\"} tags=${result.size} entries=${totalEntries} (${manifestPath})`);\n return result;\n })();\n return manifestPromise;\n }\n function expandPathsToUrls(paths, hostname) {\n const normalized = /* @__PURE__ */ new Set();\n for (const p of paths) {\n if (!p)\n continue;\n normalized.add(ensureLeadingSlash(p));\n }\n if (normalized.size === 0)\n return [];\n const urls = /* @__PURE__ */ new Set();\n for (const p of normalized) {\n urls.add(`https://${hostname}${p}`);\n if (buildId) {\n const rel = stripLeadingSlash2(p);\n urls.add(`https://${hostname}/_next/data/${buildId}/${rel || \"index\"}.json`);\n }\n }\n return Array.from(urls);\n }\n async function refreshBatch(urls, hostname, siteId) {\n var _a2;\n const body = {\n hostname,\n siteId,\n urls\n };\n let res;\n try {\n res = await (0, gateway_auth_12.gatewayFetch)(cfg, \"/cache/refresh\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n timeoutMs: REFRESH_TIMEOUT_MS\n });\n } catch (err) {\n console.warn(`[cdn-purge] cache/refresh error (${urls.length} urls): ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n return;\n }\n if (!res.ok) {\n let detail = \"\";\n try {\n detail = (await res.text()).slice(0, 200);\n } catch (_b2) {\n }\n console.warn(`[cdn-purge] cache/refresh failed status=${res.status} urls=${urls.length} ${detail}`);\n return;\n }\n console.log(`[cdn-purge] cache/refresh ok: urls=${urls.length}`);\n }\n async function refreshUrls(allUrls, hostname, siteId) {\n if (allUrls.length === 0)\n return;\n const batches = [];\n for (let i = 0; i < allUrls.length; i += URL_BATCH_SIZE) {\n batches.push(allUrls.slice(i, i + URL_BATCH_SIZE));\n }\n let cursor = 0;\n async function worker() {\n while (cursor < batches.length) {\n const idx = cursor++;\n await refreshBatch(batches[idx], hostname, siteId);\n }\n }\n const workers = Array.from({ length: Math.min(REFRESH_CONCURRENCY, batches.length) }, () => worker());\n await Promise.all(workers);\n }\n function resolveTarget(action) {\n const { hostname, siteId } = (0, edge_context_12.getEdgeContext)();\n if (!hostname || siteId === void 0 || siteId === \"\") {\n console.warn(`[cdn-purge] ${action} skip: edge context missing (hostname=${hostname !== null && hostname !== void 0 ? hostname : \"\\u2205\"} siteId=${siteId !== null && siteId !== void 0 ? siteId : \"\\u2205\"}); \\u8981\\u6C42\\u5165\\u7AD9\\u8BF7\\u6C42\\u5E26 host \\u4E0E x-er-origin-site-id`);\n return null;\n }\n return { hostname, siteId };\n }\n async function purgeByPaths(paths) {\n var _a2;\n try {\n const target = resolveTarget(\"purgeByPaths\");\n if (!target)\n return;\n const urls = expandPathsToUrls(paths, target.hostname);\n console.log(`[cdn-purge] purgeByPaths: input=${paths.length} urls=${urls.length}`);\n await refreshUrls(urls, target.hostname, target.siteId);\n } catch (err) {\n console.warn(`[cdn-purge] purgeByPaths error: ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n }\n }\n async function purgeByTags(tags) {\n var _a2;\n try {\n const uniqueTags = Array.from(new Set(tags.map((t) => typeof t === \"string\" ? t : \"\").map((t) => t.trim()).filter(Boolean)));\n if (uniqueTags.length === 0)\n return;\n const target = resolveTarget(\"purgeByTags\");\n if (!target)\n return;\n const map = await loadManifest();\n const merged = /* @__PURE__ */ new Set();\n for (const t of uniqueTags) {\n const paths = map.get(t);\n if (!paths)\n continue;\n for (const p of paths)\n merged.add(p);\n }\n if (merged.size === 0) {\n console.log(`[cdn-purge] purgeByTags: input=${uniqueTags.length} matched=0 (manifest miss, skip)`);\n return;\n }\n const urls = expandPathsToUrls(Array.from(merged), target.hostname);\n console.log(`[cdn-purge] purgeByTags: input=${uniqueTags.length} matched=${merged.size} urls=${urls.length}`);\n await refreshUrls(urls, target.hostname, target.siteId);\n } catch (err) {\n console.warn(`[cdn-purge] purgeByTags error: ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n }\n }\n return { purgeByPaths, purgeByTags };\n }\n exports2.createCdnPurgeClient = createCdnPurgeClient;\n }\n});\n\n// dist/overrides/tagCache/gateway.js\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar gateway_auth_1 = require_gateway_auth();\nvar edge_context_1 = require_edge_context();\nvar cdn_purge_1 = require_cdn_purge();\nvar QUERY_TIMEOUT = 3e3;\nvar WRITE_TIMEOUT = 5e3;\nvar BATCH_SIZE = 200;\nvar PURGE_TIMEOUT = 15e3;\nvar MAX_BATCH_GET_TAGS = 100;\nfunction stripLeadingSlash(s) {\n return s.replace(/^\\/+/, \"\");\n}\nvar GatewayTagCache = class {\n constructor() {\n this.name = \"gateway-tag-cache\";\n this.mode = \"nextMode\";\n this.config = null;\n this.configLoaded = false;\n this.cdnPurgeClient = void 0;\n }\n getConfig() {\n if (!this.configLoaded) {\n this.config = (0, gateway_auth_1.loadGatewayAuthConfig)();\n this.configLoaded = true;\n }\n return this.config;\n }\n /**\n * 拼 TableStore tag 主键:`{version}/{tag}`。\n * version 来自 ESA_CACHE_GW_VERSION,与 OSS Cache Key 使用同一版本维度。\n */\n buildTagKey(config, tag) {\n return `${config.version}/${stripLeadingSlash(tag)}`;\n }\n async getLastRevalidated(tags) {\n const config = this.getConfig();\n if (!config)\n return 0;\n try {\n const rows = await this.batchGetTags(config, tags);\n const now = Date.now();\n let maxRevalidatedAt = 0;\n for (const row of rows) {\n if (row.revalidatedAt !== void 0 && row.revalidatedAt <= now && row.revalidatedAt > maxRevalidatedAt) {\n maxRevalidatedAt = row.revalidatedAt;\n }\n }\n return maxRevalidatedAt;\n } catch (err) {\n console.warn(`[tagCache] getLastRevalidated error: ${err.message}`);\n return 0;\n }\n }\n async hasBeenRevalidated(tags, lastModified) {\n var _a, _b;\n const config = this.getConfig();\n if (!config)\n return false;\n if (tags.length === 0)\n return false;\n try {\n const rows = await this.batchGetTags(config, tags);\n const now = Date.now();\n const lm = lastModified !== null && lastModified !== void 0 ? lastModified : 0;\n for (const row of rows) {\n const eventAt = (_b = (_a = row.revalidatedAt) !== null && _a !== void 0 ? _a : row.stale) !== null && _b !== void 0 ? _b : 0;\n const eventAffectsEntry = eventAt > lm && eventAt <= now;\n if (row.expire !== void 0) {\n if (row.expire <= now && row.expire > lm && eventAffectsEntry) {\n return true;\n }\n continue;\n }\n if (row.stale !== void 0)\n continue;\n if (eventAffectsEntry) {\n return true;\n }\n }\n return false;\n } catch (err) {\n console.warn(`[tagCache] hasBeenRevalidated error: ${err.message}`);\n return false;\n }\n }\n async isStale(tags, lastModified) {\n var _a;\n const config = this.getConfig();\n if (!config)\n return false;\n if (tags.length === 0)\n return false;\n try {\n const rows = await this.batchGetTags(config, tags);\n const lm = lastModified !== null && lastModified !== void 0 ? lastModified : 0;\n const now = Date.now();\n for (const row of rows) {\n if (row.stale === void 0)\n continue;\n const eventAt = (_a = row.revalidatedAt) !== null && _a !== void 0 ? _a : row.stale;\n const eventAffectsEntry = eventAt > lm && eventAt <= now;\n const hasBecomeStale = row.stale <= now;\n const hasNotExpired = row.expire === void 0 || row.expire > now;\n if (eventAffectsEntry && row.stale >= lm && hasBecomeStale && hasNotExpired) {\n return true;\n }\n }\n return false;\n } catch (err) {\n console.warn(`[tagCache] isStale error: ${err.message}`);\n return false;\n }\n }\n async writeTags(tags) {\n if (!tags || tags.length === 0)\n return;\n const config = this.getConfig();\n if (!config)\n return;\n const writeTs = Date.now();\n const rows = tags.map((input) => {\n const tagStr = typeof input === \"string\" ? input : input.tag;\n const stale = typeof input === \"string\" ? void 0 : input.stale;\n const expire = typeof input === \"string\" ? void 0 : input.expire;\n const tagKey = this.buildTagKey(config, tagStr);\n const revalidatedAt = stale !== null && stale !== void 0 ? stale : writeTs;\n const staleStr = stale === void 0 ? \"\\u2205\" : String(stale);\n const expireStr = expire === void 0 ? \"\\u2205\" : String(expire);\n console.log(`[tagCache] writeTags: tag=\"${tagStr}\" key=\"${tagKey}\" revalidatedAt=${revalidatedAt} stale=${staleStr} expire=${expireStr}`);\n const columns = [\n { name: \"revalidatedAt\", value: revalidatedAt }\n ];\n if (stale !== void 0) {\n columns.push({ name: \"stale\", value: stale });\n }\n if (expire !== void 0) {\n columns.push({ name: \"expire\", value: expire });\n }\n return {\n primaryKey: [\n { name: \"app_id\", value: `${config.aliuid}/${config.routinename}` },\n { name: \"tag\", value: tagKey }\n ],\n columns\n };\n });\n await this.batchWrite(config, rows);\n const tagStrs = tags.map((t) => typeof t === \"string\" ? t : t.tag).filter((s) => typeof s === \"string\" && s.length > 0);\n if (tagStrs.length > 0) {\n this.firePurge(config, tagStrs);\n }\n }\n // ---- private methods ----\n async batchGetTags(config, tags) {\n var _a, _b;\n if (tags.length > MAX_BATCH_GET_TAGS) {\n throw new Error(`too many tags in one query: ${tags.length} > ${MAX_BATCH_GET_TAGS} (TableStore BatchGetRow limit)`);\n }\n const tagKeys = tags.map((tag) => this.buildTagKey(config, tag));\n console.log(`[tagCache] batchGetTags: tags=${JSON.stringify(tags)} keys=${JSON.stringify(tagKeys)}`);\n const primaryKeys = tags.map((tag) => [\n { name: \"app_id\", value: `${config.aliuid}/${config.routinename}` },\n { name: \"tag\", value: this.buildTagKey(config, tag) }\n ]);\n const res = await (0, gateway_auth_1.gatewayFetch)(config, \"/table/batch-get-row\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ primaryKeys }),\n timeoutMs: QUERY_TIMEOUT\n });\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[tagCache] batch-get-row rejected (${res.status})`);\n } else {\n console.warn(`[tagCache] batch-get-row failed: status=${res.status}`);\n }\n return [];\n }\n const data = await res.json();\n console.log(`[tagCache] batch-get-row ok: tags=${tags.length} rows=${(_b = (_a = data.rows) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0}`);\n if (!data.rows)\n return [];\n return data.rows.map((row) => {\n var _a2;\n const result = {};\n for (const col of (_a2 = row.columns) !== null && _a2 !== void 0 ? _a2 : []) {\n if (col.name === \"revalidatedAt\" && typeof col.value === \"number\") {\n result.revalidatedAt = col.value;\n } else if (col.name === \"stale\" && typeof col.value === \"number\") {\n result.stale = col.value;\n } else if (col.name === \"expire\" && typeof col.value === \"number\") {\n result.expire = col.value;\n }\n }\n return result;\n });\n }\n async batchWrite(config, rows) {\n if (rows.length === 0)\n return;\n for (let i = 0; i < rows.length; i += BATCH_SIZE) {\n const batch = rows.slice(i, i + BATCH_SIZE);\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, \"/table/batch-write\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ rows: batch }),\n timeoutMs: WRITE_TIMEOUT\n });\n if (res.status === 401 || res.status === 403) {\n console.error(`[tagCache] batch-write rejected (${res.status})`);\n return;\n }\n if (!res.ok) {\n console.warn(`[tagCache] batch-write failed: status=${res.status}`);\n } else {\n console.log(`[tagCache] batch-write ok: rows=${batch.length}`);\n }\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[tagCache] batch-write timeout (${WRITE_TIMEOUT}ms)`);\n } else {\n console.warn(`[tagCache] batch-write error: ${err.message}`);\n }\n }\n }\n }\n /**\n * 懒加载 cdn-purge 客户端。返回 null 表示环境变量缺失,降级跳过 purge。\n */\n getCdnPurgeClient() {\n if (this.cdnPurgeClient !== void 0)\n return this.cdnPurgeClient;\n const cfg = (0, cdn_purge_1.loadCdnPurgeConfig)();\n this.cdnPurgeClient = cfg ? (0, cdn_purge_1.createCdnPurgeClient)(cfg) : null;\n return this.cdnPurgeClient;\n }\n /**\n * 根据 PCG_CDN_PURGE_MODE 环境变量选择 purge 策略。\n * - \"path\"(默认):走 manifest 反查 tag→path,按 URL 级别刷新\n * - \"tag\":直接发 cacheTags 数组,由 ESA 原生按 Cache-Tag 刷新\n */\n firePurge(config, tagStrs) {\n const mode = (process.env.PCG_CDN_PURGE_MODE || \"path\").toLowerCase();\n if (mode === \"tag\") {\n this.purgeByCacheTags(config, tagStrs).catch((err) => {\n var _a;\n console.warn(`[tagCache] cacheTags purge failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n });\n } else {\n const purgeClient = this.getCdnPurgeClient();\n if (purgeClient) {\n purgeClient.purgeByTags(tagStrs).catch((err) => {\n var _a;\n console.warn(`[tagCache] path purge failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n });\n }\n }\n }\n /**\n * 调 Gateway /cache/refresh(cacheTags) 触发 ESA PurgeCaches Type=cachetag。\n * hostname / siteId 从当前请求的 edge context 读取,缺失则 skip。\n */\n async purgeByCacheTags(config, tags) {\n var _a;\n const { hostname, siteId } = (0, edge_context_1.getEdgeContext)();\n if (!hostname || siteId === void 0 || siteId === \"\") {\n console.warn(`[tagCache] cacheTags purge skip: edge context missing (hostname=${hostname !== null && hostname !== void 0 ? hostname : \"\\u2205\"} siteId=${siteId !== null && siteId !== void 0 ? siteId : \"\\u2205\"})`);\n return;\n }\n const body = { hostname, siteId, cacheTags: tags };\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, \"/cache/refresh\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n timeoutMs: PURGE_TIMEOUT\n });\n if (!res.ok) {\n let detail = \"\";\n try {\n detail = (await res.text()).slice(0, 200);\n } catch (_b) {\n }\n console.warn(`[tagCache] cacheTags purge failed: status=${res.status} tags=${tags.length} ${detail}`);\n return;\n }\n console.log(`[tagCache] cacheTags purge ok: tags=${tags.length}`);\n } catch (err) {\n console.warn(`[tagCache] cacheTags purge error: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n }\n }\n};\nexports.default = GatewayTagCache;\n",
|
|
3
|
+
"runtime/efc-observability.cjs": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\n\n// dist/runtime/debug-network-log.cjs\nvar require_debug_network_log = __commonJS({\n \"dist/runtime/debug-network-log.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var fs = require(\"node:fs\");\n var { Console: Console2 } = require(\"node:console\");\n var KEY2 = Symbol.for(\"pcg.debug.network-log\");\n var state2 = globalThis[KEY2] || (globalThis[KEY2] = { pending: 0, warned: false, details: /* @__PURE__ */ new WeakMap() });\n function warn(reason) {\n if (state2.warned)\n return;\n state2.warned = true;\n try {\n new Console2({ stdout: process.stderr, ignoreErrors: true }).warn(`[pcg debug network] ${reason}`);\n } catch (_a) {\n }\n }\n function debugHeaders(headers) {\n return Object.fromEntries(Array.from(new Headers(headers), ([name, value]) => [\n name,\n /authorization|cookie|key|token|secret|password|signature|credential|session/i.test(name) ? \"[REDACTED]\" : value\n ]));\n }\n function errorDetails(error) {\n return {\n name: error === null || error === void 0 ? void 0 : error.name,\n message: String((error === null || error === void 0 ? void 0 : error.message) || error).slice(0, 2048),\n code: error === null || error === void 0 ? void 0 : error.code\n };\n }\n function capture(record, update) {\n try {\n const details = state2.details.get(record) || {};\n update(details);\n state2.details.set(record, details);\n } catch (_a) {\n warn(\"unable to capture local request details\");\n }\n }\n var debugNetwork2 = {\n enabled: true,\n request(record, url, init) {\n capture(record, (details) => {\n let host = null;\n try {\n host = new URL(url).host;\n } catch (_a) {\n }\n details.request = {\n host,\n method: init.method || \"GET\",\n headers: debugHeaders(init.headers)\n };\n });\n },\n response(record, response) {\n capture(record, (details) => {\n details.response = { status: response.status, headers: debugHeaders(response.headers) };\n });\n },\n error(record, error) {\n capture(record, (details) => {\n details.error = errorDetails(error);\n if (error === null || error === void 0 ? void 0 : error.cause)\n details.error.cause = errorDetails(error.cause);\n });\n }\n };\n function withDebugDetails(body, records) {\n if (!records)\n return body;\n const debug = {};\n let bytes = body.length + 32;\n for (const [i, record] of records.entries()) {\n const details = state2.details.get(record);\n if (!details)\n continue;\n const key = `gw${i + 1}`;\n bytes += Buffer.byteLength(JSON.stringify(details)) + key.length + 4;\n if (bytes > 64 * 1024) {\n debug.truncated = true;\n break;\n }\n debug[key] = details;\n }\n return Buffer.from(JSON.stringify({ ...JSON.parse(body.toString(\"utf8\")), debug }));\n }\n function writeDebugNetworkLog2(body, onSettled, records) {\n if (state2.pending >= 64) {\n warn(\"local log queue full; skipping debug copy\");\n return;\n }\n state2.pending++;\n const done = (error) => {\n state2.pending--;\n if (error)\n warn(`local log write failed (${error.code || \"unknown\"})`);\n try {\n onSettled();\n } catch (_a) {\n warn(\"local log completion failed\");\n }\n };\n try {\n fs.appendFile(process.env.PCG_DEBUG_NETWORK_LOG_PATH || \"/tmp/pcg-gateway-network.ndjson\", Buffer.concat([withDebugDetails(body, records), Buffer.from(\"\\n\")]), { mode: 384 }, done);\n } catch (error) {\n done(error);\n }\n }\n module2.exports = {\n debugNetwork: debugNetwork2,\n writeDebugNetworkLog: writeDebugNetworkLog2,\n hasPendingDebugNetworkLogs: () => state2.pending > 0\n };\n }\n});\n\n// dist/runtime/efc-observability.cjs\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar { AsyncLocalStorage } = require(\"node:async_hooks\");\nvar diagnostics = require(\"node:diagnostics_channel\");\nvar http = require(\"node:http\");\nvar { randomUUID } = require(\"node:crypto\");\nvar { performance } = require(\"node:perf_hooks\");\nvar { Console } = require(\"node:console\");\nvar { debugNetwork, writeDebugNetworkLog, hasPendingDebugNetworkLogs } = require_debug_network_log();\nvar KEY = Symbol.for(\"pcg.efc.observability\");\nvar state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n});\nvar LOG_LIMIT = 32 * 1024;\nvar BODY_LIMIT = 64 * 1024;\nvar DEADLINE_MS = 5e3;\nvar diagnosticConsole;\nfunction warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n}\nfunction safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n}\nfunction validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n}\nfunction validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n}\nfunction traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n}\nfunction safePath(value) {\n const path = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n}\nfunction notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n if (hasPendingDebugNetworkLogs())\n return;\n for (const done of state.waiters)\n done(true);\n}\nfunction drop(reason) {\n state.counts.dropped++;\n warning(reason);\n}\nfunction rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n}\nfunction snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n writeDebugNetworkLog(body, notify, ctx.records);\n if (!ctx.report)\n return;\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n}\nfunction finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n}\nfunction closeRoot(ctx) {\n if (ctx.closed || !ctx.collect)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n}\nfunction complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n}\nfunction responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n}\nfunction installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request, error }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call) {\n debugNetwork.error(call.record, error);\n complete(call);\n }\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]) || randomUUID().replace(/-/g, \"\");\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n const collect = report || debugNetwork.enabled;\n ctx = {\n trace,\n metadata,\n report,\n collect,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!collect) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path = safePath(req.url);\n if (validText(path, 2048))\n metadata.path = path;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n ctx.collect = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http.Server.prototype.emit === observedEmit)\n http.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n}\nasync function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n ensureGatewayTrace(init.headers);\n if (!ctx || !ctx.collect || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n debugNetwork.request(call.record, url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n debugNetwork.response(call.record, response);\n return response;\n } catch (error) {\n safe(() => complete(call));\n debugNetwork.error(call.record, error);\n throw error;\n }\n}\nfunction markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n}\nfunction send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n}\nfunction pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n}\nfunction flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n}\nfunction getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n}\nfunction getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n}\nfunction ensureGatewayTrace(headers) {\n const trace = traceId(getEfcTraceId()) || traceId(headers.get(\"eagleeye-traceid\")) || randomUUID().replace(/-/g, \"\");\n headers.set(\"eagleeye-traceid\", trace);\n return trace;\n}\nstate.observeGatewayFetch = observeGatewayFetch;\nstate.flushFunctionLogs = flushFunctionLogs;\nstate.getEfcTraceId = getEfcTraceId;\nstate.ensureGatewayTrace = ensureGatewayTrace;\nmodule.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId,\n ensureGatewayTrace\n};\n",
|
|
4
|
+
"adapters/wrappers/node-server.js": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod2) => function __require() {\n return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;\n};\n\n// dist/adapters/converters/node-request.js\nvar require_node_request = __commonJS({\n \"dist/adapters/converters/node-request.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.convertNodeRequest = void 0;\n function firstHeaderValue(value) {\n var _a;\n const raw = Array.isArray(value) ? value.join(\",\") : value;\n const first = (_a = raw === null || raw === void 0 ? void 0 : raw.split(\",\")[0]) === null || _a === void 0 ? void 0 : _a.trim();\n return first || void 0;\n }\n async function convertNodeRequest(req, converter) {\n var _a, _b, _c;\n const protocol = (_a = firstHeaderValue(req.headers[\"x-forwarded-proto\"])) !== null && _a !== void 0 ? _a : \"http\";\n req.protocol = protocol;\n let rejectRequest;\n const requestFailed = new Promise((_, reject) => {\n rejectRequest = reject;\n });\n const onError = (error) => rejectRequest(error);\n const onAborted = () => rejectRequest(new Error(\"Request aborted\"));\n req.once(\"error\", onError);\n req.once(\"aborted\", onAborted);\n let converted;\n try {\n converted = await Promise.race([\n converter.convertFrom(req),\n requestFailed\n ]);\n } finally {\n req.removeListener(\"error\", onError);\n req.removeListener(\"aborted\", onAborted);\n }\n const rawUrl = req.url || \"/\";\n const host = converted.headers.host || `localhost:${(_b = process.env.PORT) !== null && _b !== void 0 ? _b : \"3000\"}`;\n const absoluteUrl = new URL(`${protocol}://${host}${rawUrl}`);\n const remoteAddress = firstHeaderValue(converted.headers[\"x-forwarded-for\"]) || converted.headers[\"x-real-ip\"] || ((_c = req.socket) === null || _c === void 0 ? void 0 : _c.remoteAddress) || \"127.0.0.1\";\n return {\n ...converted,\n rawPath: absoluteUrl.pathname,\n url: absoluteUrl.href,\n remoteAddress\n };\n }\n exports2.convertNodeRequest = convertNodeRequest;\n }\n});\n\n// dist/runtime/debug-network-log.cjs\nvar require_debug_network_log = __commonJS({\n \"dist/runtime/debug-network-log.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var fs3 = require(\"node:fs\");\n var { Console } = require(\"node:console\");\n var KEY = Symbol.for(\"pcg.debug.network-log\");\n var state = globalThis[KEY] || (globalThis[KEY] = { pending: 0, warned: false, details: /* @__PURE__ */ new WeakMap() });\n function warn(reason) {\n if (state.warned)\n return;\n state.warned = true;\n try {\n new Console({ stdout: process.stderr, ignoreErrors: true }).warn(`[pcg debug network] ${reason}`);\n } catch (_a) {\n }\n }\n function debugHeaders(headers) {\n return Object.fromEntries(Array.from(new Headers(headers), ([name, value]) => [\n name,\n /authorization|cookie|key|token|secret|password|signature|credential|session/i.test(name) ? \"[REDACTED]\" : value\n ]));\n }\n function errorDetails(error) {\n return {\n name: error === null || error === void 0 ? void 0 : error.name,\n message: String((error === null || error === void 0 ? void 0 : error.message) || error).slice(0, 2048),\n code: error === null || error === void 0 ? void 0 : error.code\n };\n }\n function capture(record, update) {\n try {\n const details = state.details.get(record) || {};\n update(details);\n state.details.set(record, details);\n } catch (_a) {\n warn(\"unable to capture local request details\");\n }\n }\n var debugNetwork = {\n enabled: true,\n request(record, url, init) {\n capture(record, (details) => {\n let host = null;\n try {\n host = new URL(url).host;\n } catch (_a) {\n }\n details.request = {\n host,\n method: init.method || \"GET\",\n headers: debugHeaders(init.headers)\n };\n });\n },\n response(record, response) {\n capture(record, (details) => {\n details.response = { status: response.status, headers: debugHeaders(response.headers) };\n });\n },\n error(record, error) {\n capture(record, (details) => {\n details.error = errorDetails(error);\n if (error === null || error === void 0 ? void 0 : error.cause)\n details.error.cause = errorDetails(error.cause);\n });\n }\n };\n function withDebugDetails(body, records) {\n if (!records)\n return body;\n const debug = {};\n let bytes = body.length + 32;\n for (const [i, record] of records.entries()) {\n const details = state.details.get(record);\n if (!details)\n continue;\n const key = `gw${i + 1}`;\n bytes += Buffer.byteLength(JSON.stringify(details)) + key.length + 4;\n if (bytes > 64 * 1024) {\n debug.truncated = true;\n break;\n }\n debug[key] = details;\n }\n return Buffer.from(JSON.stringify({ ...JSON.parse(body.toString(\"utf8\")), debug }));\n }\n function writeDebugNetworkLog(body, onSettled, records) {\n if (state.pending >= 64) {\n warn(\"local log queue full; skipping debug copy\");\n return;\n }\n state.pending++;\n const done = (error) => {\n state.pending--;\n if (error)\n warn(`local log write failed (${error.code || \"unknown\"})`);\n try {\n onSettled();\n } catch (_a) {\n warn(\"local log completion failed\");\n }\n };\n try {\n fs3.appendFile(process.env.PCG_DEBUG_NETWORK_LOG_PATH || \"/tmp/pcg-gateway-network.ndjson\", Buffer.concat([withDebugDetails(body, records), Buffer.from(\"\\n\")]), { mode: 384 }, done);\n } catch (error) {\n done(error);\n }\n }\n module2.exports = {\n debugNetwork,\n writeDebugNetworkLog,\n hasPendingDebugNetworkLogs: () => state.pending > 0\n };\n }\n});\n\n// dist/runtime/efc-observability.cjs\nvar require_efc_observability = __commonJS({\n \"dist/runtime/efc-observability.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var { AsyncLocalStorage } = require(\"node:async_hooks\");\n var diagnostics = require(\"node:diagnostics_channel\");\n var http2 = require(\"node:http\");\n var { randomUUID } = require(\"node:crypto\");\n var { performance } = require(\"node:perf_hooks\");\n var { Console } = require(\"node:console\");\n var { debugNetwork, writeDebugNetworkLog, hasPendingDebugNetworkLogs } = require_debug_network_log();\n var KEY = Symbol.for(\"pcg.efc.observability\");\n var state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n });\n var LOG_LIMIT = 32 * 1024;\n var BODY_LIMIT = 64 * 1024;\n var DEADLINE_MS = 5e3;\n var diagnosticConsole;\n function warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n }\n function safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n }\n function validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n }\n function validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n }\n function traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n }\n function safePath(value) {\n const path3 = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path3.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n }\n function notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n if (hasPendingDebugNetworkLogs())\n return;\n for (const done of state.waiters)\n done(true);\n }\n function drop(reason) {\n state.counts.dropped++;\n warning(reason);\n }\n function rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n }\n function snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n writeDebugNetworkLog(body, notify, ctx.records);\n if (!ctx.report)\n return;\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n }\n function finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n }\n function closeRoot(ctx) {\n if (ctx.closed || !ctx.collect)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n }\n function complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n }\n function responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n }\n function installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http2.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request, error }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call) {\n debugNetwork.error(call.record, error);\n complete(call);\n }\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]) || randomUUID().replace(/-/g, \"\");\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n const collect = report || debugNetwork.enabled;\n ctx = {\n trace,\n metadata,\n report,\n collect,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!collect) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path3 = safePath(req.url);\n if (validText(path3, 2048))\n metadata.path = path3;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n ctx.collect = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http2.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http2.Server.prototype.emit === observedEmit)\n http2.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n }\n async function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n ensureGatewayTrace(init.headers);\n if (!ctx || !ctx.collect || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n debugNetwork.request(call.record, url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n debugNetwork.response(call.record, response);\n return response;\n } catch (error) {\n safe(() => complete(call));\n debugNetwork.error(call.record, error);\n throw error;\n }\n }\n function markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n }\n function send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http2.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n }\n function pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n }\n function flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n }\n function getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n }\n function getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n }\n function ensureGatewayTrace(headers) {\n const trace = traceId(getEfcTraceId()) || traceId(headers.get(\"eagleeye-traceid\")) || randomUUID().replace(/-/g, \"\");\n headers.set(\"eagleeye-traceid\", trace);\n return trace;\n }\n state.observeGatewayFetch = observeGatewayFetch;\n state.flushFunctionLogs = flushFunctionLogs;\n state.getEfcTraceId = getEfcTraceId;\n state.ensureGatewayTrace = ensureGatewayTrace;\n module2.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId,\n ensureGatewayTrace\n };\n }\n});\n\n// dist/runtime/gateway-auth.js\nvar require_gateway_auth = __commonJS({\n \"dist/runtime/gateway-auth.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.gatewayFetch = exports2.signGatewayHeaders = exports2.loadGatewayAuthConfig = void 0;\n var crypto_1 = require(\"crypto\");\n var efc_observability_cjs_12 = require_efc_observability();\n var DEFAULT_TTL_MS = 5 * 60 * 1e3;\n var DEFAULT_TIMEOUT_MS = 5e3;\n function _fetch(input, init) {\n var _a, _b;\n const gatewayGlobalFetch = globalThis.fetch;\n const fn = gatewayGlobalFetch.__nextPatched ? (_b = (_a = gatewayGlobalFetch._nextOriginalFetch) !== null && _a !== void 0 ? _a : globalThis.__originalFetch) !== null && _b !== void 0 ? _b : gatewayGlobalFetch : gatewayGlobalFetch;\n return fn(input, init);\n }\n function loadGatewayAuthConfig() {\n const gatewayUrl = process.env.ESA_CACHE_GW_GATEWAY_ENDPOINT;\n const authKey = process.env.ESA_CACHE_GW_AUTH_KEY;\n const aliuid = process.env.ESA_CACHE_GW_ALIUID;\n const routinename = process.env.ESA_CACHE_GW_FUNCTIONNAME;\n const version = process.env.ESA_CACHE_GW_VERSION;\n const missing = [];\n if (!gatewayUrl)\n missing.push(\"ESA_CACHE_GW_GATEWAY_ENDPOINT\");\n if (!authKey)\n missing.push(\"ESA_CACHE_GW_AUTH_KEY\");\n if (!aliuid)\n missing.push(\"ESA_CACHE_GW_ALIUID\");\n if (!routinename)\n missing.push(\"ESA_CACHE_GW_FUNCTIONNAME\");\n if (!version)\n missing.push(\"ESA_CACHE_GW_VERSION\");\n if (missing.length > 0) {\n console.error(`[gateway-auth] \\u7F3A\\u5C11\\u5FC5\\u9700\\u7684\\u73AF\\u5883\\u53D8\\u91CF: ${missing.join(\", \")}`);\n return null;\n }\n return {\n gatewayUrl: gatewayUrl.replace(/\\/+$/, \"\"),\n secret: authKey,\n aliuid,\n routinename,\n version\n };\n }\n exports2.loadGatewayAuthConfig = loadGatewayAuthConfig;\n function signGatewayHeaders(cfg, ttlMs = DEFAULT_TTL_MS) {\n const expires = String(Date.now() + ttlMs);\n const md5Hash = (0, crypto_1.createHash)(\"md5\").update(`${cfg.secret}${expires}${cfg.aliuid}${cfg.routinename}${cfg.version}`).digest(\"hex\");\n return {\n authorization: `${expires}-${md5Hash}`,\n aliuid: cfg.aliuid,\n routinename: cfg.routinename,\n version: cfg.version\n };\n }\n exports2.signGatewayHeaders = signGatewayHeaders;\n async function gatewayFetch(cfg, pathOrUrl, init) {\n var _a, _b;\n const url = pathOrUrl.startsWith(\"/\") ? `${cfg.gatewayUrl}${pathOrUrl}` : pathOrUrl;\n const signed = signGatewayHeaders(cfg);\n const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);\n headers.set(\"Authorization\", signed.authorization);\n headers.set(\"AliUid\", signed.aliuid);\n headers.set(\"RoutineName\", signed.routinename);\n headers.set(\"Version\", signed.version);\n (0, efc_observability_cjs_12.ensureGatewayTrace)(headers);\n const timeoutMs = (_a = init === null || init === void 0 ? void 0 : init.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await (0, efc_observability_cjs_12.observeGatewayFetch)(url, {\n ...init,\n headers,\n signal: (_b = init === null || init === void 0 ? void 0 : init.signal) !== null && _b !== void 0 ? _b : controller.signal\n }, _fetch);\n } finally {\n clearTimeout(timer);\n }\n }\n exports2.gatewayFetch = gatewayFetch;\n }\n});\n\n// dist/runtime/image-config.js\nvar require_image_config = __commonJS({\n \"dist/runtime/image-config.js\"(exports, module) {\n \"use strict\";\n var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });\n var __importStar = exports && exports.__importStar || function(mod2) {\n if (mod2 && mod2.__esModule) return mod2;\n var result = {};\n if (mod2 != null) {\n for (var k in mod2) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding(result, mod2, k);\n }\n __setModuleDefault(result, mod2);\n return result;\n };\n Object.defineProperty(exports, \"__esModule\", { value: true });\n exports._setMatcherForTests = exports._resetImageConfigCacheForTests = exports.validateImageUrl = void 0;\n var fs = __importStar(require(\"fs\"));\n var path = __importStar(require(\"path\"));\n var cachedConfig;\n var cachedMatcher;\n var warnedMatcherMissing = false;\n function configFilePath() {\n return path.resolve(process.cwd(), \".next\", \"required-server-files.json\");\n }\n function loadImageConfig() {\n var _a, _b, _c;\n if (cachedConfig !== void 0)\n return cachedConfig;\n const filePath = configFilePath();\n let raw;\n try {\n raw = fs.readFileSync(filePath, \"utf-8\");\n } catch (err) {\n console.warn(`[image-config] required-server-files.json not found at ${filePath} \\u2014 allowing all image URLs (${(_a = err.code) !== null && _a !== void 0 ? _a : err.message})`);\n cachedConfig = { mode: \"config-missing\" };\n return cachedConfig;\n }\n try {\n const parsed = JSON.parse(raw);\n const images = (_c = (_b = parsed === null || parsed === void 0 ? void 0 : parsed.config) === null || _b === void 0 ? void 0 : _b.images) !== null && _c !== void 0 ? _c : {};\n cachedConfig = {\n mode: \"loaded\",\n images: {\n remotePatterns: Array.isArray(images.remotePatterns) ? images.remotePatterns : [],\n domains: Array.isArray(images.domains) ? images.domains : [],\n unoptimized: images.unoptimized === true\n }\n };\n return cachedConfig;\n } catch (err) {\n console.warn(`[image-config] failed to parse ${filePath}: ${err.message} \\u2014 allowing all image URLs`);\n cachedConfig = { mode: \"config-missing\" };\n return cachedConfig;\n }\n }\n function loadMatcher() {\n if (cachedMatcher !== void 0)\n return cachedMatcher;\n try {\n const dynamicRequire = eval(\"require\");\n const mod = dynamicRequire(\"next/dist/shared/lib/match-remote-pattern\");\n const hasRemoteMatch = mod === null || mod === void 0 ? void 0 : mod.hasRemoteMatch;\n if (typeof hasRemoteMatch !== \"function\") {\n throw new Error(\"hasRemoteMatch not exported\");\n }\n cachedMatcher = hasRemoteMatch;\n return cachedMatcher;\n } catch (err) {\n if (!warnedMatcherMissing) {\n warnedMatcherMissing = true;\n console.warn(`[image-config] cannot load next/dist/shared/lib/match-remote-pattern (${err.message}) \\u2014 falling back to deny-external-only mode`);\n }\n cachedMatcher = null;\n return null;\n }\n }\n function validateImageUrl(absoluteUrl, hostHeader) {\n const cfg = loadImageConfig();\n if (cfg.mode === \"config-missing\") {\n return { ok: true, reason: \"config-missing\" };\n }\n const { images } = cfg;\n if (images.unoptimized) {\n return { ok: true, reason: \"unoptimized\" };\n }\n const reqHost = hostHeader.toLowerCase();\n const urlHost = absoluteUrl.host.toLowerCase();\n if (reqHost && reqHost === urlHost) {\n return { ok: true, reason: \"same-origin\" };\n }\n const matcher = loadMatcher();\n if (matcher === null) {\n return { ok: false, reason: \"matcher-unavailable\" };\n }\n if (matcher(images.domains, images.remotePatterns, absoluteUrl)) {\n return { ok: true, reason: \"pattern-match\" };\n }\n return { ok: false, reason: \"remote-pattern-not-matched\" };\n }\n exports.validateImageUrl = validateImageUrl;\n function _resetImageConfigCacheForTests() {\n cachedConfig = void 0;\n cachedMatcher = void 0;\n warnedMatcherMissing = false;\n }\n exports._resetImageConfigCacheForTests = _resetImageConfigCacheForTests;\n function _setMatcherForTests(impl) {\n cachedMatcher = impl;\n }\n exports._setMatcherForTests = _setMatcherForTests;\n }\n});\n\n// dist/runtime/image-proxy.js\nvar require_image_proxy = __commonJS({\n \"dist/runtime/image-proxy.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.handleImageProxy = void 0;\n var stream_1 = require(\"stream\");\n var gateway_auth_1 = require_gateway_auth();\n var image_config_1 = require_image_config();\n var GATEWAY_TIMEOUT_MS = 1e4;\n var PASSTHROUGH_HEADERS = [\n \"content-type\",\n \"content-length\",\n \"cache-control\",\n \"etag\",\n \"vary\",\n \"last-modified\",\n \"content-security-policy\"\n ];\n function isExternalImageUrl(url) {\n return url.startsWith(\"http://\") || url.startsWith(\"https://\");\n }\n function normalizeImageUrl(rawUrl) {\n if (rawUrl.startsWith(\"http://\") || rawUrl.startsWith(\"https://\")) {\n return rawUrl;\n }\n return rawUrl.startsWith(\"/\") ? rawUrl : `/${rawUrl}`;\n }\n function writeJson(res, status, body) {\n res.statusCode = status;\n res.setHeader(\"Content-Type\", \"application/json; charset=utf-8\");\n res.end(JSON.stringify(body));\n }\n async function handleImageProxy(req, res) {\n const reqUrl = req.url || \"\";\n const qIdx = reqUrl.indexOf(\"?\");\n if (qIdx === -1) {\n return writeJson(res, 400, { error: \"Missing query parameters\" });\n }\n const params = new URLSearchParams(reqUrl.slice(qIdx + 1));\n const rawUrl = params.get(\"url\");\n const w = params.get(\"w\");\n const q = params.get(\"q\");\n if (!rawUrl || !w) {\n return writeJson(res, 400, {\n error: \"Missing required parameters: url, w\"\n });\n }\n const imageUrl = normalizeImageUrl(rawUrl);\n if (isExternalImageUrl(imageUrl)) {\n let parsedUrl;\n try {\n parsedUrl = new URL(imageUrl);\n } catch (_a) {\n return writeJson(res, 400, { error: \"Invalid url parameter\" });\n }\n const hostHeader = req.headers[\"host\"] || \"\";\n const verdict = (0, image_config_1.validateImageUrl)(parsedUrl, hostHeader);\n if (!verdict.ok) {\n return writeJson(res, 400, { error: \"url not allowed\" });\n }\n }\n const cfg = (0, gateway_auth_1.loadGatewayAuthConfig)();\n if (!cfg) {\n return writeJson(res, 500, {\n error: \"Gateway auth config missing\"\n });\n }\n const upstreamParams = new URLSearchParams({ url: imageUrl, w });\n if (q)\n upstreamParams.set(\"q\", q);\n const upstreamPath = `/image/optimize?${upstreamParams}`;\n const ifNoneMatch = req.headers[\"if-none-match\"];\n const upstreamHeaders = {};\n if (typeof ifNoneMatch === \"string\") {\n upstreamHeaders[\"if-none-match\"] = ifNoneMatch;\n }\n const accept = req.headers[\"accept\"];\n if (typeof accept === \"string\") {\n upstreamHeaders[\"accept\"] = accept;\n }\n let upstream;\n try {\n upstream = await (0, gateway_auth_1.gatewayFetch)(cfg, upstreamPath, {\n method: \"GET\",\n headers: upstreamHeaders,\n timeoutMs: GATEWAY_TIMEOUT_MS\n });\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[image-proxy] Gateway timeout after ${GATEWAY_TIMEOUT_MS}ms: ${imageUrl}`);\n return writeJson(res, 504, { error: \"Upstream timeout\" });\n }\n console.warn(`[image-proxy] Gateway fetch error: ${err.message} (url=${imageUrl})`);\n return writeJson(res, 502, { error: \"Bad gateway\" });\n }\n res.statusCode = upstream.status;\n for (const name of PASSTHROUGH_HEADERS) {\n const value = upstream.headers.get(name);\n if (value !== null) {\n res.setHeader(name, value);\n }\n }\n if (upstream.status === 304 || !upstream.body) {\n res.end();\n return;\n }\n try {\n const nodeStream = stream_1.Readable.fromWeb(upstream.body);\n nodeStream.on(\"error\", (err) => {\n console.warn(`[image-proxy] Stream error: ${err.message}`);\n if (!res.writableEnded)\n res.end();\n });\n nodeStream.pipe(res);\n } catch (err) {\n console.warn(`[image-proxy] Pipe setup failed: ${err.message}`);\n if (!res.headersSent) {\n writeJson(res, 502, { error: \"Stream setup failed\" });\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n }\n exports2.handleImageProxy = handleImageProxy;\n }\n});\n\n// dist/runtime/edge-context.js\nvar require_edge_context = __commonJS({\n \"dist/runtime/edge-context.js\"(exports2) {\n \"use strict\";\n var _a;\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.getCacheTags = exports2.setCacheTags = exports2.getEdgeContext = exports2.runWithEdgeContext = exports2.buildEdgeContextFromHeaders = void 0;\n var node_async_hooks_1 = require(\"node:async_hooks\");\n var ALS_KEY = Symbol.for(\"pcg.edgeContext.als\");\n var globalRef = globalThis;\n var storage = (_a = globalRef[ALS_KEY]) !== null && _a !== void 0 ? _a : globalRef[ALS_KEY] = new node_async_hooks_1.AsyncLocalStorage();\n var SITE_ID_HEADER = \"x-er-origin-site-id\";\n var HOSTNAME_HEADER = \"host\";\n var FORWARDED_HOSTNAME_HEADER = \"x-forwarded-host\";\n function pickHeader(headers, name) {\n var _a2;\n return (_a2 = headers[name]) !== null && _a2 !== void 0 ? _a2 : headers[name.toLowerCase()];\n }\n function parseHostname(raw) {\n var _a2;\n if (!raw)\n return void 0;\n const first = (_a2 = raw.split(\",\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\n return first || void 0;\n }\n function parseSiteId(raw) {\n if (!raw)\n return void 0;\n const trimmed = raw.trim();\n if (!trimmed)\n return void 0;\n const n = Number(trimmed);\n return Number.isFinite(n) && trimmed === String(n) ? n : trimmed;\n }\n function buildEdgeContextFromHeaders(headers) {\n var _a2;\n const ctx = {};\n const siteId = parseSiteId(pickHeader(headers, SITE_ID_HEADER));\n if (siteId !== void 0)\n ctx.siteId = siteId;\n const hostname = (_a2 = parseHostname(pickHeader(headers, HOSTNAME_HEADER))) !== null && _a2 !== void 0 ? _a2 : parseHostname(pickHeader(headers, FORWARDED_HOSTNAME_HEADER));\n if (hostname)\n ctx.hostname = hostname;\n return ctx;\n }\n exports2.buildEdgeContextFromHeaders = buildEdgeContextFromHeaders;\n function runWithEdgeContext(headers, fn) {\n const ctx = buildEdgeContextFromHeaders(headers);\n return storage.run(ctx, fn);\n }\n exports2.runWithEdgeContext = runWithEdgeContext;\n function getEdgeContext() {\n var _a2;\n return (_a2 = storage.getStore()) !== null && _a2 !== void 0 ? _a2 : {};\n }\n exports2.getEdgeContext = getEdgeContext;\n function setCacheTags(tags) {\n const store = storage.getStore();\n if (store)\n store.cacheTags = tags;\n }\n exports2.setCacheTags = setCacheTags;\n function getCacheTags() {\n var _a2;\n return (_a2 = storage.getStore()) === null || _a2 === void 0 ? void 0 : _a2.cacheTags;\n }\n exports2.getCacheTags = getCacheTags;\n }\n});\n\n// dist/adapters/wrappers/node-server.js\nvar __createBinding2 = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault2 = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar2 = exports && exports.__importStar || function(mod2) {\n if (mod2 && mod2.__esModule) return mod2;\n var result = {};\n if (mod2 != null) {\n for (var k in mod2) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod2, k)) __createBinding2(result, mod2, k);\n }\n __setModuleDefault2(result, mod2);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.bridgeOpenNextHandler = void 0;\nvar http = __importStar2(require(\"http\"));\nvar fs2 = __importStar2(require(\"fs\"));\nvar path2 = __importStar2(require(\"path\"));\nvar node_request_1 = require_node_request();\nvar image_proxy_1 = require_image_proxy();\nvar edge_context_1 = require_edge_context();\nvar efc_observability_cjs_1 = require_efc_observability();\nvar PCG_DEFAULT_LOG_FILE = \"/tmp/pcg.log\";\nfunction setupFileLogger() {\n const logFile = process.env.PCG_LOG_FILE || PCG_DEFAULT_LOG_FILE;\n const logDir = path2.dirname(logFile);\n try {\n fs2.mkdirSync(logDir, { recursive: true });\n } catch (_a) {\n }\n let stream;\n try {\n stream = fs2.createWriteStream(logFile, { flags: \"a\" });\n stream.on(\"error\", () => {\n stream = void 0;\n });\n } catch (_b) {\n }\n const timestamp = () => {\n const d = /* @__PURE__ */ new Date();\n return d.toISOString().replace(\"T\", \" \").replace(\"Z\", \"\");\n };\n const origLog = console.log.bind(console);\n const origError = console.error.bind(console);\n const origWarn = console.warn.bind(console);\n const writeToFile = (level, args) => {\n if (!stream)\n return;\n try {\n const msg = args.map((a) => typeof a === \"string\" ? a : JSON.stringify(a, null, 2)).join(\" \");\n stream.write(`${timestamp()} [${level}] ${msg}\n`);\n } catch (_a) {\n }\n };\n console.log = (...args) => {\n origLog(...args);\n writeToFile(\"INFO\", args);\n };\n console.error = (...args) => {\n origError(...args);\n writeToFile(\"ERROR\", args);\n };\n console.warn = (...args) => {\n origWarn(...args);\n writeToFile(\"WARN\", args);\n };\n process.on(\"uncaughtException\", (err) => {\n writeToFile(\"FATAL\", [`Uncaught Exception: ${err.stack || err.message}`]);\n if (!stream) {\n origError(err);\n process.exit(1);\n return;\n }\n stream.end(() => process.exit(1));\n setTimeout(() => process.exit(1), 1e3).unref();\n });\n process.on(\"unhandledRejection\", (reason) => {\n writeToFile(\"ERROR\", [`Unhandled Rejection: ${reason}`]);\n });\n}\nsetupFileLogger();\n(0, efc_observability_cjs_1.installEfcObservability)();\nvar MIME_TYPES = {\n \".js\": \"application/javascript\",\n \".mjs\": \"application/javascript\",\n \".css\": \"text/css\",\n \".html\": \"text/html\",\n \".json\": \"application/json\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".svg\": \"image/svg+xml\",\n \".ico\": \"image/x-icon\",\n \".woff\": \"font/woff\",\n \".woff2\": \"font/woff2\",\n \".ttf\": \"font/ttf\",\n \".map\": \"application/json\",\n \".txt\": \"text/plain\",\n \".webp\": \"image/webp\"\n};\nfunction serveStaticFile(assetsDir, req, res) {\n var _a, _b;\n const urlPath = (_b = (_a = req.url) === null || _a === void 0 ? void 0 : _a.split(\"?\")[0]) !== null && _b !== void 0 ? _b : \"/\";\n if (urlPath === \"/\" || !urlPath.startsWith(\"/\"))\n return false;\n const filePath = path2.join(assetsDir, urlPath);\n const normalizedPath = path2.normalize(filePath);\n if (!normalizedPath.startsWith(assetsDir)) {\n res.writeHead(403);\n res.end();\n return true;\n }\n let stat;\n try {\n stat = fs2.statSync(normalizedPath);\n } catch (_c) {\n return false;\n }\n if (!stat.isFile())\n return false;\n const ext = path2.extname(normalizedPath);\n const contentType = MIME_TYPES[ext] || \"application/octet-stream\";\n const isHashedAsset = urlPath.startsWith(\"/_next/static/\");\n res.writeHead(200, {\n \"Content-Type\": contentType,\n \"Content-Length\": stat.size,\n \"Cache-Control\": isHashedAsset ? \"public, max-age=31536000, immutable\" : \"public, max-age=60\"\n });\n fs2.createReadStream(normalizedPath).pipe(res);\n return true;\n}\nfunction bridgeOpenNextHandler(handler, converter) {\n return async (req, res) => {\n try {\n const event = await (0, node_request_1.convertNodeRequest)(req, converter);\n const abortController = new AbortController();\n res.on(\"close\", () => abortController.abort());\n const streamCreator = {\n writeHeaders(prelude) {\n const cacheTags = (0, edge_context_1.getCacheTags)();\n if (cacheTags) {\n res.setHeader(\"Cache-Tag\", cacheTags);\n }\n delete prelude.headers[\"x-next-cache-tags\"];\n res.setHeader(\"Set-Cookie\", prelude.cookies);\n res.writeHead(prelude.statusCode, prelude.headers);\n (0, efc_observability_cjs_1.markResponseStreaming)(prelude.statusCode);\n res.flushHeaders();\n return res;\n },\n abortSignal: abortController.signal\n };\n await (0, edge_context_1.runWithEdgeContext)(event.headers, () => handler(event, { streamCreator }));\n } catch (err) {\n console.error(`[pcg-node] ${req.method} ${req.url} 500:`, err.stack || err.message || err);\n if (!res.headersSent) {\n const isDev = process.env.NODE_ENV !== \"production\";\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({\n error: \"Internal Server Error\",\n ...isDev && { message: err.message, stack: err.stack }\n }));\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n };\n}\nexports.bridgeOpenNextHandler = bridgeOpenNextHandler;\nasync function wrapper(handler, converter) {\n var _a;\n const port = parseInt((_a = process.env.PORT) !== null && _a !== void 0 ? _a : \"3000\", 10);\n const host = process.env.HOST || \"0.0.0.0\";\n const assetsDir = path2.resolve(process.cwd(), \"..\", \"..\", \"assets\");\n const logFile = process.env.PCG_LOG_FILE || PCG_DEFAULT_LOG_FILE;\n console.log(`[pcg-node] File logger \\u2192 ${logFile}`);\n if (!fs2.existsSync(assetsDir)) {\n console.warn(`[pcg-node] assets directory not found at ${assetsDir} \\u2014 static file requests will fall through to Next handler`);\n }\n const dispatchToNext = bridgeOpenNextHandler(handler, converter);\n const server = http.createServer(async (req, res) => {\n var _a2, _b;\n const urlPath = (_b = (_a2 = req.url) === null || _a2 === void 0 ? void 0 : _a2.split(\"?\")[0]) !== null && _b !== void 0 ? _b : \"/\";\n if (urlPath !== \"/__health\") {\n console.log(`[pcg-node] --> ${req.method} ${req.url}\n` + JSON.stringify(req.headers, null, 2));\n }\n if (urlPath === \"/__health\") {\n res.writeHead(200, { \"Content-Type\": \"text/plain\" });\n res.end(\"OK\");\n return;\n }\n if (urlPath === \"/_next/image\") {\n try {\n await (0, image_proxy_1.handleImageProxy)(req, res);\n } catch (err) {\n console.error(\"[pcg-node] image-proxy error:\", err);\n if (!res.headersSent) {\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Image proxy failed\" }));\n } else if (!res.writableEnded) {\n res.end();\n }\n }\n return;\n }\n if (serveStaticFile(assetsDir, req, res))\n return;\n await dispatchToNext(req, res);\n });\n let shuttingDown = false;\n const shutdown = (signal) => {\n if (shuttingDown)\n return;\n shuttingDown = true;\n console.log(`[pcg-node] ${signal} received, shutting down...`);\n server.close(() => {\n void (0, efc_observability_cjs_1.flushFunctionLogs)(1e4).then(() => process.exit(0), () => process.exit(0));\n });\n setTimeout(() => process.exit(0), 11e3).unref();\n };\n process.on(\"SIGINT\", () => shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => shutdown(\"SIGTERM\"));\n await new Promise((resolve) => {\n server.listen(port, host, () => {\n console.log(`[pcg-node] Listening on ${host}:${port}`);\n console.log(`[pcg-node] assets: ${assetsDir}`);\n console.log(\"[pcg-node] routes: /__health, /_next/image, /_next/static/*, <next>\");\n resolve();\n });\n });\n return () => {\n server.close();\n };\n}\nvar wrapperDef = {\n wrapper,\n name: \"pcg-node\",\n supportStreaming: true\n};\nexports.default = wrapperDef;\n",
|
|
5
|
+
"overrides/incrementalCache/gateway.js": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\n\n// dist/_protocol/types.js\nvar require_types = __commonJS({\n \"dist/_protocol/types.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n }\n});\n\n// dist/_protocol/keys.js\nvar require_keys = __commonJS({\n \"dist/_protocol/keys.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.buildAstroSessionKey = exports2.buildAstroRouteCacheTagKey = exports2.buildAstroRouteCacheOssKey = exports2.buildPageMetadataKey = exports2.buildTagKey = exports2.buildStaticAssetKey = exports2.buildOssKey = void 0;\n function stripLeadingSlash(s) {\n return s.replace(/^\\/+/, \"\");\n }\n function buildOssKey(params) {\n const { appId, buildId, cacheType = \"cache\" } = params;\n const key = stripLeadingSlash(params.key);\n if (cacheType === \"fetch\") {\n return `${appId}/__fetch/${buildId}/${key}`;\n }\n if (cacheType === \"composable\") {\n return `${appId}/${buildId}/${key}.composable`;\n }\n return `${appId}/${buildId}/${key}.cache`;\n }\n exports2.buildOssKey = buildOssKey;\n function buildStaticAssetKey(params) {\n const p = stripLeadingSlash(params.path);\n return `${params.appId}/_next/static/${p}`;\n }\n exports2.buildStaticAssetKey = buildStaticAssetKey;\n function buildTagKey(params) {\n return {\n app_id: params.appId,\n tag: `${params.buildId}/${params.tag}`,\n path: `${params.buildId}/${params.path}`\n };\n }\n exports2.buildTagKey = buildTagKey;\n function buildPageMetadataKey(params) {\n return {\n app_id: params.appId,\n url: params.url\n };\n }\n exports2.buildPageMetadataKey = buildPageMetadataKey;\n function buildAstroRouteCacheOssKey(params) {\n return `${params.appId}/${params.buildId}/__astro-route/${params.digest}.cache`;\n }\n exports2.buildAstroRouteCacheOssKey = buildAstroRouteCacheOssKey;\n function buildAstroRouteCacheTagKey(params) {\n return `${params.buildId}/astro/${params.digest}`;\n }\n exports2.buildAstroRouteCacheTagKey = buildAstroRouteCacheTagKey;\n function buildAstroSessionKey(params) {\n return `astro:session:${params.namespace}:${params.appId}:${params.sessionDigest}`;\n }\n exports2.buildAstroSessionKey = buildAstroSessionKey;\n }\n});\n\n// dist/_protocol/endpoints.js\nvar require_endpoints = __commonJS({\n \"dist/_protocol/endpoints.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.buildCentralEndpoints = void 0;\n function stripTrailingSlashes(s) {\n return s.replace(/\\/+$/, \"\");\n }\n function buildCentralEndpoints(base) {\n const b = stripTrailingSlashes(base);\n return {\n base: b,\n cache: `${b}/cache`,\n cacheRefresh: `${b}/cache/refresh`,\n revalidateTag: `${b}/revalidate/tag`,\n revalidatePath: `${b}/revalidate/path`,\n tagByTag: `${b}/tag/by-tag`,\n tagByPath: `${b}/tag/by-path`,\n tagLastModified: `${b}/tag/last-modified`,\n tagWrite: `${b}/tag/write`,\n deploySts: `${b}/deploy/sts-token`,\n deployTags: `${b}/deploy/tags`,\n astroSession: (sessionId) => `${b}/astro/v1/sessions/${encodeURIComponent(sessionId)}`\n };\n }\n exports2.buildCentralEndpoints = buildCentralEndpoints;\n }\n});\n\n// dist/_protocol/index.js\nvar require_protocol = __commonJS({\n \"dist/_protocol/index.js\"(exports2) {\n \"use strict\";\n var __createBinding2 = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding2(exports3, m, p);\n };\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n __exportStar(require_types(), exports2);\n __exportStar(require_keys(), exports2);\n __exportStar(require_endpoints(), exports2);\n }\n});\n\n// dist/runtime/debug-network-log.cjs\nvar require_debug_network_log = __commonJS({\n \"dist/runtime/debug-network-log.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var fs2 = require(\"node:fs\");\n var { Console } = require(\"node:console\");\n var KEY = Symbol.for(\"pcg.debug.network-log\");\n var state = globalThis[KEY] || (globalThis[KEY] = { pending: 0, warned: false, details: /* @__PURE__ */ new WeakMap() });\n function warn(reason) {\n if (state.warned)\n return;\n state.warned = true;\n try {\n new Console({ stdout: process.stderr, ignoreErrors: true }).warn(`[pcg debug network] ${reason}`);\n } catch (_a) {\n }\n }\n function debugHeaders(headers) {\n return Object.fromEntries(Array.from(new Headers(headers), ([name, value]) => [\n name,\n /authorization|cookie|key|token|secret|password|signature|credential|session/i.test(name) ? \"[REDACTED]\" : value\n ]));\n }\n function errorDetails(error) {\n return {\n name: error === null || error === void 0 ? void 0 : error.name,\n message: String((error === null || error === void 0 ? void 0 : error.message) || error).slice(0, 2048),\n code: error === null || error === void 0 ? void 0 : error.code\n };\n }\n function capture(record, update) {\n try {\n const details = state.details.get(record) || {};\n update(details);\n state.details.set(record, details);\n } catch (_a) {\n warn(\"unable to capture local request details\");\n }\n }\n var debugNetwork = {\n enabled: true,\n request(record, url, init) {\n capture(record, (details) => {\n let host = null;\n try {\n host = new URL(url).host;\n } catch (_a) {\n }\n details.request = {\n host,\n method: init.method || \"GET\",\n headers: debugHeaders(init.headers)\n };\n });\n },\n response(record, response) {\n capture(record, (details) => {\n details.response = { status: response.status, headers: debugHeaders(response.headers) };\n });\n },\n error(record, error) {\n capture(record, (details) => {\n details.error = errorDetails(error);\n if (error === null || error === void 0 ? void 0 : error.cause)\n details.error.cause = errorDetails(error.cause);\n });\n }\n };\n function withDebugDetails(body, records) {\n if (!records)\n return body;\n const debug = {};\n let bytes = body.length + 32;\n for (const [i, record] of records.entries()) {\n const details = state.details.get(record);\n if (!details)\n continue;\n const key = `gw${i + 1}`;\n bytes += Buffer.byteLength(JSON.stringify(details)) + key.length + 4;\n if (bytes > 64 * 1024) {\n debug.truncated = true;\n break;\n }\n debug[key] = details;\n }\n return Buffer.from(JSON.stringify({ ...JSON.parse(body.toString(\"utf8\")), debug }));\n }\n function writeDebugNetworkLog(body, onSettled, records) {\n if (state.pending >= 64) {\n warn(\"local log queue full; skipping debug copy\");\n return;\n }\n state.pending++;\n const done = (error) => {\n state.pending--;\n if (error)\n warn(`local log write failed (${error.code || \"unknown\"})`);\n try {\n onSettled();\n } catch (_a) {\n warn(\"local log completion failed\");\n }\n };\n try {\n fs2.appendFile(process.env.PCG_DEBUG_NETWORK_LOG_PATH || \"/tmp/pcg-gateway-network.ndjson\", Buffer.concat([withDebugDetails(body, records), Buffer.from(\"\\n\")]), { mode: 384 }, done);\n } catch (error) {\n done(error);\n }\n }\n module2.exports = {\n debugNetwork,\n writeDebugNetworkLog,\n hasPendingDebugNetworkLogs: () => state.pending > 0\n };\n }\n});\n\n// dist/runtime/efc-observability.cjs\nvar require_efc_observability = __commonJS({\n \"dist/runtime/efc-observability.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var { AsyncLocalStorage } = require(\"node:async_hooks\");\n var diagnostics = require(\"node:diagnostics_channel\");\n var http = require(\"node:http\");\n var { randomUUID } = require(\"node:crypto\");\n var { performance } = require(\"node:perf_hooks\");\n var { Console } = require(\"node:console\");\n var { debugNetwork, writeDebugNetworkLog, hasPendingDebugNetworkLogs } = require_debug_network_log();\n var KEY = Symbol.for(\"pcg.efc.observability\");\n var state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n });\n var LOG_LIMIT = 32 * 1024;\n var BODY_LIMIT = 64 * 1024;\n var DEADLINE_MS = 5e3;\n var diagnosticConsole;\n function warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n }\n function safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n }\n function validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n }\n function validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n }\n function traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n }\n function safePath(value) {\n const path2 = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path2.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n }\n function notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n if (hasPendingDebugNetworkLogs())\n return;\n for (const done of state.waiters)\n done(true);\n }\n function drop(reason) {\n state.counts.dropped++;\n warning(reason);\n }\n function rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n }\n function snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n writeDebugNetworkLog(body, notify, ctx.records);\n if (!ctx.report)\n return;\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n }\n function finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n }\n function closeRoot(ctx) {\n if (ctx.closed || !ctx.collect)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n }\n function complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n }\n function responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n }\n function installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request, error }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call) {\n debugNetwork.error(call.record, error);\n complete(call);\n }\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]) || randomUUID().replace(/-/g, \"\");\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n const collect = report || debugNetwork.enabled;\n ctx = {\n trace,\n metadata,\n report,\n collect,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!collect) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path2 = safePath(req.url);\n if (validText(path2, 2048))\n metadata.path = path2;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n ctx.collect = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http.Server.prototype.emit === observedEmit)\n http.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n }\n async function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n ensureGatewayTrace(init.headers);\n if (!ctx || !ctx.collect || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n debugNetwork.request(call.record, url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n debugNetwork.response(call.record, response);\n return response;\n } catch (error) {\n safe(() => complete(call));\n debugNetwork.error(call.record, error);\n throw error;\n }\n }\n function markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n }\n function send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n }\n function pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n }\n function flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n }\n function getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n }\n function getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n }\n function ensureGatewayTrace(headers) {\n const trace = traceId(getEfcTraceId()) || traceId(headers.get(\"eagleeye-traceid\")) || randomUUID().replace(/-/g, \"\");\n headers.set(\"eagleeye-traceid\", trace);\n return trace;\n }\n state.observeGatewayFetch = observeGatewayFetch;\n state.flushFunctionLogs = flushFunctionLogs;\n state.getEfcTraceId = getEfcTraceId;\n state.ensureGatewayTrace = ensureGatewayTrace;\n module2.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId,\n ensureGatewayTrace\n };\n }\n});\n\n// dist/runtime/gateway-auth.js\nvar require_gateway_auth = __commonJS({\n \"dist/runtime/gateway-auth.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.gatewayFetch = exports2.signGatewayHeaders = exports2.loadGatewayAuthConfig = void 0;\n var crypto_1 = require(\"crypto\");\n var efc_observability_cjs_1 = require_efc_observability();\n var DEFAULT_TTL_MS = 5 * 60 * 1e3;\n var DEFAULT_TIMEOUT_MS = 5e3;\n function _fetch(input, init) {\n var _a, _b;\n const gatewayGlobalFetch = globalThis.fetch;\n const fn = gatewayGlobalFetch.__nextPatched ? (_b = (_a = gatewayGlobalFetch._nextOriginalFetch) !== null && _a !== void 0 ? _a : globalThis.__originalFetch) !== null && _b !== void 0 ? _b : gatewayGlobalFetch : gatewayGlobalFetch;\n return fn(input, init);\n }\n function loadGatewayAuthConfig() {\n const gatewayUrl = process.env.ESA_CACHE_GW_GATEWAY_ENDPOINT;\n const authKey = process.env.ESA_CACHE_GW_AUTH_KEY;\n const aliuid = process.env.ESA_CACHE_GW_ALIUID;\n const routinename = process.env.ESA_CACHE_GW_FUNCTIONNAME;\n const version = process.env.ESA_CACHE_GW_VERSION;\n const missing = [];\n if (!gatewayUrl)\n missing.push(\"ESA_CACHE_GW_GATEWAY_ENDPOINT\");\n if (!authKey)\n missing.push(\"ESA_CACHE_GW_AUTH_KEY\");\n if (!aliuid)\n missing.push(\"ESA_CACHE_GW_ALIUID\");\n if (!routinename)\n missing.push(\"ESA_CACHE_GW_FUNCTIONNAME\");\n if (!version)\n missing.push(\"ESA_CACHE_GW_VERSION\");\n if (missing.length > 0) {\n console.error(`[gateway-auth] \\u7F3A\\u5C11\\u5FC5\\u9700\\u7684\\u73AF\\u5883\\u53D8\\u91CF: ${missing.join(\", \")}`);\n return null;\n }\n return {\n gatewayUrl: gatewayUrl.replace(/\\/+$/, \"\"),\n secret: authKey,\n aliuid,\n routinename,\n version\n };\n }\n exports2.loadGatewayAuthConfig = loadGatewayAuthConfig;\n function signGatewayHeaders(cfg, ttlMs = DEFAULT_TTL_MS) {\n const expires = String(Date.now() + ttlMs);\n const md5Hash = (0, crypto_1.createHash)(\"md5\").update(`${cfg.secret}${expires}${cfg.aliuid}${cfg.routinename}${cfg.version}`).digest(\"hex\");\n return {\n authorization: `${expires}-${md5Hash}`,\n aliuid: cfg.aliuid,\n routinename: cfg.routinename,\n version: cfg.version\n };\n }\n exports2.signGatewayHeaders = signGatewayHeaders;\n async function gatewayFetch(cfg, pathOrUrl, init) {\n var _a, _b;\n const url = pathOrUrl.startsWith(\"/\") ? `${cfg.gatewayUrl}${pathOrUrl}` : pathOrUrl;\n const signed = signGatewayHeaders(cfg);\n const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);\n headers.set(\"Authorization\", signed.authorization);\n headers.set(\"AliUid\", signed.aliuid);\n headers.set(\"RoutineName\", signed.routinename);\n headers.set(\"Version\", signed.version);\n (0, efc_observability_cjs_1.ensureGatewayTrace)(headers);\n const timeoutMs = (_a = init === null || init === void 0 ? void 0 : init.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await (0, efc_observability_cjs_1.observeGatewayFetch)(url, {\n ...init,\n headers,\n signal: (_b = init === null || init === void 0 ? void 0 : init.signal) !== null && _b !== void 0 ? _b : controller.signal\n }, _fetch);\n } finally {\n clearTimeout(timer);\n }\n }\n exports2.gatewayFetch = gatewayFetch;\n }\n});\n\n// dist/runtime/edge-context.js\nvar require_edge_context = __commonJS({\n \"dist/runtime/edge-context.js\"(exports2) {\n \"use strict\";\n var _a;\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.getCacheTags = exports2.setCacheTags = exports2.getEdgeContext = exports2.runWithEdgeContext = exports2.buildEdgeContextFromHeaders = void 0;\n var node_async_hooks_1 = require(\"node:async_hooks\");\n var ALS_KEY = Symbol.for(\"pcg.edgeContext.als\");\n var globalRef = globalThis;\n var storage = (_a = globalRef[ALS_KEY]) !== null && _a !== void 0 ? _a : globalRef[ALS_KEY] = new node_async_hooks_1.AsyncLocalStorage();\n var SITE_ID_HEADER = \"x-er-origin-site-id\";\n var HOSTNAME_HEADER = \"host\";\n var FORWARDED_HOSTNAME_HEADER = \"x-forwarded-host\";\n function pickHeader(headers, name) {\n var _a2;\n return (_a2 = headers[name]) !== null && _a2 !== void 0 ? _a2 : headers[name.toLowerCase()];\n }\n function parseHostname(raw) {\n var _a2;\n if (!raw)\n return void 0;\n const first = (_a2 = raw.split(\",\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\n return first || void 0;\n }\n function parseSiteId(raw) {\n if (!raw)\n return void 0;\n const trimmed = raw.trim();\n if (!trimmed)\n return void 0;\n const n = Number(trimmed);\n return Number.isFinite(n) && trimmed === String(n) ? n : trimmed;\n }\n function buildEdgeContextFromHeaders(headers) {\n var _a2;\n const ctx = {};\n const siteId = parseSiteId(pickHeader(headers, SITE_ID_HEADER));\n if (siteId !== void 0)\n ctx.siteId = siteId;\n const hostname = (_a2 = parseHostname(pickHeader(headers, HOSTNAME_HEADER))) !== null && _a2 !== void 0 ? _a2 : parseHostname(pickHeader(headers, FORWARDED_HOSTNAME_HEADER));\n if (hostname)\n ctx.hostname = hostname;\n return ctx;\n }\n exports2.buildEdgeContextFromHeaders = buildEdgeContextFromHeaders;\n function runWithEdgeContext(headers, fn) {\n const ctx = buildEdgeContextFromHeaders(headers);\n return storage.run(ctx, fn);\n }\n exports2.runWithEdgeContext = runWithEdgeContext;\n function getEdgeContext() {\n var _a2;\n return (_a2 = storage.getStore()) !== null && _a2 !== void 0 ? _a2 : {};\n }\n exports2.getEdgeContext = getEdgeContext;\n function setCacheTags(tags) {\n const store = storage.getStore();\n if (store)\n store.cacheTags = tags;\n }\n exports2.setCacheTags = setCacheTags;\n function getCacheTags() {\n var _a2;\n return (_a2 = storage.getStore()) === null || _a2 === void 0 ? void 0 : _a2.cacheTags;\n }\n exports2.getCacheTags = getCacheTags;\n }\n});\n\n// dist/overrides/incrementalCache/gateway.js\nvar __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = exports && exports.__importStar || function(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) {\n for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n }\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar fs = __importStar(require(\"fs\"));\nvar path = __importStar(require(\"path\"));\nvar protocol_1 = require_protocol();\nvar gateway_auth_1 = require_gateway_auth();\nvar edge_context_1 = require_edge_context();\nvar GET_TIMEOUT = 5e3;\nvar SET_TIMEOUT = 1e4;\nvar DELETE_TIMEOUT = 5e3;\nfunction normalizeCacheType(value) {\n if (value === true || value === \"fetch\")\n return \"fetch\";\n if (value === \"composable\")\n return \"composable\";\n return \"cache\";\n}\nfunction buildKey(config, key, cacheTypeInput) {\n return (0, protocol_1.buildOssKey)({\n appId: `${config.aliuid}/${config.routinename}`,\n buildId: config.version,\n key,\n cacheType: normalizeCacheType(cacheTypeInput)\n });\n}\nvar GatewayIncrementalCache = class {\n constructor() {\n this.name = \"gateway-incremental-cache\";\n this.config = null;\n this.configLoaded = false;\n }\n /**\n * 延迟加载配置,避免在构造函数中因环境变量缺失而阻塞 Function 启动。\n */\n getConfig() {\n if (!this.configLoaded) {\n this.config = (0, gateway_auth_1.loadGatewayAuthConfig)();\n this.configLoaded = true;\n }\n return this.config;\n }\n /**\n * 从 Gateway 读取缓存。\n * Gateway 不可用时降级读 .open-next/cache/ 下的预构建文件(本地开发)。\n */\n async get(key, cacheType) {\n var _a, _b;\n const config = this.getConfig();\n if (!config)\n return this.getFromLocalCache(key, cacheType);\n const ossKey = buildKey(config, key, cacheType);\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, `/storage/${ossKey}`, {\n method: \"GET\",\n timeoutMs: GET_TIMEOUT\n });\n if (res.status === 404)\n return null;\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[incrementalCache] GET \\u88AB\\u62D2\\u7EDD: key=\"${ossKey}\" (${res.status})\\uFF0C\\u8BF7\\u68C0\\u67E5\\u7B7E\\u540D secret \\u6216 key \\u524D\\u7F00`);\n } else {\n console.warn(`[incrementalCache] GET \\u5931\\u8D25: key=\"${ossKey}\", \\u72B6\\u6001\\u7801=${res.status}`);\n }\n return null;\n }\n const body = await res.text();\n let envelope;\n try {\n envelope = JSON.parse(body);\n } catch (_c) {\n console.warn(`[incrementalCache] JSON \\u89E3\\u6790\\u5931\\u8D25: key=\"${ossKey}\"`);\n return null;\n }\n if (!envelope || typeof envelope !== \"object\" || typeof envelope.lastModified !== \"number\") {\n console.warn(`[incrementalCache] envelope \\u683C\\u5F0F\\u5F02\\u5E38\\u6216\\u7F3A lastModified: key=\"${ossKey}\"`);\n return null;\n }\n const val = envelope.value;\n const tags = (_b = (_a = val === null || val === void 0 ? void 0 : val.meta) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[\"x-next-cache-tags\"];\n if (typeof tags === \"string\") {\n (0, edge_context_1.setCacheTags)(tags);\n }\n return { value: envelope.value, lastModified: envelope.lastModified };\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[incrementalCache] GET \\u8D85\\u65F6: key=\"${ossKey}\" (${GET_TIMEOUT}ms)`);\n } else {\n console.warn(`[incrementalCache] GET \\u5F02\\u5E38: key=\"${ossKey}\", ${err.message}`);\n }\n return null;\n }\n }\n /**\n * 向 Gateway 写入缓存。\n * Gateway 不可用时降级写入本地 runtime cache 目录(本地开发)。\n */\n async set(key, value, cacheType) {\n var _a, _b;\n const tags = (_b = (_a = value === null || value === void 0 ? void 0 : value.meta) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[\"x-next-cache-tags\"];\n if (typeof tags === \"string\") {\n (0, edge_context_1.setCacheTags)(tags);\n }\n const config = this.getConfig();\n if (!config) {\n this.setToLocalCache(key, value, cacheType);\n return;\n }\n const ossKey = buildKey(config, key, cacheType);\n const body = JSON.stringify({ lastModified: Date.now(), value });\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, `/storage/${ossKey}`, {\n method: \"PUT\",\n headers: { \"Content-Type\": \"application/json\" },\n body,\n timeoutMs: SET_TIMEOUT\n });\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[incrementalCache] PUT \\u88AB\\u62D2\\u7EDD: key=\"${ossKey}\" (${res.status})\\uFF0C\\u8BF7\\u68C0\\u67E5\\u7B7E\\u540D secret \\u6216 key \\u524D\\u7F00`);\n } else {\n console.warn(`[incrementalCache] PUT \\u5931\\u8D25: key=\"${ossKey}\", \\u72B6\\u6001\\u7801=${res.status}`);\n }\n }\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[incrementalCache] PUT \\u8D85\\u65F6: key=\"${ossKey}\" (${SET_TIMEOUT}ms)`);\n } else {\n console.warn(`[incrementalCache] PUT \\u5F02\\u5E38: key=\"${ossKey}\", ${err.message}`);\n }\n }\n }\n // ---------------------------------------------------------------------------\n // 本地缓存目录解析\n // ---------------------------------------------------------------------------\n /**\n * 解析 .open-next/cache 根目录。\n * process.cwd() 在 pcg serve 时是 .open-next/server-functions/default/,\n * 向上两级即 .open-next/cache。\n */\n getCacheRoot() {\n return path.resolve(process.cwd(), \"..\", \"..\", \"cache\");\n }\n /**\n * 将旧 boolean 参数或新版字符串参数统一为缓存类型标识。\n */\n resolveTypeLabel(cacheType) {\n return normalizeCacheType(cacheType);\n }\n // ---------------------------------------------------------------------------\n // 本地读缓存\n // ---------------------------------------------------------------------------\n /**\n * 本地开发降级读缓存,仅在 Gateway 不可用时启用。\n *\n * 查找顺序:\n * 1. 运行时缓存: .open-next/cache/__runtime/{type}/{key}.cache\n * (set() 在本地模式下写入的 composable/fetch/cache 缓存)\n * 2. 预构建缓存: .open-next/cache/{buildId}/{key}.cache\n * (pcg build 生成的页面级别缓存)\n * 3. 预构建 fetch 缓存: .open-next/cache/__fetch/{buildId}/{key}\n * (pcg build 生成的 fetch 数据缓存)\n */\n getFromLocalCache(key, cacheTypeInput) {\n const cacheRoot = this.getCacheRoot();\n const cacheType = this.resolveTypeLabel(cacheTypeInput);\n const runtimeResult = this.readRuntimeCache(cacheRoot, cacheType, key);\n if (runtimeResult)\n return runtimeResult;\n if (cacheType === \"cache\") {\n return this.readPrebuildCache(cacheRoot, key);\n }\n if (cacheType === \"fetch\") {\n return this.readPrebuildFetchCache(cacheRoot, key);\n }\n return null;\n }\n /** 读运行时缓存: __runtime/{type}/{key}.cache */\n readRuntimeCache(cacheRoot, typeLabel, key) {\n try {\n const filePath = path.join(cacheRoot, \"__runtime\", typeLabel, `${key}.cache`);\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const envelope = JSON.parse(raw);\n if (envelope && typeof envelope === \"object\" && typeof envelope.lastModified === \"number\") {\n console.log(`[incrementalCache] runtime cache HIT: type=\"${typeLabel}\" key=\"${key}\"`);\n return { value: envelope.value, lastModified: envelope.lastModified };\n }\n } catch (_a) {\n }\n return null;\n }\n /** 读预构建缓存: {buildId}/{key}.cache */\n readPrebuildCache(cacheRoot, key) {\n var _a, _b;\n try {\n const entries = fs.readdirSync(cacheRoot).filter((d) => {\n if (d.startsWith(\"__\"))\n return false;\n try {\n return fs.statSync(path.join(cacheRoot, d)).isDirectory();\n } catch (_a2) {\n return false;\n }\n });\n for (const bid of entries) {\n const filePath = path.join(cacheRoot, bid, `${key}.cache`);\n try {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const value = JSON.parse(raw);\n const stat = fs.statSync(filePath);\n const tags = (_b = (_a = value === null || value === void 0 ? void 0 : value.meta) === null || _a === void 0 ? void 0 : _a.headers) === null || _b === void 0 ? void 0 : _b[\"x-next-cache-tags\"];\n if (typeof tags === \"string\") {\n (0, edge_context_1.setCacheTags)(tags);\n }\n console.log(`[incrementalCache] local cache HIT: key=\"${key}\" tags=${tags !== null && tags !== void 0 ? tags : \"\\u2205\"}`);\n return { value, lastModified: stat.mtimeMs };\n } catch (_c) {\n continue;\n }\n }\n } catch (_d) {\n }\n return null;\n }\n /** 读预构建 fetch 缓存: __fetch/{buildId}/{key} (无 .cache 后缀) */\n readPrebuildFetchCache(cacheRoot, key) {\n try {\n const fetchDir = path.join(cacheRoot, \"__fetch\");\n const buildIds = fs.readdirSync(fetchDir).filter((d) => {\n try {\n return fs.statSync(path.join(fetchDir, d)).isDirectory();\n } catch (_a) {\n return false;\n }\n });\n for (const bid of buildIds) {\n const filePath = path.join(fetchDir, bid, key);\n try {\n const raw = fs.readFileSync(filePath, \"utf-8\");\n const value = JSON.parse(raw);\n const stat = fs.statSync(filePath);\n console.log(`[incrementalCache] local fetch cache HIT: key=\"${key}\"`);\n return { value, lastModified: stat.mtimeMs };\n } catch (_a) {\n continue;\n }\n }\n } catch (_b) {\n }\n return null;\n }\n // ---------------------------------------------------------------------------\n // 本地写缓存\n // ---------------------------------------------------------------------------\n /**\n * 本地开发降级写缓存。\n * 将 envelope { lastModified, value } 写入\n * .open-next/cache/__runtime/{type}/{key}.cache,\n * 供后续 getFromLocalCache() 读取。\n */\n setToLocalCache(key, value, cacheTypeInput) {\n try {\n const cacheRoot = this.getCacheRoot();\n const typeLabel = this.resolveTypeLabel(cacheTypeInput);\n const dir = path.join(cacheRoot, \"__runtime\", typeLabel);\n const filePath = path.join(dir, `${key}.cache`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n const envelope = JSON.stringify({ lastModified: Date.now(), value });\n fs.writeFileSync(filePath, envelope, \"utf-8\");\n console.log(`[incrementalCache] runtime cache SET: type=\"${typeLabel}\" key=\"${key}\"`);\n } catch (err) {\n console.warn(`[incrementalCache] runtime cache SET failed: key=\"${key}\", ${err.message}`);\n }\n }\n /**\n * 通过 Gateway 删除缓存。\n */\n async delete(key, cacheType) {\n const config = this.getConfig();\n if (!config)\n return;\n const ossKey = buildKey(config, key, cacheType);\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, `/storage/${ossKey}`, {\n method: \"DELETE\",\n timeoutMs: DELETE_TIMEOUT\n });\n if (res.status === 404)\n return;\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[incrementalCache] DELETE \\u88AB\\u62D2\\u7EDD: key=\"${ossKey}\" (${res.status})\\uFF0C\\u8BF7\\u68C0\\u67E5\\u7B7E\\u540D secret \\u6216 key \\u524D\\u7F00`);\n } else {\n console.warn(`[incrementalCache] DELETE \\u5931\\u8D25: key=\"${ossKey}\", \\u72B6\\u6001\\u7801=${res.status}`);\n }\n }\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[incrementalCache] DELETE \\u8D85\\u65F6: key=\"${ossKey}\" (${DELETE_TIMEOUT}ms)`);\n } else {\n console.warn(`[incrementalCache] DELETE \\u5F02\\u5E38: key=\"${ossKey}\", ${err.message}`);\n }\n }\n }\n};\nexports.default = GatewayIncrementalCache;\n",
|
|
6
|
+
"overrides/tagCache/gateway.js": "\"use strict\";\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\n\n// dist/runtime/debug-network-log.cjs\nvar require_debug_network_log = __commonJS({\n \"dist/runtime/debug-network-log.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var fs = require(\"node:fs\");\n var { Console } = require(\"node:console\");\n var KEY = Symbol.for(\"pcg.debug.network-log\");\n var state = globalThis[KEY] || (globalThis[KEY] = { pending: 0, warned: false, details: /* @__PURE__ */ new WeakMap() });\n function warn(reason) {\n if (state.warned)\n return;\n state.warned = true;\n try {\n new Console({ stdout: process.stderr, ignoreErrors: true }).warn(`[pcg debug network] ${reason}`);\n } catch (_a) {\n }\n }\n function debugHeaders(headers) {\n return Object.fromEntries(Array.from(new Headers(headers), ([name, value]) => [\n name,\n /authorization|cookie|key|token|secret|password|signature|credential|session/i.test(name) ? \"[REDACTED]\" : value\n ]));\n }\n function errorDetails(error) {\n return {\n name: error === null || error === void 0 ? void 0 : error.name,\n message: String((error === null || error === void 0 ? void 0 : error.message) || error).slice(0, 2048),\n code: error === null || error === void 0 ? void 0 : error.code\n };\n }\n function capture(record, update) {\n try {\n const details = state.details.get(record) || {};\n update(details);\n state.details.set(record, details);\n } catch (_a) {\n warn(\"unable to capture local request details\");\n }\n }\n var debugNetwork = {\n enabled: true,\n request(record, url, init) {\n capture(record, (details) => {\n let host = null;\n try {\n host = new URL(url).host;\n } catch (_a) {\n }\n details.request = {\n host,\n method: init.method || \"GET\",\n headers: debugHeaders(init.headers)\n };\n });\n },\n response(record, response) {\n capture(record, (details) => {\n details.response = { status: response.status, headers: debugHeaders(response.headers) };\n });\n },\n error(record, error) {\n capture(record, (details) => {\n details.error = errorDetails(error);\n if (error === null || error === void 0 ? void 0 : error.cause)\n details.error.cause = errorDetails(error.cause);\n });\n }\n };\n function withDebugDetails(body, records) {\n if (!records)\n return body;\n const debug = {};\n let bytes = body.length + 32;\n for (const [i, record] of records.entries()) {\n const details = state.details.get(record);\n if (!details)\n continue;\n const key = `gw${i + 1}`;\n bytes += Buffer.byteLength(JSON.stringify(details)) + key.length + 4;\n if (bytes > 64 * 1024) {\n debug.truncated = true;\n break;\n }\n debug[key] = details;\n }\n return Buffer.from(JSON.stringify({ ...JSON.parse(body.toString(\"utf8\")), debug }));\n }\n function writeDebugNetworkLog(body, onSettled, records) {\n if (state.pending >= 64) {\n warn(\"local log queue full; skipping debug copy\");\n return;\n }\n state.pending++;\n const done = (error) => {\n state.pending--;\n if (error)\n warn(`local log write failed (${error.code || \"unknown\"})`);\n try {\n onSettled();\n } catch (_a) {\n warn(\"local log completion failed\");\n }\n };\n try {\n fs.appendFile(process.env.PCG_DEBUG_NETWORK_LOG_PATH || \"/tmp/pcg-gateway-network.ndjson\", Buffer.concat([withDebugDetails(body, records), Buffer.from(\"\\n\")]), { mode: 384 }, done);\n } catch (error) {\n done(error);\n }\n }\n module2.exports = {\n debugNetwork,\n writeDebugNetworkLog,\n hasPendingDebugNetworkLogs: () => state.pending > 0\n };\n }\n});\n\n// dist/runtime/efc-observability.cjs\nvar require_efc_observability = __commonJS({\n \"dist/runtime/efc-observability.cjs\"(exports2, module2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n var { AsyncLocalStorage } = require(\"node:async_hooks\");\n var diagnostics = require(\"node:diagnostics_channel\");\n var http = require(\"node:http\");\n var { randomUUID } = require(\"node:crypto\");\n var { performance } = require(\"node:perf_hooks\");\n var { Console } = require(\"node:console\");\n var { debugNetwork, writeDebugNetworkLog, hasPendingDebugNetworkLogs } = require_debug_network_log();\n var KEY = Symbol.for(\"pcg.efc.observability\");\n var state = globalThis[KEY] || (globalThis[KEY] = {\n requests: new AsyncLocalStorage(),\n calls: new AsyncLocalStorage(),\n transports: /* @__PURE__ */ new WeakMap(),\n roots: /* @__PURE__ */ new Set(),\n queue: [],\n sending: 0,\n waiters: /* @__PURE__ */ new Set(),\n counts: { delivered: 0, dropped: 0, failed: 0 },\n lastWarning: -Infinity\n });\n var LOG_LIMIT = 32 * 1024;\n var BODY_LIMIT = 64 * 1024;\n var DEADLINE_MS = 5e3;\n var diagnosticConsole;\n function warning(reason) {\n try {\n if (performance.now() - state.lastWarning < 3e4)\n return;\n state.lastWarning = performance.now();\n diagnosticConsole || (diagnosticConsole = new Console({\n stdout: process.stderr,\n ignoreErrors: true\n }));\n diagnosticConsole.warn(`[pcg timing] ${reason}`);\n } catch (_a) {\n }\n }\n function safe(fn) {\n try {\n return fn();\n } catch (_a) {\n warning(\"observation failed\");\n }\n }\n function validText(value, limit) {\n return typeof value === \"string\" && value.length > 0 && Buffer.byteLength(value) <= limit && !/[\\x00-\\x1f\\x7f]/.test(value) && Buffer.from(value).toString(\"utf8\") === value;\n }\n function validIdentifier(value) {\n return validText(value, 128) && !/[\\\\/]/.test(value);\n }\n function traceId(value) {\n return validIdentifier(value) && !/[^\\x21-\\x7e]/.test(value) ? value : void 0;\n }\n function safePath(value) {\n const path = new URL(value || \"/\", \"http://efc.local\").pathname;\n return path.replace(/(\\/astro\\/v1\\/sessions\\/)[^/]+/g, \"$1:sessionId\").replace(/(\\/api\\/dashboard\\/runtime-config\\/auth-keys\\/)[^/]+/g, \"$1:keyId\");\n }\n function notify() {\n if (state.roots.size || state.queue.length || state.sending)\n return;\n if (hasPendingDebugNetworkLogs())\n return;\n for (const done of state.waiters)\n done(true);\n }\n function drop(reason) {\n state.counts.dropped++;\n warning(reason);\n }\n function rounded(value) {\n return Math.round(value * 1e3) / 1e3;\n }\n function snapshot(ctx) {\n const total = { stream: ctx.stream };\n for (const field of [\"head\", \"dur\"]) {\n if (ctx.records.every((record) => typeof record[field] === \"number\")) {\n total[field] = rounded(ctx.records.reduce((sum, record) => sum + record[field], 0));\n }\n }\n const timing = { total };\n ctx.records.forEach((record, i) => {\n timing[`gw${i + 1}`] = record;\n });\n const log = JSON.stringify(timing);\n if (Buffer.byteLength(log) > LOG_LIMIT)\n return drop(\"log exceeds size limit\");\n const body = Buffer.from(JSON.stringify({\n ...ctx.metadata,\n timestamp: (/* @__PURE__ */ new Date()).toISOString(),\n level: \"INFO\",\n log\n }));\n if (body.length > BODY_LIMIT)\n return drop(\"request exceeds size limit\");\n writeDebugNetworkLog(body, notify, ctx.records);\n if (!ctx.report)\n return;\n if (state.queue.length >= 64)\n return drop(\"log queue full\");\n state.queue.push(body);\n pump();\n }\n function finalize(ctx, expired = false) {\n if (!ctx.closed || ctx.submitted || !expired && ctx.pending && !ctx.overflow)\n return;\n ctx.submitted = true;\n clearTimeout(ctx.timer);\n state.requests.exit(() => state.calls.exit(() => setImmediate(() => {\n try {\n if (ctx.overflow)\n drop(\"collection exceeds size limit\");\n else\n snapshot(ctx);\n if (expired)\n warning(\"Gateway body collection deadline exceeded\");\n } catch (_a) {\n drop(\"unable to encode timing log\");\n } finally {\n ctx.records.length = 0;\n state.roots.delete(ctx);\n notify();\n }\n })));\n }\n function closeRoot(ctx) {\n if (ctx.closed || !ctx.collect)\n return;\n ctx.closed = true;\n finalize(ctx);\n if (!ctx.submitted) {\n ctx.timer = setTimeout(() => safe(() => finalize(ctx, true)), DEADLINE_MS);\n ctx.timer.unref();\n }\n }\n function complete(call, end = performance.now()) {\n if (call.done)\n return;\n call.done = true;\n call.record.dur = rounded(Math.max(0, end - call.start));\n call.ctx.pending--;\n finalize(call.ctx);\n }\n function responseHeaders(call, status, rid, at) {\n if (call.done || call.ctx.submitted)\n return;\n call.record.head = rounded(Math.max(0, at - call.start));\n call.record.result = status;\n if (typeof rid === \"string\") {\n call.ctx.bytes += Buffer.byteLength(JSON.stringify(rid));\n if (call.ctx.bytes > LOG_LIMIT)\n call.ctx.overflow = true;\n else\n call.record.rid = rid;\n }\n }\n function installEfcObservability() {\n if (state.installed)\n return true;\n const undo = [];\n let originalEmit;\n let observedEmit;\n const subscribe = (name, fn) => {\n const channel = diagnostics.channel(name);\n const listener = (message) => safe(() => fn(message));\n undo.push(() => channel.unsubscribe(listener));\n channel.subscribe(listener);\n };\n try {\n originalEmit = http.Server.prototype.emit;\n subscribe(\"undici:request:create\", ({ request }) => {\n const call = state.calls.getStore();\n if (!call || call.done || call.ctx.submitted)\n return;\n call.open++;\n state.transports.set(request, call);\n });\n subscribe(\"undici:request:headers\", ({ request, response }) => {\n const call = state.transports.get(request);\n if (!call || response.statusCode < 200)\n return;\n if (call.follow && [301, 302, 303, 307, 308].includes(response.statusCode) && response.headers.some((name, i) => i % 2 === 0 && String(name).toLowerCase() === \"location\")) {\n state.transports.delete(request);\n call.open--;\n return;\n }\n let rid = \"\";\n for (let i = 0; i < response.headers.length; i += 2) {\n if (String(response.headers[i]).toLowerCase() === \"x-request-id\") {\n rid = String(response.headers[i + 1]);\n break;\n }\n }\n responseHeaders(call, response.statusCode, rid, performance.now());\n });\n subscribe(\"undici:request:trailers\", ({ request }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (!call)\n return;\n call.open--;\n call.end = performance.now();\n if (call.resolved && call.open === 0)\n complete(call, call.end);\n });\n subscribe(\"undici:request:error\", ({ request, error }) => {\n const call = state.transports.get(request);\n state.transports.delete(request);\n if (call) {\n debugNetwork.error(call.record, error);\n complete(call);\n }\n });\n observedEmit = function(event, ...args) {\n if (event !== \"request\")\n return Reflect.apply(originalEmit, this, [event, ...args]);\n const [req, res] = args;\n let ctx;\n let prepared = false;\n safe(() => {\n const trace = traceId(req.headers[\"eagleeye-traceid\"]) || randomUUID().replace(/-/g, \"\");\n const enabled = !!process.env.ESA_EFC_FUNCTION_LOG_KEY;\n const metadata = {\n functionName: process.env.ESA_CACHE_GW_FUNCTIONNAME,\n codeVersion: process.env.ESA_CACHE_GW_VERSION,\n requestId: trace || randomUUID()\n };\n const report = enabled && validIdentifier(metadata.functionName) && validIdentifier(metadata.codeVersion);\n if (enabled && !report)\n drop(\"invalid function metadata\");\n const collect = report || debugNetwork.enabled;\n ctx = {\n trace,\n metadata,\n report,\n collect,\n hasBody: req.method !== \"HEAD\",\n closed: false,\n submitted: false,\n stream: 0,\n records: [],\n pending: 0,\n bytes: 64,\n overflow: false\n };\n if (!collect) {\n prepared = true;\n return;\n }\n const host = req.headers.host;\n if (validText(host, 253) && !host.includes(\"/\"))\n metadata.host = host;\n const path = safePath(req.url);\n if (validText(path, 2048))\n metadata.path = path;\n state.roots.add(ctx);\n const originalWrite = res.write;\n const observedWrite = function(chunk, ...rest) {\n if (ctx.hasBody && this.statusCode !== 204 && this.statusCode !== 304 && chunk && chunk.length > 0)\n ctx.stream = 1;\n return Reflect.apply(originalWrite, this, [chunk, ...rest]);\n };\n res.write = observedWrite;\n const done = () => {\n safe(() => {\n res.removeListener(\"finish\", done);\n res.removeListener(\"close\", done);\n if (res.write === observedWrite)\n res.write = originalWrite;\n closeRoot(ctx);\n });\n };\n res.once(\"finish\", done);\n res.once(\"close\", done);\n prepared = true;\n });\n if (ctx && !prepared) {\n ctx.report = false;\n ctx.collect = false;\n state.roots.delete(ctx);\n drop(\"unable to install response observation\");\n }\n return ctx ? state.requests.run(ctx, () => Reflect.apply(originalEmit, this, [event, ...args])) : Reflect.apply(originalEmit, this, [event, ...args]);\n };\n http.Server.prototype.emit = observedEmit;\n state.installed = true;\n return true;\n } catch (_a) {\n safe(() => {\n if (observedEmit && http.Server.prototype.emit === observedEmit)\n http.Server.prototype.emit = originalEmit;\n });\n for (const remove of undo.reverse())\n safe(remove);\n warning(\"unable to install observation\");\n return false;\n }\n }\n async function observeGatewayFetch(url, init, fetcher) {\n const ctx = state.requests.getStore();\n let call;\n safe(() => {\n ensureGatewayTrace(init.headers);\n if (!ctx || !ctx.collect || ctx.closed || ctx.overflow)\n return;\n const record = { rid: \"\", path: safePath(url) };\n ctx.bytes += Buffer.byteLength(JSON.stringify(record)) + 128;\n if (ctx.bytes > LOG_LIMIT) {\n ctx.overflow = true;\n ctx.records.length = 0;\n return;\n }\n call = {\n ctx,\n record,\n start: performance.now(),\n open: 0,\n resolved: false,\n done: false,\n follow: !init.redirect || init.redirect === \"follow\"\n };\n ctx.records.push(record);\n ctx.pending++;\n });\n if (!call)\n return fetcher(url, init);\n debugNetwork.request(call.record, url, init);\n try {\n const response = await state.calls.run(call, () => fetcher(url, init));\n safe(() => {\n if (call.record.head === void 0) {\n responseHeaders(call, response.status, response.headers.get(\"x-request-id\") || \"\", performance.now());\n }\n call.resolved = true;\n if (call.end !== void 0 && call.open === 0)\n complete(call, call.end);\n });\n debugNetwork.response(call.record, response);\n return response;\n } catch (error) {\n safe(() => complete(call));\n debugNetwork.error(call.record, error);\n throw error;\n }\n }\n function markResponseStreaming(statusCode = 200) {\n safe(() => {\n const ctx = state.requests.getStore();\n if (ctx && ctx.hasBody && statusCode !== 204 && statusCode !== 304)\n ctx.stream = 1;\n });\n }\n function send(body) {\n return new Promise((resolve) => {\n let req;\n let timer;\n let finished = false;\n const done = (ok, reason) => {\n if (finished)\n return;\n finished = true;\n clearTimeout(timer);\n if (ok)\n state.counts.delivered++;\n else {\n state.counts.failed++;\n warning(reason);\n }\n resolve();\n };\n try {\n const key = process.env.ESA_EFC_FUNCTION_LOG_KEY;\n if (!key)\n return done(false, \"log capability disabled\");\n req = http.request({\n host: \"127.0.0.1\",\n port: 44772,\n path: \"/function-logs\",\n method: \"POST\",\n agent: false,\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": body.length,\n \"X-EFC-Function-Log-Key\": key\n }\n }, (res) => {\n let text = \"\";\n let size = 0;\n res.on(\"data\", (chunk) => {\n size += chunk.length;\n if (size > 4096) {\n done(false, \"log API response exceeds limit\");\n res.destroy();\n } else\n text += chunk.toString(\"utf8\");\n });\n res.on(\"end\", () => {\n let accepted;\n if (res.statusCode === 200)\n safe(() => {\n accepted = JSON.parse(text).accepted;\n });\n done(res.statusCode === 200 && accepted === 1, `log API status=${res.statusCode}`);\n });\n res.on(\"error\", () => done(false, \"log API response error\"));\n res.on(\"aborted\", () => done(false, \"log API response aborted\"));\n });\n req.on(\"error\", () => done(false, \"log API connection error\"));\n timer = setTimeout(() => {\n done(false, \"log API deadline exceeded\");\n req.destroy();\n }, DEADLINE_MS);\n req.end(body);\n } catch (_a) {\n done(false, \"log API request failed\");\n if (req)\n req.destroy();\n }\n });\n }\n function pump() {\n while (state.sending < 4 && state.queue.length) {\n const body = state.queue.shift();\n state.sending++;\n state.requests.exit(() => state.calls.exit(() => {\n send(body).then(() => {\n state.sending--;\n safe(pump);\n safe(notify);\n });\n }));\n }\n }\n function flushFunctionLogs(timeoutMs = 1e4) {\n return new Promise((resolve) => {\n const timer = setTimeout(() => done(false), timeoutMs);\n const done = (ok) => {\n clearTimeout(timer);\n state.waiters.delete(done);\n if (!ok)\n warning(\"log drain deadline exceeded\");\n resolve(ok);\n };\n state.waiters.add(done);\n notify();\n });\n }\n function getFunctionLogStats() {\n return {\n ...state.counts,\n queued: state.queue.length,\n sending: state.sending,\n collecting: state.roots.size\n };\n }\n function getEfcTraceId() {\n var _a;\n return (_a = state.requests.getStore()) === null || _a === void 0 ? void 0 : _a.trace;\n }\n function ensureGatewayTrace(headers) {\n const trace = traceId(getEfcTraceId()) || traceId(headers.get(\"eagleeye-traceid\")) || randomUUID().replace(/-/g, \"\");\n headers.set(\"eagleeye-traceid\", trace);\n return trace;\n }\n state.observeGatewayFetch = observeGatewayFetch;\n state.flushFunctionLogs = flushFunctionLogs;\n state.getEfcTraceId = getEfcTraceId;\n state.ensureGatewayTrace = ensureGatewayTrace;\n module2.exports = {\n installEfcObservability,\n observeGatewayFetch,\n markResponseStreaming,\n flushFunctionLogs,\n getFunctionLogStats,\n getEfcTraceId,\n ensureGatewayTrace\n };\n }\n});\n\n// dist/runtime/gateway-auth.js\nvar require_gateway_auth = __commonJS({\n \"dist/runtime/gateway-auth.js\"(exports2) {\n \"use strict\";\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.gatewayFetch = exports2.signGatewayHeaders = exports2.loadGatewayAuthConfig = void 0;\n var crypto_1 = require(\"crypto\");\n var efc_observability_cjs_1 = require_efc_observability();\n var DEFAULT_TTL_MS = 5 * 60 * 1e3;\n var DEFAULT_TIMEOUT_MS = 5e3;\n function _fetch(input, init) {\n var _a, _b;\n const gatewayGlobalFetch = globalThis.fetch;\n const fn = gatewayGlobalFetch.__nextPatched ? (_b = (_a = gatewayGlobalFetch._nextOriginalFetch) !== null && _a !== void 0 ? _a : globalThis.__originalFetch) !== null && _b !== void 0 ? _b : gatewayGlobalFetch : gatewayGlobalFetch;\n return fn(input, init);\n }\n function loadGatewayAuthConfig() {\n const gatewayUrl = process.env.ESA_CACHE_GW_GATEWAY_ENDPOINT;\n const authKey = process.env.ESA_CACHE_GW_AUTH_KEY;\n const aliuid = process.env.ESA_CACHE_GW_ALIUID;\n const routinename = process.env.ESA_CACHE_GW_FUNCTIONNAME;\n const version = process.env.ESA_CACHE_GW_VERSION;\n const missing = [];\n if (!gatewayUrl)\n missing.push(\"ESA_CACHE_GW_GATEWAY_ENDPOINT\");\n if (!authKey)\n missing.push(\"ESA_CACHE_GW_AUTH_KEY\");\n if (!aliuid)\n missing.push(\"ESA_CACHE_GW_ALIUID\");\n if (!routinename)\n missing.push(\"ESA_CACHE_GW_FUNCTIONNAME\");\n if (!version)\n missing.push(\"ESA_CACHE_GW_VERSION\");\n if (missing.length > 0) {\n console.error(`[gateway-auth] \\u7F3A\\u5C11\\u5FC5\\u9700\\u7684\\u73AF\\u5883\\u53D8\\u91CF: ${missing.join(\", \")}`);\n return null;\n }\n return {\n gatewayUrl: gatewayUrl.replace(/\\/+$/, \"\"),\n secret: authKey,\n aliuid,\n routinename,\n version\n };\n }\n exports2.loadGatewayAuthConfig = loadGatewayAuthConfig;\n function signGatewayHeaders(cfg, ttlMs = DEFAULT_TTL_MS) {\n const expires = String(Date.now() + ttlMs);\n const md5Hash = (0, crypto_1.createHash)(\"md5\").update(`${cfg.secret}${expires}${cfg.aliuid}${cfg.routinename}${cfg.version}`).digest(\"hex\");\n return {\n authorization: `${expires}-${md5Hash}`,\n aliuid: cfg.aliuid,\n routinename: cfg.routinename,\n version: cfg.version\n };\n }\n exports2.signGatewayHeaders = signGatewayHeaders;\n async function gatewayFetch(cfg, pathOrUrl, init) {\n var _a, _b;\n const url = pathOrUrl.startsWith(\"/\") ? `${cfg.gatewayUrl}${pathOrUrl}` : pathOrUrl;\n const signed = signGatewayHeaders(cfg);\n const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);\n headers.set(\"Authorization\", signed.authorization);\n headers.set(\"AliUid\", signed.aliuid);\n headers.set(\"RoutineName\", signed.routinename);\n headers.set(\"Version\", signed.version);\n (0, efc_observability_cjs_1.ensureGatewayTrace)(headers);\n const timeoutMs = (_a = init === null || init === void 0 ? void 0 : init.timeoutMs) !== null && _a !== void 0 ? _a : DEFAULT_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await (0, efc_observability_cjs_1.observeGatewayFetch)(url, {\n ...init,\n headers,\n signal: (_b = init === null || init === void 0 ? void 0 : init.signal) !== null && _b !== void 0 ? _b : controller.signal\n }, _fetch);\n } finally {\n clearTimeout(timer);\n }\n }\n exports2.gatewayFetch = gatewayFetch;\n }\n});\n\n// dist/runtime/edge-context.js\nvar require_edge_context = __commonJS({\n \"dist/runtime/edge-context.js\"(exports2) {\n \"use strict\";\n var _a;\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.getCacheTags = exports2.setCacheTags = exports2.getEdgeContext = exports2.runWithEdgeContext = exports2.buildEdgeContextFromHeaders = void 0;\n var node_async_hooks_1 = require(\"node:async_hooks\");\n var ALS_KEY = Symbol.for(\"pcg.edgeContext.als\");\n var globalRef = globalThis;\n var storage = (_a = globalRef[ALS_KEY]) !== null && _a !== void 0 ? _a : globalRef[ALS_KEY] = new node_async_hooks_1.AsyncLocalStorage();\n var SITE_ID_HEADER = \"x-er-origin-site-id\";\n var HOSTNAME_HEADER = \"host\";\n var FORWARDED_HOSTNAME_HEADER = \"x-forwarded-host\";\n function pickHeader(headers, name) {\n var _a2;\n return (_a2 = headers[name]) !== null && _a2 !== void 0 ? _a2 : headers[name.toLowerCase()];\n }\n function parseHostname(raw) {\n var _a2;\n if (!raw)\n return void 0;\n const first = (_a2 = raw.split(\",\")[0]) === null || _a2 === void 0 ? void 0 : _a2.trim();\n return first || void 0;\n }\n function parseSiteId(raw) {\n if (!raw)\n return void 0;\n const trimmed = raw.trim();\n if (!trimmed)\n return void 0;\n const n = Number(trimmed);\n return Number.isFinite(n) && trimmed === String(n) ? n : trimmed;\n }\n function buildEdgeContextFromHeaders(headers) {\n var _a2;\n const ctx = {};\n const siteId = parseSiteId(pickHeader(headers, SITE_ID_HEADER));\n if (siteId !== void 0)\n ctx.siteId = siteId;\n const hostname = (_a2 = parseHostname(pickHeader(headers, HOSTNAME_HEADER))) !== null && _a2 !== void 0 ? _a2 : parseHostname(pickHeader(headers, FORWARDED_HOSTNAME_HEADER));\n if (hostname)\n ctx.hostname = hostname;\n return ctx;\n }\n exports2.buildEdgeContextFromHeaders = buildEdgeContextFromHeaders;\n function runWithEdgeContext(headers, fn) {\n const ctx = buildEdgeContextFromHeaders(headers);\n return storage.run(ctx, fn);\n }\n exports2.runWithEdgeContext = runWithEdgeContext;\n function getEdgeContext() {\n var _a2;\n return (_a2 = storage.getStore()) !== null && _a2 !== void 0 ? _a2 : {};\n }\n exports2.getEdgeContext = getEdgeContext;\n function setCacheTags(tags) {\n const store = storage.getStore();\n if (store)\n store.cacheTags = tags;\n }\n exports2.setCacheTags = setCacheTags;\n function getCacheTags() {\n var _a2;\n return (_a2 = storage.getStore()) === null || _a2 === void 0 ? void 0 : _a2.cacheTags;\n }\n exports2.getCacheTags = getCacheTags;\n }\n});\n\n// dist/runtime/build-id.js\nvar require_build_id = __commonJS({\n \"dist/runtime/build-id.js\"(exports2) {\n \"use strict\";\n var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });\n var __importStar = exports2 && exports2.__importStar || function(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) {\n for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n }\n __setModuleDefault(result, mod);\n return result;\n };\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.__setBuildIdForTest = exports2.__resetBuildIdCache = exports2.loadBuildId = void 0;\n var fs = __importStar(require(\"fs\"));\n var path = __importStar(require(\"path\"));\n var cached;\n function loadBuildId() {\n var _a;\n if (cached !== void 0)\n return cached;\n const p = path.join(__dirname, \".next\", \"BUILD_ID\");\n try {\n const v = fs.readFileSync(p, \"utf-8\").trim();\n cached = v || null;\n } catch (err) {\n if ((err === null || err === void 0 ? void 0 : err.code) !== \"ENOENT\") {\n console.warn(`[build-id] BUILD_ID read error ${p}: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n } else {\n console.warn(`[build-id] BUILD_ID not found at ${p}`);\n }\n cached = null;\n }\n return cached;\n }\n exports2.loadBuildId = loadBuildId;\n function __resetBuildIdCache() {\n cached = void 0;\n }\n exports2.__resetBuildIdCache = __resetBuildIdCache;\n function __setBuildIdForTest(v) {\n cached = v;\n }\n exports2.__setBuildIdForTest = __setBuildIdForTest;\n }\n});\n\n// dist/runtime/cdn-purge.js\nvar require_cdn_purge = __commonJS({\n \"dist/runtime/cdn-purge.js\"(exports2) {\n \"use strict\";\n var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() {\n return m[k];\n } };\n }\n Object.defineProperty(o, k2, desc);\n }) : (function(o, m, k, k2) {\n if (k2 === void 0) k2 = k;\n o[k2] = m[k];\n }));\n var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n }) : function(o, v) {\n o[\"default\"] = v;\n });\n var __importStar = exports2 && exports2.__importStar || function(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) {\n for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n }\n __setModuleDefault(result, mod);\n return result;\n };\n Object.defineProperty(exports2, \"__esModule\", { value: true });\n exports2.createCdnPurgeClient = exports2.loadCdnPurgeConfig = void 0;\n var fs = __importStar(require(\"fs\"));\n var path = __importStar(require(\"path\"));\n var gateway_auth_12 = require_gateway_auth();\n var edge_context_12 = require_edge_context();\n var build_id_1 = require_build_id();\n var REFRESH_TIMEOUT_MS = 15e3;\n var URL_BATCH_SIZE = 100;\n var REFRESH_CONCURRENCY = 4;\n var TAG_MANIFEST_FILENAME = \"__pcg_tag_manifest.json\";\n function stripLeadingSlash2(s) {\n return s.replace(/^\\/+/, \"\");\n }\n function ensureLeadingSlash(s) {\n return s.startsWith(\"/\") ? s : `/${s}`;\n }\n function loadCdnPurgeConfig() {\n const base = (0, gateway_auth_12.loadGatewayAuthConfig)();\n if (!base)\n return null;\n return { ...base };\n }\n exports2.loadCdnPurgeConfig = loadCdnPurgeConfig;\n function createCdnPurgeClient(cfg) {\n var _a, _b;\n const buildId = (_a = cfg.buildId) !== null && _a !== void 0 ? _a : (0, build_id_1.loadBuildId)();\n const pathPrefix = buildId ? `${buildId}/` : null;\n const manifestPath = (_b = cfg.manifestPath) !== null && _b !== void 0 ? _b : path.join(__dirname, TAG_MANIFEST_FILENAME);\n let manifestPromise = null;\n async function loadManifest() {\n if (manifestPromise)\n return manifestPromise;\n manifestPromise = (async () => {\n var _a2, _b2, _c, _d;\n const map = /* @__PURE__ */ new Map();\n let raw;\n try {\n raw = await fs.promises.readFile(manifestPath, \"utf-8\");\n } catch (err) {\n if ((err === null || err === void 0 ? void 0 : err.code) !== \"ENOENT\") {\n console.warn(`[cdn-purge] manifest read error ${manifestPath}: ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n }\n return /* @__PURE__ */ new Map();\n }\n let rows;\n try {\n const parsed = JSON.parse(raw);\n rows = Array.isArray(parsed) ? parsed : [];\n } catch (err) {\n console.warn(`[cdn-purge] manifest parse error ${manifestPath}: ${(_b2 = err === null || err === void 0 ? void 0 : err.message) !== null && _b2 !== void 0 ? _b2 : err}`);\n return /* @__PURE__ */ new Map();\n }\n for (const row of rows) {\n const tagPk = (_c = row === null || row === void 0 ? void 0 : row.tag) === null || _c === void 0 ? void 0 : _c.S;\n const pathPk = (_d = row === null || row === void 0 ? void 0 : row.path) === null || _d === void 0 ? void 0 : _d.S;\n if (typeof tagPk !== \"string\" || typeof pathPk !== \"string\")\n continue;\n let tag;\n let p;\n if (pathPrefix) {\n if (!tagPk.startsWith(pathPrefix))\n continue;\n if (!pathPk.startsWith(pathPrefix))\n continue;\n tag = tagPk.slice(pathPrefix.length);\n p = pathPk.slice(pathPrefix.length);\n } else {\n const tIdx = tagPk.indexOf(\"/\");\n const pIdx = pathPk.indexOf(\"/\");\n if (tIdx < 0 || pIdx < 0)\n continue;\n if (tagPk.slice(0, tIdx) !== pathPk.slice(0, pIdx))\n continue;\n tag = tagPk.slice(tIdx + 1);\n p = pathPk.slice(pIdx + 1);\n }\n if (!tag || !p)\n continue;\n let bucket = map.get(tag);\n if (!bucket) {\n bucket = /* @__PURE__ */ new Set();\n map.set(tag, bucket);\n }\n bucket.add(p);\n }\n const result = /* @__PURE__ */ new Map();\n let totalEntries = 0;\n for (const [tag, set] of map) {\n result.set(tag, Array.from(set));\n totalEntries += set.size;\n }\n console.log(`[cdn-purge] manifest loaded: buildId=${buildId !== null && buildId !== void 0 ? buildId : \"(auto)\"} tags=${result.size} entries=${totalEntries} (${manifestPath})`);\n return result;\n })();\n return manifestPromise;\n }\n function expandPathsToUrls(paths, hostname) {\n const normalized = /* @__PURE__ */ new Set();\n for (const p of paths) {\n if (!p)\n continue;\n normalized.add(ensureLeadingSlash(p));\n }\n if (normalized.size === 0)\n return [];\n const urls = /* @__PURE__ */ new Set();\n for (const p of normalized) {\n urls.add(`https://${hostname}${p}`);\n if (buildId) {\n const rel = stripLeadingSlash2(p);\n urls.add(`https://${hostname}/_next/data/${buildId}/${rel || \"index\"}.json`);\n }\n }\n return Array.from(urls);\n }\n async function refreshBatch(urls, hostname, siteId) {\n var _a2;\n const body = {\n hostname,\n siteId,\n urls\n };\n let res;\n try {\n res = await (0, gateway_auth_12.gatewayFetch)(cfg, \"/cache/refresh\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n timeoutMs: REFRESH_TIMEOUT_MS\n });\n } catch (err) {\n console.warn(`[cdn-purge] cache/refresh error (${urls.length} urls): ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n return;\n }\n if (!res.ok) {\n let detail = \"\";\n try {\n detail = (await res.text()).slice(0, 200);\n } catch (_b2) {\n }\n console.warn(`[cdn-purge] cache/refresh failed status=${res.status} urls=${urls.length} ${detail}`);\n return;\n }\n console.log(`[cdn-purge] cache/refresh ok: urls=${urls.length}`);\n }\n async function refreshUrls(allUrls, hostname, siteId) {\n if (allUrls.length === 0)\n return;\n const batches = [];\n for (let i = 0; i < allUrls.length; i += URL_BATCH_SIZE) {\n batches.push(allUrls.slice(i, i + URL_BATCH_SIZE));\n }\n let cursor = 0;\n async function worker() {\n while (cursor < batches.length) {\n const idx = cursor++;\n await refreshBatch(batches[idx], hostname, siteId);\n }\n }\n const workers = Array.from({ length: Math.min(REFRESH_CONCURRENCY, batches.length) }, () => worker());\n await Promise.all(workers);\n }\n function resolveTarget(action) {\n const { hostname, siteId } = (0, edge_context_12.getEdgeContext)();\n if (!hostname || siteId === void 0 || siteId === \"\") {\n console.warn(`[cdn-purge] ${action} skip: edge context missing (hostname=${hostname !== null && hostname !== void 0 ? hostname : \"\\u2205\"} siteId=${siteId !== null && siteId !== void 0 ? siteId : \"\\u2205\"}); \\u8981\\u6C42\\u5165\\u7AD9\\u8BF7\\u6C42\\u5E26 host \\u4E0E x-er-origin-site-id`);\n return null;\n }\n return { hostname, siteId };\n }\n async function purgeByPaths(paths) {\n var _a2;\n try {\n const target = resolveTarget(\"purgeByPaths\");\n if (!target)\n return;\n const urls = expandPathsToUrls(paths, target.hostname);\n console.log(`[cdn-purge] purgeByPaths: input=${paths.length} urls=${urls.length}`);\n await refreshUrls(urls, target.hostname, target.siteId);\n } catch (err) {\n console.warn(`[cdn-purge] purgeByPaths error: ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n }\n }\n async function purgeByTags(tags) {\n var _a2;\n try {\n const uniqueTags = Array.from(new Set(tags.map((t) => typeof t === \"string\" ? t : \"\").map((t) => t.trim()).filter(Boolean)));\n if (uniqueTags.length === 0)\n return;\n const target = resolveTarget(\"purgeByTags\");\n if (!target)\n return;\n const map = await loadManifest();\n const merged = /* @__PURE__ */ new Set();\n for (const t of uniqueTags) {\n const paths = map.get(t);\n if (!paths)\n continue;\n for (const p of paths)\n merged.add(p);\n }\n if (merged.size === 0) {\n console.log(`[cdn-purge] purgeByTags: input=${uniqueTags.length} matched=0 (manifest miss, skip)`);\n return;\n }\n const urls = expandPathsToUrls(Array.from(merged), target.hostname);\n console.log(`[cdn-purge] purgeByTags: input=${uniqueTags.length} matched=${merged.size} urls=${urls.length}`);\n await refreshUrls(urls, target.hostname, target.siteId);\n } catch (err) {\n console.warn(`[cdn-purge] purgeByTags error: ${(_a2 = err === null || err === void 0 ? void 0 : err.message) !== null && _a2 !== void 0 ? _a2 : err}`);\n }\n }\n return { purgeByPaths, purgeByTags };\n }\n exports2.createCdnPurgeClient = createCdnPurgeClient;\n }\n});\n\n// dist/overrides/tagCache/gateway.js\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar gateway_auth_1 = require_gateway_auth();\nvar edge_context_1 = require_edge_context();\nvar cdn_purge_1 = require_cdn_purge();\nvar QUERY_TIMEOUT = 3e3;\nvar WRITE_TIMEOUT = 5e3;\nvar BATCH_SIZE = 200;\nvar PURGE_TIMEOUT = 15e3;\nvar MAX_BATCH_GET_TAGS = 100;\nfunction stripLeadingSlash(s) {\n return s.replace(/^\\/+/, \"\");\n}\nvar GatewayTagCache = class {\n constructor() {\n this.name = \"gateway-tag-cache\";\n this.mode = \"nextMode\";\n this.config = null;\n this.configLoaded = false;\n this.cdnPurgeClient = void 0;\n }\n getConfig() {\n if (!this.configLoaded) {\n this.config = (0, gateway_auth_1.loadGatewayAuthConfig)();\n this.configLoaded = true;\n }\n return this.config;\n }\n /**\n * 拼 TableStore tag 主键:`{version}/{tag}`。\n * version 来自 ESA_CACHE_GW_VERSION,与 OSS Cache Key 使用同一版本维度。\n */\n buildTagKey(config, tag) {\n return `${config.version}/${stripLeadingSlash(tag)}`;\n }\n async getLastRevalidated(tags) {\n const config = this.getConfig();\n if (!config)\n return 0;\n try {\n const rows = await this.batchGetTags(config, tags);\n const now = Date.now();\n let maxRevalidatedAt = 0;\n for (const row of rows) {\n if (row.revalidatedAt !== void 0 && row.revalidatedAt <= now && row.revalidatedAt > maxRevalidatedAt) {\n maxRevalidatedAt = row.revalidatedAt;\n }\n }\n return maxRevalidatedAt;\n } catch (err) {\n console.warn(`[tagCache] getLastRevalidated error: ${err.message}`);\n return 0;\n }\n }\n async hasBeenRevalidated(tags, lastModified) {\n var _a, _b;\n const config = this.getConfig();\n if (!config)\n return false;\n if (tags.length === 0)\n return false;\n try {\n const rows = await this.batchGetTags(config, tags);\n const now = Date.now();\n const lm = lastModified !== null && lastModified !== void 0 ? lastModified : 0;\n for (const row of rows) {\n const eventAt = (_b = (_a = row.revalidatedAt) !== null && _a !== void 0 ? _a : row.stale) !== null && _b !== void 0 ? _b : 0;\n const eventAffectsEntry = eventAt > lm && eventAt <= now;\n if (row.expire !== void 0) {\n if (row.expire <= now && row.expire > lm && eventAffectsEntry) {\n return true;\n }\n continue;\n }\n if (row.stale !== void 0)\n continue;\n if (eventAffectsEntry) {\n return true;\n }\n }\n return false;\n } catch (err) {\n console.warn(`[tagCache] hasBeenRevalidated error: ${err.message}`);\n return false;\n }\n }\n async isStale(tags, lastModified) {\n var _a;\n const config = this.getConfig();\n if (!config)\n return false;\n if (tags.length === 0)\n return false;\n try {\n const rows = await this.batchGetTags(config, tags);\n const lm = lastModified !== null && lastModified !== void 0 ? lastModified : 0;\n const now = Date.now();\n for (const row of rows) {\n if (row.stale === void 0)\n continue;\n const eventAt = (_a = row.revalidatedAt) !== null && _a !== void 0 ? _a : row.stale;\n const eventAffectsEntry = eventAt > lm && eventAt <= now;\n const hasBecomeStale = row.stale <= now;\n const hasNotExpired = row.expire === void 0 || row.expire > now;\n if (eventAffectsEntry && row.stale >= lm && hasBecomeStale && hasNotExpired) {\n return true;\n }\n }\n return false;\n } catch (err) {\n console.warn(`[tagCache] isStale error: ${err.message}`);\n return false;\n }\n }\n async writeTags(tags) {\n if (!tags || tags.length === 0)\n return;\n const config = this.getConfig();\n if (!config)\n return;\n const writeTs = Date.now();\n const rows = tags.map((input) => {\n const tagStr = typeof input === \"string\" ? input : input.tag;\n const stale = typeof input === \"string\" ? void 0 : input.stale;\n const expire = typeof input === \"string\" ? void 0 : input.expire;\n const tagKey = this.buildTagKey(config, tagStr);\n const revalidatedAt = stale !== null && stale !== void 0 ? stale : writeTs;\n const staleStr = stale === void 0 ? \"\\u2205\" : String(stale);\n const expireStr = expire === void 0 ? \"\\u2205\" : String(expire);\n console.log(`[tagCache] writeTags: tag=\"${tagStr}\" key=\"${tagKey}\" revalidatedAt=${revalidatedAt} stale=${staleStr} expire=${expireStr}`);\n const columns = [\n { name: \"revalidatedAt\", value: revalidatedAt }\n ];\n if (stale !== void 0) {\n columns.push({ name: \"stale\", value: stale });\n }\n if (expire !== void 0) {\n columns.push({ name: \"expire\", value: expire });\n }\n return {\n primaryKey: [\n { name: \"app_id\", value: `${config.aliuid}/${config.routinename}` },\n { name: \"tag\", value: tagKey }\n ],\n columns\n };\n });\n await this.batchWrite(config, rows);\n const tagStrs = tags.map((t) => typeof t === \"string\" ? t : t.tag).filter((s) => typeof s === \"string\" && s.length > 0);\n if (tagStrs.length > 0) {\n this.firePurge(config, tagStrs);\n }\n }\n // ---- private methods ----\n async batchGetTags(config, tags) {\n var _a, _b;\n if (tags.length > MAX_BATCH_GET_TAGS) {\n throw new Error(`too many tags in one query: ${tags.length} > ${MAX_BATCH_GET_TAGS} (TableStore BatchGetRow limit)`);\n }\n const tagKeys = tags.map((tag) => this.buildTagKey(config, tag));\n console.log(`[tagCache] batchGetTags: tags=${JSON.stringify(tags)} keys=${JSON.stringify(tagKeys)}`);\n const primaryKeys = tags.map((tag) => [\n { name: \"app_id\", value: `${config.aliuid}/${config.routinename}` },\n { name: \"tag\", value: this.buildTagKey(config, tag) }\n ]);\n const res = await (0, gateway_auth_1.gatewayFetch)(config, \"/table/batch-get-row\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ primaryKeys }),\n timeoutMs: QUERY_TIMEOUT\n });\n if (!res.ok) {\n if (res.status === 401 || res.status === 403) {\n console.error(`[tagCache] batch-get-row rejected (${res.status})`);\n } else {\n console.warn(`[tagCache] batch-get-row failed: status=${res.status}`);\n }\n return [];\n }\n const data = await res.json();\n console.log(`[tagCache] batch-get-row ok: tags=${tags.length} rows=${(_b = (_a = data.rows) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0}`);\n if (!data.rows)\n return [];\n return data.rows.map((row) => {\n var _a2;\n const result = {};\n for (const col of (_a2 = row.columns) !== null && _a2 !== void 0 ? _a2 : []) {\n if (col.name === \"revalidatedAt\" && typeof col.value === \"number\") {\n result.revalidatedAt = col.value;\n } else if (col.name === \"stale\" && typeof col.value === \"number\") {\n result.stale = col.value;\n } else if (col.name === \"expire\" && typeof col.value === \"number\") {\n result.expire = col.value;\n }\n }\n return result;\n });\n }\n async batchWrite(config, rows) {\n if (rows.length === 0)\n return;\n for (let i = 0; i < rows.length; i += BATCH_SIZE) {\n const batch = rows.slice(i, i + BATCH_SIZE);\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, \"/table/batch-write\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ rows: batch }),\n timeoutMs: WRITE_TIMEOUT\n });\n if (res.status === 401 || res.status === 403) {\n console.error(`[tagCache] batch-write rejected (${res.status})`);\n return;\n }\n if (!res.ok) {\n console.warn(`[tagCache] batch-write failed: status=${res.status}`);\n } else {\n console.log(`[tagCache] batch-write ok: rows=${batch.length}`);\n }\n } catch (err) {\n if (err.name === \"AbortError\") {\n console.warn(`[tagCache] batch-write timeout (${WRITE_TIMEOUT}ms)`);\n } else {\n console.warn(`[tagCache] batch-write error: ${err.message}`);\n }\n }\n }\n }\n /**\n * 懒加载 cdn-purge 客户端。返回 null 表示环境变量缺失,降级跳过 purge。\n */\n getCdnPurgeClient() {\n if (this.cdnPurgeClient !== void 0)\n return this.cdnPurgeClient;\n const cfg = (0, cdn_purge_1.loadCdnPurgeConfig)();\n this.cdnPurgeClient = cfg ? (0, cdn_purge_1.createCdnPurgeClient)(cfg) : null;\n return this.cdnPurgeClient;\n }\n /**\n * 根据 PCG_CDN_PURGE_MODE 环境变量选择 purge 策略。\n * - \"path\"(默认):走 manifest 反查 tag→path,按 URL 级别刷新\n * - \"tag\":直接发 cacheTags 数组,由 ESA 原生按 Cache-Tag 刷新\n */\n firePurge(config, tagStrs) {\n const mode = (process.env.PCG_CDN_PURGE_MODE || \"path\").toLowerCase();\n if (mode === \"tag\") {\n this.purgeByCacheTags(config, tagStrs).catch((err) => {\n var _a;\n console.warn(`[tagCache] cacheTags purge failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n });\n } else {\n const purgeClient = this.getCdnPurgeClient();\n if (purgeClient) {\n purgeClient.purgeByTags(tagStrs).catch((err) => {\n var _a;\n console.warn(`[tagCache] path purge failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n });\n }\n }\n }\n /**\n * 调 Gateway /cache/refresh(cacheTags) 触发 ESA PurgeCaches Type=cachetag。\n * hostname / siteId 从当前请求的 edge context 读取,缺失则 skip。\n */\n async purgeByCacheTags(config, tags) {\n var _a;\n const { hostname, siteId } = (0, edge_context_1.getEdgeContext)();\n if (!hostname || siteId === void 0 || siteId === \"\") {\n console.warn(`[tagCache] cacheTags purge skip: edge context missing (hostname=${hostname !== null && hostname !== void 0 ? hostname : \"\\u2205\"} siteId=${siteId !== null && siteId !== void 0 ? siteId : \"\\u2205\"})`);\n return;\n }\n const body = { hostname, siteId, cacheTags: tags };\n try {\n const res = await (0, gateway_auth_1.gatewayFetch)(config, \"/cache/refresh\", {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n timeoutMs: PURGE_TIMEOUT\n });\n if (!res.ok) {\n let detail = \"\";\n try {\n detail = (await res.text()).slice(0, 200);\n } catch (_b) {\n }\n console.warn(`[tagCache] cacheTags purge failed: status=${res.status} tags=${tags.length} ${detail}`);\n return;\n }\n console.log(`[tagCache] cacheTags purge ok: tags=${tags.length}`);\n } catch (err) {\n console.warn(`[tagCache] cacheTags purge error: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);\n }\n }\n};\nexports.default = GatewayTagCache;\n",
|
|
7
7
|
};
|