@edgeone/nuxt-pages
Version:
A professional deployment package that seamlessly deploys your Nuxt 3/4 applications to Tencent Cloud EdgeOne platform with optimized performance and intelligent caching.
1,411 lines (1,372 loc) • 47.7 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name2 in all)
__defProp(target, name2, { get: all[name2], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/run/handlers/cache.cts
var cache_exports = {};
__export(cache_exports, {
EdgeoneCacheHandler: () => EdgeoneCacheHandler,
default: () => cache_default
});
module.exports = __toCommonJS(cache_exports);
var import_node_buffer = require("node:buffer");
// src/shared/cache-types.cts
var isCachedPageValue = (value) => value.kind === "PAGE" || value.kind === "PAGES";
var isCachedRouteValue = (value) => value.kind === "ROUTE" || value.kind === "APP_ROUTE";
// node_modules/lru-cache/dist/esm/index.js
var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
var PROCESS = typeof process === "object" && !!process ? process : {};
var emitWarning = (msg, type, code, fn) => {
typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
};
var AC = globalThis.AbortController;
var AS = globalThis.AbortSignal;
if (typeof AC === "undefined") {
AS = class AbortSignal {
onabort;
_onabort = [];
reason;
aborted = false;
addEventListener(_, fn) {
this._onabort.push(fn);
}
};
AC = class AbortController {
constructor() {
warnACPolyfill();
}
signal = new AS();
abort(reason) {
if (this.signal.aborted)
return;
this.signal.reason = reason;
this.signal.aborted = true;
for (const fn of this.signal._onabort) {
fn(reason);
}
this.signal.onabort?.(reason);
}
};
let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
const warnACPolyfill = () => {
if (!printACPolyfillWarning)
return;
printACPolyfillWarning = false;
emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
};
}
var TYPE = Symbol("type");
// src/run/handlers/request-context.cts
var import_node_async_hooks = require("node:async_hooks");
// node_modules/@netlify/functions/dist/internal.js
var import_process = require("process");
var systemLogTag = "__nfSystemLog";
var serializeError = (error) => {
const cause = error?.cause instanceof Error ? serializeError(error.cause) : error.cause;
return {
error: error.message,
error_cause: cause,
error_stack: error.stack
};
};
var SystemLogger = class _SystemLogger {
fields;
logLevel;
constructor(fields = {}, logLevel = 2) {
this.fields = fields;
this.logLevel = logLevel;
}
doLog(logger, message) {
if (import_process.env.NETLIFY_DEV && !import_process.env.NETLIFY_ENABLE_SYSTEM_LOGGING) {
return;
}
logger(systemLogTag, JSON.stringify({ msg: message, fields: this.fields }));
}
log(message) {
if (this.logLevel > 2) {
return;
}
this.doLog(console.log, message);
}
debug(message) {
if (this.logLevel > 1) {
return;
}
this.doLog(console.debug, message);
}
error(message) {
if (this.logLevel > 3) {
return;
}
this.doLog(console.error, message);
}
withLogLevel(level) {
return new _SystemLogger(this.fields, level);
}
withFields(fields) {
return new _SystemLogger(
{
...this.fields,
...fields
},
this.logLevel
);
}
withError(error) {
const fields = error instanceof Error ? serializeError(error) : { error };
return this.withFields(fields);
}
};
var systemLogger = new SystemLogger();
// src/run/handlers/request-context.cts
var REQUEST_CONTEXT_GLOBAL_KEY = Symbol.for("nf-request-context-async-local-storage");
var REQUEST_COUNTER_KEY = Symbol.for("nf-request-counter");
var extendedGlobalThis = globalThis;
var requestContextAsyncLocalStorage;
function getRequestContextAsyncLocalStorage() {
if (requestContextAsyncLocalStorage) {
return requestContextAsyncLocalStorage;
}
if (extendedGlobalThis[REQUEST_CONTEXT_GLOBAL_KEY]) {
return extendedGlobalThis[REQUEST_CONTEXT_GLOBAL_KEY];
}
const storage = new import_node_async_hooks.AsyncLocalStorage();
requestContextAsyncLocalStorage = storage;
extendedGlobalThis[REQUEST_CONTEXT_GLOBAL_KEY] = storage;
return storage;
}
var getRequestContext = () => getRequestContextAsyncLocalStorage().getStore();
function getLogger() {
return getRequestContext()?.logger ?? systemLogger;
}
// src/run/storage/request-scoped-in-memory-cache.cts
var NullValue = Symbol.for("null-value");
var IN_MEMORY_CACHE_MAX_SIZE = Symbol.for("nf-in-memory-cache-max-size");
var IN_MEMORY_LRU_CACHE = Symbol.for("nf-in-memory-lru-cache");
var DEFAULT_FALLBACK_MAX_SIZE = 50 * 1024 * 1024;
// src/run/storage/regional-blob-store.cts
var FETCH_BEFORE_NUXT_PATCHED_IT = Symbol.for("nf-not-patched-fetch");
function attemptToGetOriginalFetch(fetch2) {
return fetch2._nuxtOriginalFetch ?? fetch2;
}
function forceOptOutOfUsingDataCache(fetch2) {
return (input, init) => {
return fetch2(input, {
...init,
next: {
...init?.next,
// setting next.internal = true should prevent from trying to use data cache
// https://github.com/vercel/next.js/blob/fa214c74c1d8023098c0e94e57f917ef9f1afd1a/packages/next/src/server/lib/patch-fetch.ts#L174
// https://github.com/vercel/next.js/blob/fa214c74c1d8023098c0e94e57f917ef9f1afd1a/packages/next/src/server/lib/patch-fetch.ts#L210-L213
// this is last line of defense in case we didn't manage to get unpatched fetch that will not affect
// fetch if it's unpatched so it should be safe to apply always if we aren't sure if we use patched fetch
// @ts-expect-error - this is an internal field that Next.js doesn't add to its global
// type overrides for RequestInit type (like `next.revalidate` or `next.tags`)
internal: true
}
});
};
}
var fetchBeforeNuxtPatchedItFallback = forceOptOutOfUsingDataCache(
attemptToGetOriginalFetch(globalThis.fetch)
);
// src/run/storage/storage.cts
var getMemoizedKeyValueStoreBackedByRegionalBlobStore = (...args) => {
};
// package.json
var name = "@edgeone/nuxt-pages";
var version = "1.0.6";
// src/run/handlers/tags-handler.cts
var purgeCacheUserAgent = `${name}@${version}`;
function getCacheTagsFromTagOrTags(tagOrTags) {
return (Array.isArray(tagOrTags) ? tagOrTags : [tagOrTags]).flatMap((tag) => tag.split(/,|%2c/gi)).filter(Boolean);
}
async function purgeEdgeCache(tagOrTags) {
const tags = getCacheTagsFromTagOrTags(tagOrTags).map((tag) => {
return tag.replace(/^_N_T_/, "").replace(/\/page|\/layout$/, "");
});
if (tags.length === 0) {
return Promise.resolve();
}
getLogger().debug(`[NuxtRuntime] Purging CDN cache for: [${tags.join(", ")}]`);
const baseUrl = process.env.IS_MAINLAND === "true" ? "https://pages-api.cloud.tencent.com" : "https://pages-api.edgeone.ai";
const token = process.env.PURGE_TOKEN;
const requestBody = {
path: [...tags]
};
const res = await fetch(`${baseUrl}/eo/purge`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify(requestBody)
});
const data = await res.json();
if (data?.error) {
console.log(`Failed to purge CDN cache: ${data?.error.message}`);
}
}
async function doRevalidateTagAndPurgeEdgeCache(tags) {
getLogger().withFields({ tags }).debug("doRevalidateTagAndPurgeEdgeCache");
if (tags.length === 0) {
return;
}
const tagManifest = {
revalidatedAt: Date.now()
};
await purgeEdgeCache(tags);
}
function markTagsAsStaleAndPurgeEdgeCache(tagOrTags) {
const tags = getCacheTagsFromTagOrTags(tagOrTags);
const revalidateTagPromise = doRevalidateTagAndPurgeEdgeCache(tags);
const requestContext = getRequestContext();
if (requestContext) {
requestContext.trackBackgroundWork(revalidateTagPromise);
}
return revalidateTagPromise;
}
// node_modules/@opentelemetry/api/build/esm/platform/node/globalThis.js
var _globalThis = typeof globalThis === "object" ? globalThis : global;
// node_modules/@opentelemetry/api/build/esm/version.js
var VERSION = "1.9.0";
// node_modules/@opentelemetry/api/build/esm/internal/semver.js
var re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
function _makeCompatibilityCheck(ownVersion) {
var acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);
var rejectedVersions = /* @__PURE__ */ new Set();
var myVersionMatch = ownVersion.match(re);
if (!myVersionMatch) {
return function() {
return false;
};
}
var ownVersionParsed = {
major: +myVersionMatch[1],
minor: +myVersionMatch[2],
patch: +myVersionMatch[3],
prerelease: myVersionMatch[4]
};
if (ownVersionParsed.prerelease != null) {
return function isExactmatch(globalVersion) {
return globalVersion === ownVersion;
};
}
function _reject(v) {
rejectedVersions.add(v);
return false;
}
function _accept(v) {
acceptedVersions.add(v);
return true;
}
return function isCompatible2(globalVersion) {
if (acceptedVersions.has(globalVersion)) {
return true;
}
if (rejectedVersions.has(globalVersion)) {
return false;
}
var globalVersionMatch = globalVersion.match(re);
if (!globalVersionMatch) {
return _reject(globalVersion);
}
var globalVersionParsed = {
major: +globalVersionMatch[1],
minor: +globalVersionMatch[2],
patch: +globalVersionMatch[3],
prerelease: globalVersionMatch[4]
};
if (globalVersionParsed.prerelease != null) {
return _reject(globalVersion);
}
if (ownVersionParsed.major !== globalVersionParsed.major) {
return _reject(globalVersion);
}
if (ownVersionParsed.major === 0) {
if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) {
return _accept(globalVersion);
}
return _reject(globalVersion);
}
if (ownVersionParsed.minor <= globalVersionParsed.minor) {
return _accept(globalVersion);
}
return _reject(globalVersion);
};
}
var isCompatible = _makeCompatibilityCheck(VERSION);
// node_modules/@opentelemetry/api/build/esm/internal/global-utils.js
var major = VERSION.split(".")[0];
var GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for("opentelemetry.js.api." + major);
var _global = _globalThis;
function registerGlobal(type, instance, diag, allowOverride) {
var _a;
if (allowOverride === void 0) {
allowOverride = false;
}
var api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : {
version: VERSION
};
if (!allowOverride && api[type]) {
var err = new Error("@opentelemetry/api: Attempted duplicate registration of API: " + type);
diag.error(err.stack || err.message);
return false;
}
if (api.version !== VERSION) {
var err = new Error("@opentelemetry/api: Registration of version v" + api.version + " for " + type + " does not match previously registered API v" + VERSION);
diag.error(err.stack || err.message);
return false;
}
api[type] = instance;
diag.debug("@opentelemetry/api: Registered a global for " + type + " v" + VERSION + ".");
return true;
}
function getGlobal(type) {
var _a, _b;
var globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
if (!globalVersion || !isCompatible(globalVersion)) {
return;
}
return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
}
function unregisterGlobal(type, diag) {
diag.debug("@opentelemetry/api: Unregistering a global for " + type + " v" + VERSION + ".");
var api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
if (api) {
delete api[type];
}
}
// node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js
var __read = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray = function(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var DiagComponentLogger = (
/** @class */
(function() {
function DiagComponentLogger2(props) {
this._namespace = props.namespace || "DiagComponentLogger";
}
DiagComponentLogger2.prototype.debug = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return logProxy("debug", this._namespace, args);
};
DiagComponentLogger2.prototype.error = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return logProxy("error", this._namespace, args);
};
DiagComponentLogger2.prototype.info = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return logProxy("info", this._namespace, args);
};
DiagComponentLogger2.prototype.warn = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return logProxy("warn", this._namespace, args);
};
DiagComponentLogger2.prototype.verbose = function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return logProxy("verbose", this._namespace, args);
};
return DiagComponentLogger2;
})()
);
function logProxy(funcName, namespace, args) {
var logger = getGlobal("diag");
if (!logger) {
return;
}
args.unshift(namespace);
return logger[funcName].apply(logger, __spreadArray([], __read(args), false));
}
// node_modules/@opentelemetry/api/build/esm/diag/types.js
var DiagLogLevel;
(function(DiagLogLevel2) {
DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE";
DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR";
DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN";
DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO";
DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG";
DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE";
DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL";
})(DiagLogLevel || (DiagLogLevel = {}));
// node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js
function createLogLevelDiagLogger(maxLevel, logger) {
if (maxLevel < DiagLogLevel.NONE) {
maxLevel = DiagLogLevel.NONE;
} else if (maxLevel > DiagLogLevel.ALL) {
maxLevel = DiagLogLevel.ALL;
}
logger = logger || {};
function _filterFunc(funcName, theLevel) {
var theFunc = logger[funcName];
if (typeof theFunc === "function" && maxLevel >= theLevel) {
return theFunc.bind(logger);
}
return function() {
};
}
return {
error: _filterFunc("error", DiagLogLevel.ERROR),
warn: _filterFunc("warn", DiagLogLevel.WARN),
info: _filterFunc("info", DiagLogLevel.INFO),
debug: _filterFunc("debug", DiagLogLevel.DEBUG),
verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
};
}
// node_modules/@opentelemetry/api/build/esm/api/diag.js
var __read2 = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray2 = function(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var API_NAME = "diag";
var DiagAPI = (
/** @class */
(function() {
function DiagAPI2() {
function _logProxy(funcName) {
return function() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var logger = getGlobal("diag");
if (!logger)
return;
return logger[funcName].apply(logger, __spreadArray2([], __read2(args), false));
};
}
var self = this;
var setLogger = function(logger, optionsOrLogLevel) {
var _a, _b, _c;
if (optionsOrLogLevel === void 0) {
optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
}
if (logger === self) {
var err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
return false;
}
if (typeof optionsOrLogLevel === "number") {
optionsOrLogLevel = {
logLevel: optionsOrLogLevel
};
}
var oldLogger = getGlobal("diag");
var newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
var stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
oldLogger.warn("Current logger will be overwritten from " + stack);
newLogger.warn("Current logger will overwrite one already registered from " + stack);
}
return registerGlobal("diag", newLogger, self, true);
};
self.setLogger = setLogger;
self.disable = function() {
unregisterGlobal(API_NAME, self);
};
self.createComponentLogger = function(options) {
return new DiagComponentLogger(options);
};
self.verbose = _logProxy("verbose");
self.debug = _logProxy("debug");
self.info = _logProxy("info");
self.warn = _logProxy("warn");
self.error = _logProxy("error");
}
DiagAPI2.instance = function() {
if (!this._instance) {
this._instance = new DiagAPI2();
}
return this._instance;
};
return DiagAPI2;
})()
);
// node_modules/@opentelemetry/api/build/esm/context/context.js
function createContextKey(description) {
return Symbol.for(description);
}
var BaseContext = (
/** @class */
/* @__PURE__ */ (function() {
function BaseContext2(parentContext) {
var self = this;
self._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();
self.getValue = function(key) {
return self._currentContext.get(key);
};
self.setValue = function(key, value) {
var context2 = new BaseContext2(self._currentContext);
context2._currentContext.set(key, value);
return context2;
};
self.deleteValue = function(key) {
var context2 = new BaseContext2(self._currentContext);
context2._currentContext.delete(key);
return context2;
};
}
return BaseContext2;
})()
);
var ROOT_CONTEXT = new BaseContext();
// node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js
var __read3 = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray3 = function(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var NoopContextManager = (
/** @class */
(function() {
function NoopContextManager2() {
}
NoopContextManager2.prototype.active = function() {
return ROOT_CONTEXT;
};
NoopContextManager2.prototype.with = function(_context, fn, thisArg) {
var args = [];
for (var _i = 3; _i < arguments.length; _i++) {
args[_i - 3] = arguments[_i];
}
return fn.call.apply(fn, __spreadArray3([thisArg], __read3(args), false));
};
NoopContextManager2.prototype.bind = function(_context, target) {
return target;
};
NoopContextManager2.prototype.enable = function() {
return this;
};
NoopContextManager2.prototype.disable = function() {
return this;
};
return NoopContextManager2;
})()
);
// node_modules/@opentelemetry/api/build/esm/api/context.js
var __read4 = function(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
};
var __spreadArray4 = function(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var API_NAME2 = "context";
var NOOP_CONTEXT_MANAGER = new NoopContextManager();
var ContextAPI = (
/** @class */
(function() {
function ContextAPI2() {
}
ContextAPI2.getInstance = function() {
if (!this._instance) {
this._instance = new ContextAPI2();
}
return this._instance;
};
ContextAPI2.prototype.setGlobalContextManager = function(contextManager) {
return registerGlobal(API_NAME2, contextManager, DiagAPI.instance());
};
ContextAPI2.prototype.active = function() {
return this._getContextManager().active();
};
ContextAPI2.prototype.with = function(context2, fn, thisArg) {
var _a;
var args = [];
for (var _i = 3; _i < arguments.length; _i++) {
args[_i - 3] = arguments[_i];
}
return (_a = this._getContextManager()).with.apply(_a, __spreadArray4([context2, fn, thisArg], __read4(args), false));
};
ContextAPI2.prototype.bind = function(context2, target) {
return this._getContextManager().bind(context2, target);
};
ContextAPI2.prototype._getContextManager = function() {
return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER;
};
ContextAPI2.prototype.disable = function() {
this._getContextManager().disable();
unregisterGlobal(API_NAME2, DiagAPI.instance());
};
return ContextAPI2;
})()
);
// node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js
var TraceFlags;
(function(TraceFlags2) {
TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE";
TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED";
})(TraceFlags || (TraceFlags = {}));
// node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js
var INVALID_SPANID = "0000000000000000";
var INVALID_TRACEID = "00000000000000000000000000000000";
var INVALID_SPAN_CONTEXT = {
traceId: INVALID_TRACEID,
spanId: INVALID_SPANID,
traceFlags: TraceFlags.NONE
};
// node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js
var NonRecordingSpan = (
/** @class */
(function() {
function NonRecordingSpan2(_spanContext) {
if (_spanContext === void 0) {
_spanContext = INVALID_SPAN_CONTEXT;
}
this._spanContext = _spanContext;
}
NonRecordingSpan2.prototype.spanContext = function() {
return this._spanContext;
};
NonRecordingSpan2.prototype.setAttribute = function(_key, _value) {
return this;
};
NonRecordingSpan2.prototype.setAttributes = function(_attributes) {
return this;
};
NonRecordingSpan2.prototype.addEvent = function(_name, _attributes) {
return this;
};
NonRecordingSpan2.prototype.addLink = function(_link) {
return this;
};
NonRecordingSpan2.prototype.addLinks = function(_links) {
return this;
};
NonRecordingSpan2.prototype.setStatus = function(_status) {
return this;
};
NonRecordingSpan2.prototype.updateName = function(_name) {
return this;
};
NonRecordingSpan2.prototype.end = function(_endTime) {
};
NonRecordingSpan2.prototype.isRecording = function() {
return false;
};
NonRecordingSpan2.prototype.recordException = function(_exception, _time) {
};
return NonRecordingSpan2;
})()
);
// node_modules/@opentelemetry/api/build/esm/trace/context-utils.js
var SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
function getSpan(context2) {
return context2.getValue(SPAN_KEY) || void 0;
}
function getActiveSpan() {
return getSpan(ContextAPI.getInstance().active());
}
function setSpan(context2, span) {
return context2.setValue(SPAN_KEY, span);
}
function deleteSpan(context2) {
return context2.deleteValue(SPAN_KEY);
}
function setSpanContext(context2, spanContext) {
return setSpan(context2, new NonRecordingSpan(spanContext));
}
function getSpanContext(context2) {
var _a;
return (_a = getSpan(context2)) === null || _a === void 0 ? void 0 : _a.spanContext();
}
// node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js
var VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i;
var VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i;
function isValidTraceId(traceId) {
return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID;
}
function isValidSpanId(spanId) {
return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID;
}
function isSpanContextValid(spanContext) {
return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);
}
function wrapSpanContext(spanContext) {
return new NonRecordingSpan(spanContext);
}
// node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js
var contextApi = ContextAPI.getInstance();
var NoopTracer = (
/** @class */
(function() {
function NoopTracer2() {
}
NoopTracer2.prototype.startSpan = function(name2, options, context2) {
if (context2 === void 0) {
context2 = contextApi.active();
}
var root = Boolean(options === null || options === void 0 ? void 0 : options.root);
if (root) {
return new NonRecordingSpan();
}
var parentFromContext = context2 && getSpanContext(context2);
if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) {
return new NonRecordingSpan(parentFromContext);
} else {
return new NonRecordingSpan();
}
};
NoopTracer2.prototype.startActiveSpan = function(name2, arg2, arg3, arg4) {
var opts;
var ctx;
var fn;
if (arguments.length < 2) {
return;
} else if (arguments.length === 2) {
fn = arg2;
} else if (arguments.length === 3) {
opts = arg2;
fn = arg3;
} else {
opts = arg2;
ctx = arg3;
fn = arg4;
}
var parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
var span = this.startSpan(name2, opts, parentContext);
var contextWithSpanSet = setSpan(parentContext, span);
return contextApi.with(contextWithSpanSet, fn, void 0, span);
};
return NoopTracer2;
})()
);
function isSpanContext(spanContext) {
return typeof spanContext === "object" && typeof spanContext["spanId"] === "string" && typeof spanContext["traceId"] === "string" && typeof spanContext["traceFlags"] === "number";
}
// node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js
var NOOP_TRACER = new NoopTracer();
var ProxyTracer = (
/** @class */
(function() {
function ProxyTracer2(_provider, name2, version2, options) {
this._provider = _provider;
this.name = name2;
this.version = version2;
this.options = options;
}
ProxyTracer2.prototype.startSpan = function(name2, options, context2) {
return this._getTracer().startSpan(name2, options, context2);
};
ProxyTracer2.prototype.startActiveSpan = function(_name, _options, _context, _fn) {
var tracer2 = this._getTracer();
return Reflect.apply(tracer2.startActiveSpan, tracer2, arguments);
};
ProxyTracer2.prototype._getTracer = function() {
if (this._delegate) {
return this._delegate;
}
var tracer2 = this._provider.getDelegateTracer(this.name, this.version, this.options);
if (!tracer2) {
return NOOP_TRACER;
}
this._delegate = tracer2;
return this._delegate;
};
return ProxyTracer2;
})()
);
// node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js
var NoopTracerProvider = (
/** @class */
(function() {
function NoopTracerProvider2() {
}
NoopTracerProvider2.prototype.getTracer = function(_name, _version, _options) {
return new NoopTracer();
};
return NoopTracerProvider2;
})()
);
// node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js
var NOOP_TRACER_PROVIDER = new NoopTracerProvider();
var ProxyTracerProvider = (
/** @class */
(function() {
function ProxyTracerProvider2() {
}
ProxyTracerProvider2.prototype.getTracer = function(name2, version2, options) {
var _a;
return (_a = this.getDelegateTracer(name2, version2, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name2, version2, options);
};
ProxyTracerProvider2.prototype.getDelegate = function() {
var _a;
return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
};
ProxyTracerProvider2.prototype.setDelegate = function(delegate) {
this._delegate = delegate;
};
ProxyTracerProvider2.prototype.getDelegateTracer = function(name2, version2, options) {
var _a;
return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name2, version2, options);
};
return ProxyTracerProvider2;
})()
);
// node_modules/@opentelemetry/api/build/esm/trace/status.js
var SpanStatusCode;
(function(SpanStatusCode2) {
SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET";
SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK";
SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR";
})(SpanStatusCode || (SpanStatusCode = {}));
// node_modules/@opentelemetry/api/build/esm/context-api.js
var context = ContextAPI.getInstance();
// node_modules/@opentelemetry/api/build/esm/api/trace.js
var API_NAME3 = "trace";
var TraceAPI = (
/** @class */
(function() {
function TraceAPI2() {
this._proxyTracerProvider = new ProxyTracerProvider();
this.wrapSpanContext = wrapSpanContext;
this.isSpanContextValid = isSpanContextValid;
this.deleteSpan = deleteSpan;
this.getSpan = getSpan;
this.getActiveSpan = getActiveSpan;
this.getSpanContext = getSpanContext;
this.setSpan = setSpan;
this.setSpanContext = setSpanContext;
}
TraceAPI2.getInstance = function() {
if (!this._instance) {
this._instance = new TraceAPI2();
}
return this._instance;
};
TraceAPI2.prototype.setGlobalTracerProvider = function(provider) {
var success = registerGlobal(API_NAME3, this._proxyTracerProvider, DiagAPI.instance());
if (success) {
this._proxyTracerProvider.setDelegate(provider);
}
return success;
};
TraceAPI2.prototype.getTracerProvider = function() {
return getGlobal(API_NAME3) || this._proxyTracerProvider;
};
TraceAPI2.prototype.getTracer = function(name2, version2) {
return this.getTracerProvider().getTracer(name2, version2);
};
TraceAPI2.prototype.disable = function() {
unregisterGlobal(API_NAME3, DiagAPI.instance());
this._proxyTracerProvider = new ProxyTracerProvider();
};
return TraceAPI2;
})()
);
// node_modules/@opentelemetry/api/build/esm/trace-api.js
var trace = TraceAPI.getInstance();
// node_modules/@opentelemetry/api/build/esm/experimental/trace/SugaredTracer.js
var defaultOnException = function(e, span) {
span.recordException(e);
span.setStatus({
code: SpanStatusCode.ERROR
});
};
function wrapTracer(tracer2) {
return new SugaredTracer(tracer2);
}
var SugaredTracer = (
/** @class */
(function() {
function SugaredTracer2(tracer2) {
this._tracer = tracer2;
this.startSpan = tracer2.startSpan.bind(this._tracer);
this.startActiveSpan = tracer2.startActiveSpan.bind(this._tracer);
}
SugaredTracer2.prototype.withActiveSpan = function(name2, arg2, arg3, arg4) {
var _a = massageParams(arg2, arg3, arg4), opts = _a.opts, ctx = _a.ctx, fn = _a.fn;
return this._tracer.startActiveSpan(name2, opts, ctx, function(span) {
return handleFn(span, opts, fn);
});
};
SugaredTracer2.prototype.withSpan = function(name2, arg2, arg3, arg4) {
var _a = massageParams(arg2, arg3, arg4), opts = _a.opts, ctx = _a.ctx, fn = _a.fn;
var span = this._tracer.startSpan(name2, opts, ctx);
return handleFn(span, opts, fn);
};
return SugaredTracer2;
})()
);
function massageParams(arg, arg2, arg3) {
var opts;
var ctx;
var fn;
if (!arg2 && !arg3) {
fn = arg;
} else if (!arg3) {
opts = arg;
fn = arg2;
} else {
opts = arg;
ctx = arg2;
fn = arg3;
}
opts = opts !== null && opts !== void 0 ? opts : {};
ctx = ctx !== null && ctx !== void 0 ? ctx : context.active();
return { opts, ctx, fn };
}
function handleFn(span, opts, fn) {
var _a;
var onException = (_a = opts.onException) !== null && _a !== void 0 ? _a : defaultOnException;
var errorHandler = function(e) {
onException(e, span);
span.end();
throw e;
};
try {
var ret = fn(span);
if (typeof (ret === null || ret === void 0 ? void 0 : ret.then) === "function") {
return ret.then(function(val) {
span.end();
return val;
}, errorHandler);
}
span.end();
return ret;
} catch (e) {
throw errorHandler(e);
}
}
// src/run/handlers/tracer.cts
var spanMeta = /* @__PURE__ */ new WeakMap();
var spanCounter = /* @__PURE__ */ new WeakMap();
function spanHook(span) {
const originalEnd = span.end.bind(span);
span.end = (endTime) => {
originalEnd(endTime);
const meta = spanMeta.get(span);
if (meta) {
const requestContext = getRequestContext();
if (requestContext?.captureServerTiming) {
const duration = (typeof endTime === "number" ? endTime : performance.now()) - meta.start;
const serverTiming = requestContext.serverTiming ?? "";
const currentRequestSpanCounter = spanCounter.get(requestContext) ?? 1;
requestContext.serverTiming = `${serverTiming}${serverTiming.length === 0 ? "" : ", "}s${currentRequestSpanCounter};dur=${duration};desc="${meta.name}"`;
spanCounter.set(requestContext, currentRequestSpanCounter + 1);
}
}
spanMeta.delete(span);
};
return span;
}
var tracer;
function getTracer() {
if (!tracer) {
const baseTracer = trace.getTracer("Nuxt Runtime");
const startSpan = baseTracer.startSpan.bind(baseTracer);
baseTracer.startSpan = (...args) => {
const span = startSpan(...args);
spanMeta.set(span, { start: performance.now(), name: args[0] });
return spanHook(span);
};
const startActiveSpan = baseTracer.startActiveSpan.bind(baseTracer);
baseTracer.startActiveSpan = (...args) => {
const [name2, ...restOfArgs] = args;
const augmentedArgs = restOfArgs.map((arg) => {
if (typeof arg === "function") {
return (span) => {
spanMeta.set(span, { start: performance.now(), name: args[0] });
spanHook(span);
return arg(span);
};
}
return arg;
});
return startActiveSpan(name2, ...augmentedArgs);
};
tracer = wrapTracer(baseTracer);
}
return tracer;
}
function recordWarning(warning, span) {
const spanToRecordWarningOn = span ?? trace.getActiveSpan();
if (!spanToRecordWarningOn) {
return;
}
spanToRecordWarningOn.recordException(warning);
spanToRecordWarningOn.setAttributes({
severity: "alert",
warning: true
});
}
// src/run/handlers/cache.cts
var CACHE_TAGS_HEADER = "x-next-cache-tags";
var EdgeoneCacheHandler = class {
options;
revalidatedTags;
cacheStore;
tracer = getTracer();
constructor(options) {
this.options = options;
this.revalidatedTags = options.revalidatedTags;
this.cacheStore = getMemoizedKeyValueStoreBackedByRegionalBlobStore({ consistency: "strong" });
}
getTTL(blob) {
if (blob.value?.kind === "FETCH" || blob.value?.kind === "ROUTE" || blob.value?.kind === "APP_ROUTE" || blob.value?.kind === "PAGE" || blob.value?.kind === "PAGES" || blob.value?.kind === "APP_PAGE") {
const { revalidate } = blob.value;
if (typeof revalidate === "number") {
const revalidateAfter = revalidate * 1e3 + blob.lastModified;
return (revalidateAfter - Date.now()) / 1e3;
}
if (revalidate === false) {
return "PERMANENT";
}
}
return "NOT SET";
}
captureResponseCacheLastModified(cacheValue, key, getCacheKeySpan) {
if (cacheValue.value?.kind === "FETCH") {
return;
}
const requestContext = getRequestContext();
if (!requestContext) {
recordWarning(new Error("CacheHandler was called without a request context"), getCacheKeySpan);
return;
}
if (requestContext.responseCacheKey && requestContext.responseCacheKey !== key) {
requestContext.responseCacheGetLastModified = void 0;
recordWarning(
new Error(
`Multiple response cache keys used in single request: ["${requestContext.responseCacheKey}, "${key}"]`
),
getCacheKeySpan
);
return;
}
requestContext.responseCacheKey = key;
if (cacheValue.lastModified) {
requestContext.responseCacheGetLastModified = cacheValue.lastModified;
}
}
captureRouteRevalidateAndRemoveFromObject(cacheValue) {
const { revalidate, ...restOfRouteValue } = cacheValue;
const requestContext = getRequestContext();
if (requestContext) {
requestContext.routeHandlerRevalidate = revalidate;
}
return restOfRouteValue;
}
captureCacheTags(cacheValue, key) {
const requestContext = getRequestContext();
if (!requestContext) {
return;
}
if (requestContext.responseCacheTags) {
return;
}
if (!cacheValue) {
const cacheTags = [`_N_T_${key === "/index" ? "/" : encodeURI(key)}`];
requestContext.responseCacheTags = cacheTags;
return;
}
if (cacheValue.kind === "PAGE" || cacheValue.kind === "PAGES" || cacheValue.kind === "APP_PAGE" || cacheValue.kind === "ROUTE" || cacheValue.kind === "APP_ROUTE") {
if (cacheValue.headers?.[CACHE_TAGS_HEADER]) {
const cacheTags = cacheValue.headers[CACHE_TAGS_HEADER].split(/,|%2c/gi);
requestContext.responseCacheTags = cacheTags;
} else if ((cacheValue.kind === "PAGE" || cacheValue.kind === "PAGES") && typeof cacheValue.pageData === "object") {
const cacheTags = [`_N_T_${key === "/index" ? "/" : encodeURI(key)}`];
requestContext.responseCacheTags = cacheTags;
}
}
}
async get(...args) {
return this.tracer.withActiveSpan("get cache key", async (span) => {
const [key, context2 = {}] = args;
getLogger();
span.setAttributes({ key });
const blob = null;
if (!blob) {
span.addEvent("Cache miss", { key });
return null;
}
const ttl = this.getTTL(blob);
if (getRequestContext()?.isBackgroundRevalidation && typeof ttl === "number" && ttl < 0) {
span.addEvent("Discarding stale entry due to SWR background revalidation request", {
key,
ttl
});
getLogger().withFields({
ttl,
key
});
return null;
}
const staleByTags = await this.checkCacheEntryStaleByTags(
blob,
context2.tags,
context2.softTags
);
if (staleByTags) {
span.addEvent("Stale", { staleByTags, key, ttl });
return null;
}
this.captureResponseCacheLastModified(blob, key, span);
const isDataRequest = Boolean(context2.fetchUrl);
if (!isDataRequest) {
this.captureCacheTags(blob.value, key);
}
switch (blob.value?.kind) {
case "FETCH":
span.addEvent("FETCH", {
lastModified: blob.lastModified,
revalidate: context2.revalidate,
ttl
});
return {
lastModified: blob.lastModified,
value: blob.value
};
case "ROUTE":
case "APP_ROUTE": {
span.addEvent(blob.value?.kind, {
lastModified: blob.lastModified,
status: blob.value.status,
revalidate: blob.value.revalidate,
ttl
});
const valueWithoutRevalidate = this.captureRouteRevalidateAndRemoveFromObject(blob.value);
return {
lastModified: blob.lastModified,
value: {
...valueWithoutRevalidate,
body: import_node_buffer.Buffer.from(valueWithoutRevalidate.body, "base64")
}
};
}
case "PAGE":
case "PAGES": {
const { revalidate, ...restOfPageValue } = blob.value;
const requestContext = getRequestContext();
if (requestContext) {
requestContext.pageHandlerRevalidate = revalidate;
}
span.addEvent(blob.value?.kind, { lastModified: blob.lastModified, revalidate, ttl });
return {
lastModified: blob.lastModified,
value: restOfPageValue
};
}
case "APP_PAGE": {
const requestContext = getRequestContext();
if (requestContext && blob.value?.kind === "APP_PAGE") {
requestContext.isCacheableAppPage = true;
}
const { revalidate, rscData, ...restOfPageValue } = blob.value;
span.addEvent(blob.value?.kind, { lastModified: blob.lastModified, revalidate, ttl });
return {
lastModified: blob.lastModified,
value: {
...restOfPageValue,
rscData: rscData ? import_node_buffer.Buffer.from(rscData, "base64") : void 0
}
};
}
default:
span.recordException(new Error(`Unknown cache entry kind: ${blob.value?.kind}`));
}
return null;
});
}
transformToStorableObject(data, context2) {
if (!data) {
return null;
}
if (isCachedRouteValue(data)) {
return {
...data,
revalidate: context2.revalidate ?? context2.cacheControl?.revalidate,
cacheControl: context2.cacheControl,
body: data.body.toString("base64")
};
}
if (isCachedPageValue(data)) {
return {
...data,
revalidate: context2.revalidate ?? context2.cacheControl?.revalidate,
cacheControl: context2.cacheControl
};
}
if (data?.kind === "APP_PAGE") {
return {
...data,
revalidate: context2.revalidate ?? context2.cacheControl?.revalidate,
cacheControl: context2.cacheControl,
rscData: data.rscData?.toString("base64")
};
}
return data;
}
async set(...args) {
return {};
return this.tracer.withActiveSpan("set cache key", async (span) => {
const [key, data, context2] = args;
const lastModified = Date.now();
span.setAttributes({ key, lastModified });
getLogger().debug(`[EdgeoneCacheHandler.set]: ${key}`);
const value = this.transformToStorableObject(data, context2);
const isDataReq = Boolean(context2.fetchUrl);
if (!isDataReq) {
this.captureCacheTags(value, key);
}
await this.cacheStore.set(key, { lastModified, value }, "blobStore.set");
if (data?.kind === "APP_PAGE") {
const requestContext = getRequestContext();
if (requestContext) {
requestContext.isCacheableAppPage = true;
}
}
if (!data && !isDataReq || data?.kind === "PAGE" || data?.kind === "PAGES") {
const requestContext = getRequestContext();
if (requestContext?.didPagesRouterOnDemandRevalidate) {
const tag = `_N_T_${key === "/index" ? "/" : encodeURI(key)}`;
requestContext?.trackBackgroundWork(purgeEdgeCache(tag));
}
}
});
}
async revalidateTag(tagOrTags) {
return markTagsAsStaleAndPurgeEdgeCache(tagOrTags);
}
resetRequestCache() {
}
/**
* Checks if a cache entry is stale through on demand revalidated tags
*/
checkCacheEntryStaleByTags(cacheEntry, tags = [], softTags = []) {
let cacheTags = [];
if (cacheEntry.value?.kind === "FETCH") {
cacheTags = [...tags, ...softTags];
} else if (cacheEntry.value?.kind === "PAGE" || cacheEntry.value?.kind === "PAGES" || cacheEntry.value?.kind === "APP_PAGE" || cacheEntry.value?.kind === "ROUTE" || cacheEntry.value?.kind === "APP_ROUTE") {
cacheTags = cacheEntry.value.headers?.[CACHE_TAGS_HEADER]?.split(/,|%2c/gi) || [];
} else {
return false;
}
if (this.revalidatedTags && this.revalidatedTags.length !== 0) {
for (const tag of this.revalidatedTags) {
if (cacheTags.includes(tag)) {
return true;
}
}
}
}
};
var cache_default = EdgeoneCacheHandler;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
EdgeoneCacheHandler
});