update wings

This commit is contained in:
2026-07-14 11:56:47 +05:30
parent 4b8277af70
commit 07e035dd62
1701 changed files with 0 additions and 461071 deletions

View File

@@ -1,395 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextRequestHint: null,
adapter: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextRequestHint: function() {
return NextRequestHint;
},
adapter: function() {
return adapter;
}
});
const _error = require("./error");
const _utils = require("./utils");
const _fetchevent = require("./spec-extension/fetch-event");
const _request = require("./spec-extension/request");
const _response = require("./spec-extension/response");
const _relativizeurl = require("../../shared/lib/router/utils/relativize-url");
const _nexturl = require("./next-url");
const _internalutils = require("../internal-utils");
const _apppaths = require("../../shared/lib/router/utils/app-paths");
const _approuterheaders = require("../../client/components/app-router-headers");
const _globals = require("./globals");
const _requeststore = require("../async-storage/request-store");
const _workunitasyncstorageexternal = require("../app-render/work-unit-async-storage.external");
const _workstore = require("../async-storage/work-store");
const _workasyncstorageexternal = require("../app-render/work-async-storage.external");
const _tracer = require("../lib/trace/tracer");
const _constants = require("../lib/trace/constants");
const _webonclose = require("./web-on-close");
const _getedgepreviewprops = require("./get-edge-preview-props");
const _builtinrequestcontext = require("../after/builtin-request-context");
const _implicittags = require("../lib/implicit-tags");
const _isrscrequest = require("../lib/is-rsc-request");
const _requestmeta = require("../request-meta");
class NextRequestHint extends _request.NextRequest {
constructor(params){
super(params.input, params.init);
this.sourcePage = params.page;
}
get request() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
respondWith() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
waitUntil() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
}
const headersGetter = {
keys: (headers)=>Array.from(headers.keys()),
get: (headers, key)=>headers.get(key) ?? undefined
};
let propagator = (request, fn)=>{
const tracer = (0, _tracer.getTracer)();
return tracer.withPropagatedContext(request.headers, fn, headersGetter);
};
let testApisIntercepted = false;
function ensureTestApisIntercepted() {
if (!testApisIntercepted) {
testApisIntercepted = true;
if (process.env.NEXT_PRIVATE_TEST_PROXY === 'true') {
const { interceptTestApis, wrapRequestHandler } = // eslint-disable-next-line @next/internal/typechecked-require -- experimental/testmode is not built ins next/dist/esm
require('next/dist/experimental/testmode/server-edge');
interceptTestApis();
propagator = wrapRequestHandler(propagator);
}
}
}
async function adapter(params) {
var _getBuiltinRequestContext;
ensureTestApisIntercepted();
await (0, _globals.ensureInstrumentationRegistered)();
// TODO-APP: use explicit marker for this
const isEdgeRendering = typeof globalThis.__BUILD_MANIFEST !== 'undefined';
params.request.url = (0, _apppaths.normalizeRscURL)(params.request.url);
const requestURL = params.bypassNextUrl ? new URL(params.request.url) : new _nexturl.NextURL(params.request.url, {
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
// Iterator uses an index to keep track of the current iteration. Because of deleting and appending below we can't just use the iterator.
// Instead we use the keys before iteration.
const keys = [
...requestURL.searchParams.keys()
];
for (const key of keys){
const value = requestURL.searchParams.getAll(key);
const normalizedKey = (0, _utils.normalizeNextQueryParam)(key);
if (normalizedKey) {
requestURL.searchParams.delete(normalizedKey);
for (const val of value){
requestURL.searchParams.append(normalizedKey, val);
}
requestURL.searchParams.delete(key);
}
}
// Ensure users only see page requests, never data requests.
let buildId = process.env.__NEXT_BUILD_ID || '';
if ('buildId' in requestURL) {
buildId = requestURL.buildId || '';
requestURL.buildId = '';
}
let deploymentId = process.env.NEXT_DEPLOYMENT_ID;
const requestHeaders = (0, _utils.fromNodeOutgoingHttpHeaders)(params.request.headers);
const isNextDataRequest = requestHeaders.has('x-nextjs-data');
const isRSCRequest = (0, _isrscrequest.isRSCRequestHeader)(requestHeaders.get(_approuterheaders.RSC_HEADER));
if (isNextDataRequest && requestURL.pathname === '/index') {
requestURL.pathname = '/';
}
const flightHeaders = new Map();
// Headers should only be stripped for middleware
if (!isEdgeRendering && !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
for (const header of _approuterheaders.FLIGHT_HEADERS){
const value = requestHeaders.get(header);
if (value !== null) {
flightHeaders.set(header, value);
requestHeaders.delete(header);
}
}
}
const normalizeURL = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? new URL(params.request.url) : requestURL;
const rscHash = normalizeURL.searchParams.get(_approuterheaders.NEXT_RSC_UNION_QUERY);
const request = new NextRequestHint({
page: params.page,
// Strip internal query parameters off the request.
input: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? normalizeURL.toString() : (0, _internalutils.stripInternalSearchParams)(normalizeURL).toString(),
init: {
body: params.request.body,
headers: requestHeaders,
method: params.request.method,
nextConfig: params.request.nextConfig,
signal: params.request.signal
}
});
if (params.request.requestMeta) {
(0, _requestmeta.setRequestMeta)(request, params.request.requestMeta);
}
/**
* This allows to identify the request as a data request. The user doesn't
* need to know about this property neither use it. We add it for testing
* purposes.
*/ if (isNextDataRequest) {
Object.defineProperty(request, '__isData', {
enumerable: false,
value: true
});
}
if (// If we are inside of the next start sandbox
// leverage the shared instance if not we need
// to create a fresh cache instance each time
!globalThis.__incrementalCacheShared && params.IncrementalCache) {
;
globalThis.__incrementalCache = new params.IncrementalCache({
CurCacheHandler: params.incrementalCacheHandler,
minimalMode: process.env.NODE_ENV !== 'development',
fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,
dev: process.env.NODE_ENV === 'development',
requestHeaders: params.request.headers,
getPrerenderManifest: ()=>{
return {
version: -1,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: (0, _getedgepreviewprops.getEdgePreviewProps)()
};
}
});
}
// if we're in an edge runtime sandbox, we should use the waitUntil
// that we receive from the enclosing NextServer
const outerWaitUntil = params.request.waitUntil ?? ((_getBuiltinRequestContext = (0, _builtinrequestcontext.getBuiltinRequestContext)()) == null ? void 0 : _getBuiltinRequestContext.waitUntil);
const event = new _fetchevent.NextFetchEvent({
request,
page: params.page,
context: outerWaitUntil ? {
waitUntil: outerWaitUntil
} : undefined
});
let response;
let cookiesFromResponse;
response = await propagator(request, ()=>{
// we only care to make async storage available for middleware
const isMiddleware = params.page === '/middleware' || params.page === '/src/middleware' || params.page === '/proxy' || params.page === '/src/proxy';
if (isMiddleware) {
// if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),
// so we have to inject it via DefinePlugin.
// in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).
const waitUntil = event.waitUntil.bind(event);
const closeController = new _webonclose.CloseController();
return (0, _tracer.getTracer)().trace(_constants.MiddlewareSpan.execute, {
spanName: `middleware ${request.method}`,
attributes: {
'http.target': request.nextUrl.pathname,
'http.method': request.method
}
}, async ()=>{
try {
var _params_request_nextConfig_experimental, _params_request_nextConfig, _params_request_nextConfig_experimental1, _params_request_nextConfig1;
const onUpdateCookies = (cookies)=>{
cookiesFromResponse = cookies;
};
const previewProps = (0, _getedgepreviewprops.getEdgePreviewProps)();
const page = '/' // Fake Work
;
const fallbackRouteParams = null;
const implicitTags = await (0, _implicittags.getImplicitTags)(page, request.nextUrl.pathname, fallbackRouteParams);
const requestStore = (0, _requeststore.createRequestStoreForAPI)(request, request.nextUrl, implicitTags, onUpdateCookies, previewProps);
const workStore = (0, _workstore.createWorkStore)({
page,
renderOpts: {
cacheLifeProfiles: (_params_request_nextConfig = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental = _params_request_nextConfig.experimental) == null ? void 0 : _params_request_nextConfig_experimental.cacheLife,
cacheComponents: false,
experimental: {
isRoutePPREnabled: false,
authInterrupts: !!((_params_request_nextConfig1 = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental1 = _params_request_nextConfig1.experimental) == null ? void 0 : _params_request_nextConfig_experimental1.authInterrupts)
},
supportsDynamicResponse: true,
waitUntil,
onClose: closeController.onClose.bind(closeController),
onAfterTaskError: undefined
},
isPrefetchRequest: request.headers.get(_approuterheaders.NEXT_ROUTER_PREFETCH_HEADER) === '1',
buildId: buildId ?? '',
deploymentId: deploymentId ?? '',
previouslyRevalidatedTags: []
});
return await _workasyncstorageexternal.workAsyncStorage.run(workStore, ()=>_workunitasyncstorageexternal.workUnitAsyncStorage.run(requestStore, params.handler, request, event));
} finally{
// middleware cannot stream, so we can consider the response closed
// as soon as the handler returns.
// we can delay running it until a bit later --
// if it's needed, we'll have a `waitUntil` lock anyway.
setTimeout(()=>{
closeController.dispatchClose();
}, 0);
}
});
}
return params.handler(request, event);
});
// check if response is a Response object
if (response && !(response instanceof Response)) {
throw Object.defineProperty(new TypeError('Expected an instance of Response to be returned'), "__NEXT_ERROR_CODE", {
value: "E567",
enumerable: false,
configurable: true
});
}
if (response && cookiesFromResponse) {
response.headers.set('set-cookie', cookiesFromResponse);
}
/**
* For rewrites we must always include the locale in the final pathname
* so we re-create the NextURL forcing it to include it when the it is
* an internal rewrite. Also we make sure the outgoing rewrite URL is
* a data URL if the request was a data request.
*/ const rewrite = response == null ? void 0 : response.headers.get('x-middleware-rewrite');
if (response && rewrite && (isRSCRequest || !isEdgeRendering)) {
var _params_request_nextConfig_experimental_clientParamParsingOrigins, _params_request_nextConfig_experimental, _params_request_nextConfig;
const destination = new _nexturl.NextURL(rewrite, {
forceLocale: true,
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE && !isEdgeRendering) {
if (destination.host === request.nextUrl.host) {
destination.buildId = buildId || destination.buildId;
response.headers.set('x-middleware-rewrite', String(destination));
}
}
/**
* When the request is a data request we must show if there was a rewrite
* with an internal header so the client knows which component to load
* from the data request.
*/ const { url: relativeDestination, isRelative } = (0, _relativizeurl.parseRelativeURL)(destination.toString(), requestURL.toString());
if (!isEdgeRendering && isNextDataRequest && // if the rewrite is external and external rewrite
// resolving config is enabled don't add this header
// so the upstream app can set it instead
!(process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE && relativeDestination.match(/http(s)?:\/\//))) {
response.headers.set('x-nextjs-rewrite', relativeDestination);
}
// Check to see if this is a non-relative rewrite. If it is, we need
// to check to see if it's an allowed origin to receive the rewritten
// headers.
const isAllowedOrigin = !isRelative ? (_params_request_nextConfig = params.request.nextConfig) == null ? void 0 : (_params_request_nextConfig_experimental = _params_request_nextConfig.experimental) == null ? void 0 : (_params_request_nextConfig_experimental_clientParamParsingOrigins = _params_request_nextConfig_experimental.clientParamParsingOrigins) == null ? void 0 : _params_request_nextConfig_experimental_clientParamParsingOrigins.some((origin)=>new RegExp(origin).test(destination.origin)) : false;
// If this is an RSC request, and the pathname or search has changed, and
// this isn't an external rewrite, we need to set the rewritten pathname and
// query headers.
if (isRSCRequest && (isRelative || isAllowedOrigin)) {
if (requestURL.pathname !== destination.pathname) {
response.headers.set(_approuterheaders.NEXT_REWRITTEN_PATH_HEADER, destination.pathname);
}
if (requestURL.search !== destination.search) {
response.headers.set(_approuterheaders.NEXT_REWRITTEN_QUERY_HEADER, // remove the leading ? from the search string
destination.search.slice(1));
}
}
}
/**
* Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,
* unless it's already present. This is necessary to ensure that RSC hash validation
* works correctly after a rewrite. For internal rewrites, the server can validate the
* RSC hash using the original URL, so forwarding the `_rsc` parameter is less critical.
* However, for external rewrites (where the request is proxied to another Next.js server),
* the external server does not have access to the original URL or its search parameters.
* In these cases, forwarding the `_rsc` parameter is essential so that the external server
* can perform the correct RSC hash validation.
*/ if (response && rewrite && isRSCRequest && rscHash) {
const rewriteURL = new URL(rewrite);
if (!rewriteURL.searchParams.has(_approuterheaders.NEXT_RSC_UNION_QUERY)) {
rewriteURL.searchParams.set(_approuterheaders.NEXT_RSC_UNION_QUERY, rscHash);
response.headers.set('x-middleware-rewrite', rewriteURL.toString());
}
}
/**
* For redirects we will not include the locale in case when it is the
* default and we must also make sure the outgoing URL is a data one if
* the incoming request was a data request.
*/ const redirect = response == null ? void 0 : response.headers.get('Location');
if (response && redirect && !isEdgeRendering) {
const redirectURL = new _nexturl.NextURL(redirect, {
forceLocale: false,
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
/**
* Responses created from redirects have immutable headers so we have
* to clone the response to be able to modify it.
*/ response = new Response(response.body, response);
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
if (redirectURL.host === requestURL.host) {
redirectURL.buildId = buildId || redirectURL.buildId;
response.headers.set('Location', (0, _relativizeurl.getRelativeURL)(redirectURL, requestURL));
}
}
/**
* When the request is a data request we can't use the location header as
* it may end up with CORS error. Instead we map to an internal header so
* the client knows the destination.
*/ if (isNextDataRequest) {
response.headers.delete('Location');
response.headers.set('x-nextjs-redirect', (0, _relativizeurl.getRelativeURL)(redirectURL.toString(), requestURL.toString()));
}
}
const finalResponse = response ? response : _response.NextResponse.next();
// Flight headers are not overridable / removable so they are applied at the end.
const middlewareOverrideHeaders = finalResponse.headers.get('x-middleware-override-headers');
const overwrittenHeaders = [];
if (middlewareOverrideHeaders) {
for (const [key, value] of flightHeaders){
finalResponse.headers.set(`x-middleware-request-${key}`, value);
overwrittenHeaders.push(key);
}
if (overwrittenHeaders.length > 0) {
finalResponse.headers.set('x-middleware-override-headers', middlewareOverrideHeaders + ',' + overwrittenHeaders.join(','));
}
}
return {
response: finalResponse,
waitUntil: (0, _fetchevent.getWaitUntilPromiseFromEvent)(event) ?? Promise.resolve(),
fetchMetrics: request.fetchMetrics
};
}
//# sourceMappingURL=adapter.js.map

View File

@@ -1,124 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "EdgeRouteModuleWrapper", {
enumerable: true,
get: function() {
return EdgeRouteModuleWrapper;
}
});
require("./globals");
const _adapter = require("./adapter");
const _incrementalcache = require("../lib/incremental-cache");
const _handlers = require("../use-cache/handlers");
const _routematcher = require("../route-matchers/route-matcher");
const _internaledgewaituntil = require("./internal-edge-wait-until");
const _serverutils = require("../server-utils");
const _querystring = require("../../shared/lib/router/utils/querystring");
const _webonclose = require("./web-on-close");
const _getedgepreviewprops = require("./get-edge-preview-props");
const _web = require("../../server/base-http/web");
class EdgeRouteModuleWrapper {
/**
* The constructor is wrapped with private to ensure that it can only be
* constructed by the static wrap method.
*
* @param routeModule the route module to wrap
*/ constructor(routeModule, cacheHandlers){
this.routeModule = routeModule;
this.cacheHandlers = cacheHandlers;
// TODO: (wyattjoh) possibly allow the module to define it's own matcher
this.matcher = new _routematcher.RouteMatcher(routeModule.definition);
}
/**
* This will wrap a module with the EdgeModuleWrapper and return a function
* that can be used as a handler for the edge runtime.
*
* @param module the module to wrap
* @param options any options that should be passed to the adapter and
* override the ones passed from the runtime
* @returns a function that can be used as a handler for the edge runtime
*/ static wrap(routeModule, options) {
// Create the module wrapper.
const wrapper = new EdgeRouteModuleWrapper(routeModule, options.cacheHandlers ?? {});
// Return the wrapping function.
return (opts)=>{
return (0, _adapter.adapter)({
...opts,
IncrementalCache: _incrementalcache.IncrementalCache,
incrementalCacheHandler: options.incrementalCacheHandler,
// Bind the handler method to the wrapper so it still has context.
handler: wrapper.handler.bind(wrapper),
page: options.page
});
};
}
async handler(request, evt) {
const utils = (0, _serverutils.getServerUtils)({
pageIsDynamic: this.matcher.isDynamic,
page: this.matcher.definition.pathname,
basePath: request.nextUrl.basePath,
// We don't need the `handleRewrite` util, so can just pass an empty object
rewrites: {},
// only used for rewrites, so setting an arbitrary default value here
caseSensitive: false
});
const { nextConfig } = this.routeModule.getNextConfigEdge(new _web.WebNextRequest(request));
(0, _handlers.initializeCacheHandlers)(nextConfig.cacheMaxMemorySize);
for (const [kind, cacheHandler] of Object.entries(this.cacheHandlers)){
(0, _handlers.setCacheHandler)(kind, cacheHandler);
}
const { params } = utils.normalizeDynamicRouteParams((0, _querystring.searchParamsToUrlQuery)(request.nextUrl.searchParams), false);
const waitUntil = evt.waitUntil.bind(evt);
const closeController = new _webonclose.CloseController();
const previewProps = (0, _getedgepreviewprops.getEdgePreviewProps)();
// Create the context for the handler. This contains the params from the
// match (if any).
const context = {
params,
previewProps,
renderOpts: {
supportsDynamicResponse: true,
waitUntil,
onClose: closeController.onClose.bind(closeController),
onAfterTaskError: undefined,
cacheComponents: !!process.env.__NEXT_CACHE_COMPONENTS,
experimental: {
authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS
},
cacheLifeProfiles: nextConfig.cacheLife
},
sharedContext: {
buildId: '',
deploymentId: ''
}
};
// Get the response from the handler.
let res = await this.routeModule.handle(request, context);
const waitUntilPromises = [
(0, _internaledgewaituntil.internal_getCurrentFunctionWaitUntil)()
];
if (context.renderOpts.pendingWaitUntil) {
waitUntilPromises.push(context.renderOpts.pendingWaitUntil);
}
evt.waitUntil(Promise.all(waitUntilPromises));
if (!res.body) {
// we can delay running it until a bit later --
// if it's needed, we'll have a `waitUntil` lock anyway.
setTimeout(()=>closeController.dispatchClose(), 0);
} else {
// NOTE: if this is a streaming response, onClose may be called later,
// so we can't rely on `closeController.listeners` -- it might be 0 at this point.
const trackedBody = (0, _webonclose.trackStreamConsumed)(res.body, ()=>closeController.dispatchClose());
res = new Response(trackedBody, {
status: res.status,
statusText: res.statusText,
headers: res.headers
});
}
return res;
}
}
//# sourceMappingURL=edge-route-module-wrapper.js.map

View File

@@ -1,54 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
PageSignatureError: null,
RemovedPageError: null,
RemovedUAError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
PageSignatureError: function() {
return PageSignatureError;
},
RemovedPageError: function() {
return RemovedPageError;
},
RemovedUAError: function() {
return RemovedUAError;
}
});
class PageSignatureError extends Error {
constructor({ page }){
super(`The middleware "${page}" accepts an async API directly with the form:
export function middleware(request, event) {
return NextResponse.redirect('/new-location')
}
Read more: https://nextjs.org/docs/messages/middleware-new-signature
`);
}
}
class RemovedPageError extends Error {
constructor(){
super(`The request.page has been deprecated in favour of \`URLPattern\`.
Read more: https://nextjs.org/docs/messages/middleware-request-page
`);
}
}
class RemovedUAError extends Error {
constructor(){
super(`The request.ua has been removed in favour of \`userAgent\` function.
Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
`);
}
}
//# sourceMappingURL=error.js.map

View File

@@ -1,56 +0,0 @@
// Alias index file of next/server for edge runtime for tree-shaking purpose
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ImageResponse: null,
NextRequest: null,
NextResponse: null,
URLPattern: null,
after: null,
connection: null,
userAgent: null,
userAgentFromString: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ImageResponse: function() {
return _imageresponse.ImageResponse;
},
NextRequest: function() {
return _request.NextRequest;
},
NextResponse: function() {
return _response.NextResponse;
},
URLPattern: function() {
return _urlpattern.URLPattern;
},
after: function() {
return _after.after;
},
connection: function() {
return _connection.connection;
},
userAgent: function() {
return _useragent.userAgent;
},
userAgentFromString: function() {
return _useragent.userAgentFromString;
}
});
const _imageresponse = require("../spec-extension/image-response");
const _request = require("../spec-extension/request");
const _response = require("../spec-extension/response");
const _useragent = require("../spec-extension/user-agent");
const _urlpattern = require("../spec-extension/url-pattern");
const _after = require("../../after");
const _connection = require("../../request/connection");
//# sourceMappingURL=index.js.map

View File

@@ -1,23 +0,0 @@
/**
* In edge runtime, these props directly accessed from environment variables.
* - local: env vars will be injected through edge-runtime as runtime env vars
* - deployment: env vars will be replaced by edge build pipeline
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getEdgePreviewProps", {
enumerable: true,
get: function() {
return getEdgePreviewProps;
}
});
function getEdgePreviewProps() {
return {
previewModeId: process.env.__NEXT_PREVIEW_MODE_ID || '',
previewModeSigningKey: process.env.__NEXT_PREVIEW_MODE_SIGNING_KEY || '',
previewModeEncryptionKey: process.env.__NEXT_PREVIEW_MODE_ENCRYPTION_KEY || ''
};
}
//# sourceMappingURL=get-edge-preview-props.js.map

View File

@@ -1,128 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
edgeInstrumentationOnRequestError: null,
ensureInstrumentationRegistered: null,
getEdgeInstrumentationModule: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
edgeInstrumentationOnRequestError: function() {
return edgeInstrumentationOnRequestError;
},
ensureInstrumentationRegistered: function() {
return ensureInstrumentationRegistered;
},
getEdgeInstrumentationModule: function() {
return getEdgeInstrumentationModule;
}
});
async function getEdgeInstrumentationModule() {
const instrumentation = '_ENTRIES' in globalThis && _ENTRIES.middleware_instrumentation && await _ENTRIES.middleware_instrumentation;
return instrumentation;
}
let instrumentationModulePromise = null;
async function registerInstrumentation() {
// Ensure registerInstrumentation is not called in production build
if (process.env.NEXT_PHASE === 'phase-production-build') return;
if (!instrumentationModulePromise) {
instrumentationModulePromise = getEdgeInstrumentationModule();
}
const instrumentation = await instrumentationModulePromise;
if (instrumentation == null ? void 0 : instrumentation.register) {
try {
await instrumentation.register();
} catch (err) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
throw err;
}
}
}
async function edgeInstrumentationOnRequestError(...args) {
const instrumentation = await getEdgeInstrumentationModule();
try {
var _instrumentation_onRequestError;
await (instrumentation == null ? void 0 : (_instrumentation_onRequestError = instrumentation.onRequestError) == null ? void 0 : _instrumentation_onRequestError.call(instrumentation, ...args));
} catch (err) {
// Log the soft error and continue, since the original error has already been thrown
console.error('Error in instrumentation.onRequestError:', err);
}
}
let registerInstrumentationPromise = null;
function ensureInstrumentationRegistered() {
if (!registerInstrumentationPromise) {
registerInstrumentationPromise = registerInstrumentation();
}
return registerInstrumentationPromise;
}
function getUnsupportedModuleErrorMessage(module1) {
// warning: if you change these messages, you must adjust how dev-overlay's middleware detects modules not found
return `The edge runtime does not support Node.js '${module1}' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`;
}
function __import_unsupported(moduleName) {
const proxy = new Proxy(function() {}, {
get (_obj, prop) {
if (prop === 'then') {
return {};
}
throw Object.defineProperty(new Error(getUnsupportedModuleErrorMessage(moduleName)), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
},
construct () {
throw Object.defineProperty(new Error(getUnsupportedModuleErrorMessage(moduleName)), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
},
apply (_target, _this, args) {
if (typeof args[0] === 'function') {
return args[0](proxy);
}
throw Object.defineProperty(new Error(getUnsupportedModuleErrorMessage(moduleName)), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
});
return new Proxy({}, {
get: ()=>proxy
});
}
function enhanceGlobals() {
if (process.env.NEXT_RUNTIME !== 'edge') {
return;
}
// The condition is true when the "process" module is provided
if (process !== global.process) {
// prefer local process but global.process has correct "env"
process.env = global.process.env;
global.process = process;
}
// to allow building code that import but does not use node.js modules,
// webpack will expect this function to exist in global scope
try {
Object.defineProperty(globalThis, '__import_unsupported', {
value: __import_unsupported,
enumerable: false,
configurable: false
});
} catch {}
// Eagerly fire instrumentation hook to make the startup faster.
void ensureInstrumentationRegistered();
}
enhanceGlobals();
//# sourceMappingURL=globals.js.map

View File

@@ -1,39 +0,0 @@
/**
* List of valid HTTP methods that can be implemented by Next.js's Custom App
* Routes.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
HTTP_METHODS: null,
isHTTPMethod: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
HTTP_METHODS: function() {
return HTTP_METHODS;
},
isHTTPMethod: function() {
return isHTTPMethod;
}
});
const HTTP_METHODS = [
'GET',
'HEAD',
'OPTIONS',
'POST',
'PUT',
'DELETE',
'PATCH'
];
function isHTTPMethod(maybeMethod) {
return HTTP_METHODS.includes(maybeMethod);
}
//# sourceMappingURL=http.js.map

View File

@@ -1,64 +0,0 @@
// An internal module to expose the "waitUntil" API to Edge SSR and Edge Route Handler functions.
// This is highly experimental and subject to change.
// We still need a global key to bypass Webpack's layering of modules.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
internal_getCurrentFunctionWaitUntil: null,
internal_runWithWaitUntil: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
internal_getCurrentFunctionWaitUntil: function() {
return internal_getCurrentFunctionWaitUntil;
},
internal_runWithWaitUntil: function() {
return internal_runWithWaitUntil;
}
});
const GLOBAL_KEY = Symbol.for('__next_internal_waitUntil__');
const state = // @ts-ignore
globalThis[GLOBAL_KEY] || // @ts-ignore
(globalThis[GLOBAL_KEY] = {
waitUntilCounter: 0,
waitUntilResolve: undefined,
waitUntilPromise: null
});
// No matter how many concurrent requests are being handled, we want to make sure
// that the final promise is only resolved once all of the waitUntil promises have
// settled.
function resolveOnePromise() {
state.waitUntilCounter--;
if (state.waitUntilCounter === 0) {
state.waitUntilResolve();
state.waitUntilPromise = null;
}
}
function internal_getCurrentFunctionWaitUntil() {
return state.waitUntilPromise;
}
function internal_runWithWaitUntil(fn) {
const result = fn();
if (result && typeof result === 'object' && 'then' in result && 'finally' in result && typeof result.then === 'function' && typeof result.finally === 'function') {
if (!state.waitUntilCounter) {
// Create the promise for the next batch of waitUntil calls.
state.waitUntilPromise = new Promise((resolve)=>{
state.waitUntilResolve = resolve;
});
}
state.waitUntilCounter++;
return result.finally(()=>{
resolveOnePromise();
});
}
return result;
}
//# sourceMappingURL=internal-edge-wait-until.js.map

View File

@@ -1,199 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NextURL", {
enumerable: true,
get: function() {
return NextURL;
}
});
const _detectdomainlocale = require("../../shared/lib/i18n/detect-domain-locale");
const _formatnextpathnameinfo = require("../../shared/lib/router/utils/format-next-pathname-info");
const _gethostname = require("../../shared/lib/get-hostname");
const _getnextpathnameinfo = require("../../shared/lib/router/utils/get-next-pathname-info");
const REGEX_LOCALHOST_HOSTNAME = /^(?:127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)$/;
function parseURL(url, base) {
const parsed = new URL(String(url), base && String(base));
if (REGEX_LOCALHOST_HOSTNAME.test(parsed.hostname)) {
parsed.hostname = 'localhost';
}
return parsed;
}
const Internal = Symbol('NextURLInternal');
class NextURL {
constructor(input, baseOrOpts, opts){
let base;
let options;
if (typeof baseOrOpts === 'object' && 'pathname' in baseOrOpts || typeof baseOrOpts === 'string') {
base = baseOrOpts;
options = opts || {};
} else {
options = opts || baseOrOpts || {};
}
this[Internal] = {
url: parseURL(input, base ?? options.base),
options: options,
basePath: ''
};
this.analyze();
}
analyze() {
var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig, _this_Internal_domainLocale, _this_Internal_options_nextConfig_i18n1, _this_Internal_options_nextConfig1;
const info = (0, _getnextpathnameinfo.getNextPathnameInfo)(this[Internal].url.pathname, {
nextConfig: this[Internal].options.nextConfig,
parseData: !process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE,
i18nProvider: this[Internal].options.i18nProvider
});
const hostname = (0, _gethostname.getHostname)(this[Internal].url, this[Internal].options.headers);
this[Internal].domainLocale = this[Internal].options.i18nProvider ? this[Internal].options.i18nProvider.detectDomainLocale(hostname) : (0, _detectdomainlocale.detectDomainLocale)((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.domains, hostname);
const defaultLocale = ((_this_Internal_domainLocale = this[Internal].domainLocale) == null ? void 0 : _this_Internal_domainLocale.defaultLocale) || ((_this_Internal_options_nextConfig1 = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n1 = _this_Internal_options_nextConfig1.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n1.defaultLocale);
this[Internal].url.pathname = info.pathname;
this[Internal].defaultLocale = defaultLocale;
this[Internal].basePath = info.basePath ?? '';
this[Internal].buildId = info.buildId;
this[Internal].locale = info.locale ?? defaultLocale;
this[Internal].trailingSlash = info.trailingSlash;
}
formatPathname() {
return (0, _formatnextpathnameinfo.formatNextPathnameInfo)({
basePath: this[Internal].basePath,
buildId: this[Internal].buildId,
defaultLocale: !this[Internal].options.forceLocale ? this[Internal].defaultLocale : undefined,
locale: this[Internal].locale,
pathname: this[Internal].url.pathname,
trailingSlash: this[Internal].trailingSlash
});
}
formatSearch() {
return this[Internal].url.search;
}
get buildId() {
return this[Internal].buildId;
}
set buildId(buildId) {
this[Internal].buildId = buildId;
}
get locale() {
return this[Internal].locale ?? '';
}
set locale(locale) {
var _this_Internal_options_nextConfig_i18n, _this_Internal_options_nextConfig;
if (!this[Internal].locale || !((_this_Internal_options_nextConfig = this[Internal].options.nextConfig) == null ? void 0 : (_this_Internal_options_nextConfig_i18n = _this_Internal_options_nextConfig.i18n) == null ? void 0 : _this_Internal_options_nextConfig_i18n.locales.includes(locale))) {
throw Object.defineProperty(new TypeError(`The NextURL configuration includes no locale "${locale}"`), "__NEXT_ERROR_CODE", {
value: "E597",
enumerable: false,
configurable: true
});
}
this[Internal].locale = locale;
}
get defaultLocale() {
return this[Internal].defaultLocale;
}
get domainLocale() {
return this[Internal].domainLocale;
}
get searchParams() {
return this[Internal].url.searchParams;
}
get host() {
return this[Internal].url.host;
}
set host(value) {
this[Internal].url.host = value;
}
get hostname() {
return this[Internal].url.hostname;
}
set hostname(value) {
this[Internal].url.hostname = value;
}
get port() {
return this[Internal].url.port;
}
set port(value) {
this[Internal].url.port = value;
}
get protocol() {
return this[Internal].url.protocol;
}
set protocol(value) {
this[Internal].url.protocol = value;
}
get href() {
const pathname = this.formatPathname();
const search = this.formatSearch();
return `${this.protocol}//${this.host}${pathname}${search}${this.hash}`;
}
set href(url) {
this[Internal].url = parseURL(url);
this.analyze();
}
get origin() {
return this[Internal].url.origin;
}
get pathname() {
return this[Internal].url.pathname;
}
set pathname(value) {
this[Internal].url.pathname = value;
}
get hash() {
return this[Internal].url.hash;
}
set hash(value) {
this[Internal].url.hash = value;
}
get search() {
return this[Internal].url.search;
}
set search(value) {
this[Internal].url.search = value;
}
get password() {
return this[Internal].url.password;
}
set password(value) {
this[Internal].url.password = value;
}
get username() {
return this[Internal].url.username;
}
set username(value) {
this[Internal].url.username = value;
}
get basePath() {
return this[Internal].basePath;
}
set basePath(value) {
this[Internal].basePath = value.startsWith('/') ? value : `/${value}`;
}
toString() {
return this.href;
}
toJSON() {
return this.href;
}
[Symbol.for('edge-runtime.inspect.custom')]() {
return {
href: this.href,
origin: this.origin,
protocol: this.protocol,
username: this.username,
password: this.password,
host: this.host,
hostname: this.hostname,
port: this.port,
pathname: this.pathname,
search: this.search,
searchParams: this.searchParams,
hash: this.hash
};
}
clone() {
return new NextURL(String(this), this[Internal].options);
}
}
//# sourceMappingURL=next-url.js.map

View File

@@ -1,462 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
clearAllModuleContexts: null,
clearModuleContext: null,
edgeSandboxNextRequestContext: null,
getModuleContext: null,
requestStore: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
clearAllModuleContexts: function() {
return clearAllModuleContexts;
},
clearModuleContext: function() {
return clearModuleContext;
},
edgeSandboxNextRequestContext: function() {
return edgeSandboxNextRequestContext;
},
getModuleContext: function() {
return getModuleContext;
},
requestStore: function() {
return requestStore;
}
});
const _async_hooks = require("async_hooks");
const _constants = require("../../../shared/lib/constants");
const _edgeruntime = require("next/dist/compiled/edge-runtime");
const _fs = require("fs");
const _utils = require("../utils");
const _pick = require("../../../lib/pick");
const _fetchinlineassets = require("./fetch-inline-assets");
const _vm = require("vm");
const _nodebuffer = /*#__PURE__*/ _interop_require_default(require("node:buffer"));
const _nodeevents = /*#__PURE__*/ _interop_require_default(require("node:events"));
const _nodeassert = /*#__PURE__*/ _interop_require_default(require("node:assert"));
const _nodeutil = /*#__PURE__*/ _interop_require_default(require("node:util"));
const _nodeasync_hooks = /*#__PURE__*/ _interop_require_default(require("node:async_hooks"));
const _resourcemanagers = require("./resource-managers");
const _builtinrequestcontext = require("../../after/builtin-request-context");
const _patcherrorinspect = require("../../patch-error-inspect");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let getServerError;
let decorateServerError;
if (process.env.NODE_ENV === 'development') {
getServerError = require('../../dev/node-stack-frames').getServerError;
decorateServerError = require('../../../shared/lib/error-source').decorateServerError;
} else {
getServerError = (error)=>error;
decorateServerError = ()=>{};
}
/**
* A Map of cached module contexts indexed by the module name. It allows
* to have a different cache scoped per module name or depending on the
* provided module key on creation.
*/ const moduleContexts = new Map();
const pendingModuleCaches = new Map();
async function clearAllModuleContexts() {
_resourcemanagers.intervalsManager.removeAll();
_resourcemanagers.timeoutsManager.removeAll();
moduleContexts.clear();
pendingModuleCaches.clear();
}
async function clearModuleContext(path) {
_resourcemanagers.intervalsManager.removeAll();
_resourcemanagers.timeoutsManager.removeAll();
const handleContext = (key, cache, context)=>{
if (cache == null ? void 0 : cache.paths.has(path)) {
context.delete(key);
}
};
for (const [key, cache] of moduleContexts){
handleContext(key, cache, moduleContexts);
}
for (const [key, cache] of pendingModuleCaches){
handleContext(key, await cache, pendingModuleCaches);
}
}
async function loadWasm(wasm) {
const modules = {};
await Promise.all(wasm.map(async (binding)=>{
const module1 = await WebAssembly.compile(// @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BufferSource'.
await _fs.promises.readFile(binding.filePath));
modules[binding.name] = module1;
}));
return modules;
}
function buildEnvironmentVariablesFrom(injectedEnvironments) {
let env = Object.fromEntries([
...Object.entries(process.env),
...Object.entries(injectedEnvironments),
[
'NEXT_RUNTIME',
'edge'
]
]);
return env;
}
function throwUnsupportedAPIError(name) {
const error = Object.defineProperty(new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`), "__NEXT_ERROR_CODE", {
value: "E97",
enumerable: false,
configurable: true
});
decorateServerError(error, _constants.COMPILER_NAMES.edgeServer);
throw error;
}
function createProcessPolyfill(env) {
const processPolyfill = {
env: buildEnvironmentVariablesFrom(env)
};
const overriddenValue = {};
for (const key of Object.keys(process)){
if (key === 'env') continue;
Object.defineProperty(processPolyfill, key, {
get () {
if (overriddenValue[key] !== undefined) {
return overriddenValue[key];
}
if (typeof process[key] === 'function') {
return ()=>throwUnsupportedAPIError(`process.${key}`);
}
return undefined;
},
set (value) {
overriddenValue[key] = value;
},
enumerable: false
});
}
return processPolyfill;
}
function addStub(context, name) {
Object.defineProperty(context, name, {
get () {
return function() {
throwUnsupportedAPIError(name);
};
},
enumerable: false
});
}
function getDecorateUnhandledError(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (error)=>{
if (error instanceof EdgeRuntimeError) {
decorateServerError(error, _constants.COMPILER_NAMES.edgeServer);
}
};
}
function getDecorateUnhandledRejection(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (rejected)=>{
if (rejected.reason instanceof EdgeRuntimeError) {
decorateServerError(rejected.reason, _constants.COMPILER_NAMES.edgeServer);
}
};
}
const NativeModuleMap = (()=>{
const mods = {
'node:buffer': (0, _pick.pick)(_nodebuffer.default, [
'constants',
'kMaxLength',
'kStringMaxLength',
'Buffer',
'SlowBuffer'
]),
'node:events': (0, _pick.pick)(_nodeevents.default, [
'EventEmitter',
'captureRejectionSymbol',
'defaultMaxListeners',
'errorMonitor',
'listenerCount',
'on',
'once'
]),
'node:async_hooks': (0, _pick.pick)(_nodeasync_hooks.default, [
'AsyncLocalStorage',
'AsyncResource'
]),
'node:assert': (0, _pick.pick)(_nodeassert.default, [
'AssertionError',
'deepEqual',
'deepStrictEqual',
'doesNotMatch',
'doesNotReject',
'doesNotThrow',
'equal',
'fail',
'ifError',
'match',
'notDeepEqual',
'notDeepStrictEqual',
'notEqual',
'notStrictEqual',
'ok',
'rejects',
'strict',
'strictEqual',
'throws'
]),
'node:util': (0, _pick.pick)(_nodeutil.default, [
'_extend',
'callbackify',
'format',
'inherits',
'promisify',
'types'
])
};
return new Map(Object.entries(mods));
})();
const requestStore = new _async_hooks.AsyncLocalStorage();
const edgeSandboxNextRequestContext = (0, _builtinrequestcontext.createLocalRequestContext)();
/**
* Create a module cache specific for the provided parameters. It includes
* a runtime context, require cache and paths cache.
*/ async function createModuleContext(options) {
const warnedEvals = new Set();
const warnedWasmCodegens = new Set();
const { edgeFunctionEntry } = options;
const wasm = await loadWasm(edgeFunctionEntry.wasm ?? []);
const runtime = new _edgeruntime.EdgeRuntime({
codeGeneration: process.env.NODE_ENV !== 'production' ? {
strings: true,
wasm: true
} : undefined,
extend: (context)=>{
context.process = createProcessPolyfill(edgeFunctionEntry.env);
Object.defineProperty(context, 'require', {
enumerable: false,
value: (id)=>{
const value = NativeModuleMap.get(id);
if (!value) {
throw Object.defineProperty(new TypeError('Native module not found: ' + id), "__NEXT_ERROR_CODE", {
value: "E546",
enumerable: false,
configurable: true
});
}
return value;
}
});
if (process.env.NODE_ENV !== 'production') {
context.__next_log_error__ = function(err) {
options.onError(err);
};
}
context.__next_eval__ = function __next_eval__(fn) {
const key = fn.toString();
if (!warnedEvals.has(key)) {
const warning = getServerError(Object.defineProperty(new Error(`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), "__NEXT_ERROR_CODE", {
value: "E149",
enumerable: false,
configurable: true
}), _constants.COMPILER_NAMES.edgeServer);
warning.name = 'DynamicCodeEvaluationWarning';
Error.captureStackTrace(warning, __next_eval__);
warnedEvals.add(key);
options.onWarning(warning);
}
return fn();
};
context.__next_webassembly_compile__ = function __next_webassembly_compile__(fn) {
const key = fn.toString();
if (!warnedWasmCodegens.has(key)) {
const warning = getServerError(Object.defineProperty(new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), "__NEXT_ERROR_CODE", {
value: "E184",
enumerable: false,
configurable: true
}), _constants.COMPILER_NAMES.edgeServer);
warning.name = 'DynamicWasmCodeGenerationWarning';
Error.captureStackTrace(warning, __next_webassembly_compile__);
warnedWasmCodegens.add(key);
options.onWarning(warning);
}
return fn();
};
context.__next_webassembly_instantiate__ = async function __next_webassembly_instantiate__(fn) {
const result = await fn();
// If a buffer is given, WebAssembly.instantiate returns an object
// containing both a module and an instance while it returns only an
// instance if a WASM module is given. Utilize the fact to determine
// if the WASM code generation happens.
//
// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/instantiate#primary_overload_%E2%80%94_taking_wasm_binary_code
const instantiatedFromBuffer = result.hasOwnProperty('module');
const key = fn.toString();
if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {
const warning = getServerError(Object.defineProperty(new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`), "__NEXT_ERROR_CODE", {
value: "E40",
enumerable: false,
configurable: true
}), _constants.COMPILER_NAMES.edgeServer);
warning.name = 'DynamicWasmCodeGenerationWarning';
Error.captureStackTrace(warning, __next_webassembly_instantiate__);
warnedWasmCodegens.add(key);
options.onWarning(warning);
}
return result;
};
const __fetch = context.fetch;
context.fetch = async (input, init = {})=>{
const callingError = Object.defineProperty(new Error('[internal]'), "__NEXT_ERROR_CODE", {
value: "E5",
enumerable: false,
configurable: true
});
const assetResponse = await (0, _fetchinlineassets.fetchInlineAsset)({
input,
assets: options.edgeFunctionEntry.assets,
distDir: options.distDir,
context
});
if (assetResponse) {
return assetResponse;
}
init.headers = new Headers(init.headers ?? {});
if (!init.headers.has('user-agent')) {
init.headers.set(`user-agent`, `Next.js Middleware`);
}
const response = typeof input === 'object' && 'url' in input ? __fetch(input.url, {
...(0, _pick.pick)(input, [
'method',
'body',
'cache',
'credentials',
'integrity',
'keepalive',
'mode',
'redirect',
'referrer',
'referrerPolicy',
'signal'
]),
...init,
headers: {
...Object.fromEntries(input.headers),
...Object.fromEntries(init.headers)
}
}) : __fetch(String(input), init);
return await response.catch((err)=>{
callingError.message = err.message;
err.stack = callingError.stack;
throw err;
});
};
const __Request = context.Request;
context.Request = class extends __Request {
constructor(input, init){
const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);
if (typeof input === 'string') {
(0, _utils.validateURL)(url);
super(input, init);
} else {
super(input, init);
(0, _utils.validateURL)(url);
}
this.next = init == null ? void 0 : init.next;
}
};
const __redirect = context.Response.redirect.bind(context.Response);
context.Response.redirect = (...args)=>{
(0, _utils.validateURL)(args[0]);
return __redirect(...args);
};
for (const name of _constants.EDGE_UNSUPPORTED_NODE_APIS){
addStub(context, name);
}
Object.assign(context, wasm);
context.performance = performance;
context.AsyncLocalStorage = _async_hooks.AsyncLocalStorage;
// @ts-ignore the timeouts have weird types in the edge runtime
context.setInterval = (...args)=>_resourcemanagers.intervalsManager.add(args);
// @ts-ignore the timeouts have weird types in the edge runtime
context.clearInterval = (interval)=>_resourcemanagers.intervalsManager.remove(interval);
// @ts-ignore the timeouts have weird types in the edge runtime
context.setTimeout = (...args)=>_resourcemanagers.timeoutsManager.add(args);
// @ts-ignore the timeouts have weird types in the edge runtime
context.clearTimeout = (timeout)=>_resourcemanagers.timeoutsManager.remove(timeout);
// Duplicated from packages/next/src/server/after/builtin-request-context.ts
// because we need to use the sandboxed `Symbol.for`, not the one from the outside
const NEXT_REQUEST_CONTEXT_SYMBOL = context.Symbol.for('@next/request-context');
Object.defineProperty(context, NEXT_REQUEST_CONTEXT_SYMBOL, {
enumerable: false,
value: edgeSandboxNextRequestContext
});
return context;
}
});
const decorateUnhandledError = getDecorateUnhandledError(runtime);
runtime.context.addEventListener('error', decorateUnhandledError);
const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime);
runtime.context.addEventListener('unhandledrejection', decorateUnhandledRejection);
(0, _patcherrorinspect.patchErrorInspectEdgeLite)(runtime.context.Error);
// An Error from within the Edge Runtime could also bubble up into the Node.js process.
// For example, uncaught errors are handled in the Node.js runtime.
(0, _patcherrorinspect.patchErrorInspectNodeJS)(runtime.context.Error);
return {
runtime,
paths: new Map(),
warnedEvals: new Set()
};
}
function getModuleContextShared(options) {
let deferredModuleContext = pendingModuleCaches.get(options.moduleName);
if (!deferredModuleContext) {
deferredModuleContext = createModuleContext(options);
pendingModuleCaches.set(options.moduleName, deferredModuleContext);
}
return deferredModuleContext;
}
async function getModuleContext(options) {
let lazyModuleContext;
if (options.useCache) {
lazyModuleContext = moduleContexts.get(options.moduleName) || await getModuleContextShared(options);
}
if (!lazyModuleContext) {
lazyModuleContext = await createModuleContext(options);
moduleContexts.set(options.moduleName, lazyModuleContext);
}
const moduleContext = lazyModuleContext;
const evaluateInContext = (filepath)=>{
if (!moduleContext.paths.has(filepath)) {
const content = (0, _fs.readFileSync)(filepath, 'utf-8');
try {
(0, _vm.runInContext)(content, moduleContext.runtime.context, {
filename: filepath
});
moduleContext.paths.set(filepath, content);
} catch (error) {
if (options.useCache) {
moduleContext == null ? void 0 : moduleContext.paths.delete(filepath);
}
throw error;
}
}
};
return {
...moduleContext,
evaluateInContext
};
}
//# sourceMappingURL=context.js.map

View File

@@ -1,35 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "fetchInlineAsset", {
enumerable: true,
get: function() {
return fetchInlineAsset;
}
});
const _fs = require("fs");
const _bodystreams = require("../../body-streams");
const _path = require("path");
async function fetchInlineAsset(options) {
const inputString = String(options.input);
if (!inputString.startsWith('blob:')) {
return;
}
const name = inputString.replace('blob:', '');
const asset = options.assets ? options.assets.find((x)=>x.name === name) : {
name,
filePath: name
};
if (!asset) {
return;
}
const filePath = (0, _path.resolve)(options.distDir, asset.filePath);
const fileIsReadable = await _fs.promises.access(filePath).then(()=>true, ()=>false);
if (fileIsReadable) {
const readStream = (0, _fs.createReadStream)(filePath);
return new options.context.Response((0, _bodystreams.requestToBodyStream)(options.context, Uint8Array, readStream));
}
}
//# sourceMappingURL=fetch-inline-assets.js.map

View File

@@ -1,28 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "clearModuleContext", {
enumerable: true,
get: function() {
return _context.clearModuleContext;
}
});
0 && __export(require("./sandbox"));
_export_star(require("./sandbox"), exports);
const _context = require("./context");
function _export_star(from, to) {
Object.keys(from).forEach(function(k) {
if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
Object.defineProperty(to, k, {
enumerable: true,
get: function() {
return from[k];
}
});
}
});
return from;
}
//# sourceMappingURL=index.js.map

View File

@@ -1,88 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
intervalsManager: null,
timeoutsManager: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
intervalsManager: function() {
return intervalsManager;
},
timeoutsManager: function() {
return timeoutsManager;
}
});
class ResourceManager {
add(resourceArgs) {
const resource = this.create(resourceArgs);
this.resources.push(resource);
return resource;
}
remove(resource) {
this.resources = this.resources.filter((r)=>r !== resource);
this.destroy(resource);
}
removeAll() {
this.resources.forEach(this.destroy);
this.resources = [];
}
constructor(){
this.resources = [];
}
}
class IntervalsManager extends ResourceManager {
create(args) {
// TODO: use the edge runtime provided `setInterval` instead
return webSetIntervalPolyfill(...args);
}
destroy(interval) {
clearInterval(interval);
}
}
class TimeoutsManager extends ResourceManager {
create(args) {
// TODO: use the edge runtime provided `setTimeout` instead
return webSetTimeoutPolyfill(...args);
}
destroy(timeout) {
clearTimeout(timeout);
}
}
function webSetIntervalPolyfill(callback, ms, ...args) {
return setInterval(()=>{
// node's `setInterval` sets `this` to the `Timeout` instance it returned,
// but web `setInterval` always sets `this` to `window`
// see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem
return callback.apply(globalThis, args);
}, ms)[Symbol.toPrimitive]();
}
function webSetTimeoutPolyfill(callback, ms, ...args) {
const wrappedCallback = ()=>{
try {
// node's `setTimeout` sets `this` to the `Timeout` instance it returned,
// but web `setTimeout` always sets `this` to `window`
// see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem
return callback.apply(globalThis, args);
} finally{
// On certain older node versions (<20.16.0, <22.4.0),
// a `setTimeout` whose Timeout was converted to a primitive will leak.
// See: https://github.com/nodejs/node/issues/53335
// We can work around this by explicitly calling `clearTimeout` after the callback runs.
clearTimeout(timeout);
}
};
const timeout = setTimeout(wrappedCallback, ms);
return timeout[Symbol.toPrimitive]();
}
const intervalsManager = new IntervalsManager();
const timeoutsManager = new TimeoutsManager();
//# sourceMappingURL=resource-managers.js.map

View File

@@ -1,137 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ErrorSource: null,
getRuntimeContext: null,
run: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ErrorSource: function() {
return ErrorSource;
},
getRuntimeContext: function() {
return getRuntimeContext;
},
run: function() {
return run;
}
});
const _context = require("./context");
const _bodystreams = require("../../body-streams");
const _builtinrequestcontext = require("../../after/builtin-request-context");
const _routerservercontext = require("../../lib/router-utils/router-server-context");
const ErrorSource = Symbol('SandboxError');
const FORBIDDEN_HEADERS = [
'content-length',
'content-encoding',
'transfer-encoding'
];
/**
* Decorates the runner function making sure all errors it can produce are
* tagged with `edge-server` so they can properly be rendered in dev.
*/ function withTaggedErrors(fn) {
if (process.env.NODE_ENV === 'development') {
const { getServerError } = require('../../dev/node-stack-frames');
return (params)=>fn(params).then((result)=>{
var _result_waitUntil;
return {
...result,
waitUntil: result == null ? void 0 : (_result_waitUntil = result.waitUntil) == null ? void 0 : _result_waitUntil.catch((error)=>{
// TODO: used COMPILER_NAMES.edgeServer instead. Verify that it does not increase the runtime size.
throw getServerError(error, 'edge-server');
})
};
}).catch((error)=>{
// TODO: used COMPILER_NAMES.edgeServer instead
throw getServerError(error, 'edge-server');
});
}
return fn;
}
async function getRuntimeContext(params) {
const { runtime, evaluateInContext } = await (0, _context.getModuleContext)({
moduleName: params.name,
onWarning: params.onWarning ?? (()=>{}),
onError: params.onError ?? (()=>{}),
useCache: params.useCache !== false,
edgeFunctionEntry: params.edgeFunctionEntry,
distDir: params.distDir
});
if (params.incrementalCache) {
runtime.context.globalThis.__incrementalCacheShared = true;
runtime.context.globalThis.__incrementalCache = params.incrementalCache;
}
// expose router server context for access to dev handlers like
// logErrorWithOriginalStack
;
runtime.context.globalThis[_routerservercontext.RouterServerContextSymbol] = _routerservercontext.routerServerGlobal[_routerservercontext.RouterServerContextSymbol];
if (params.serverComponentsHmrCache) {
runtime.context.globalThis.__serverComponentsHmrCache = params.serverComponentsHmrCache;
}
if (params.clientAssetToken) {
runtime.context.globalThis.NEXT_CLIENT_ASSET_SUFFIX = params.clientAssetToken ? `?dpl=${params.clientAssetToken}` : '';
}
for (const paramPath of params.paths){
evaluateInContext(paramPath);
}
return runtime;
}
const run = withTaggedErrors(async function runWithTaggedErrors(params) {
var _params_request_body;
const runtime = await getRuntimeContext(params);
const edgeFunction = (await runtime.context._ENTRIES[`middleware_${params.name}`]).default;
const cloned = ![
'HEAD',
'GET'
].includes(params.request.method) ? (_params_request_body = params.request.body) == null ? void 0 : _params_request_body.cloneBodyStream() : undefined;
const KUint8Array = runtime.evaluate('Uint8Array');
const urlInstance = new URL(params.request.url);
params.request.url = urlInstance.toString();
const headers = new Headers();
for (const [key, value] of Object.entries(params.request.headers)){
headers.set(key, (value == null ? void 0 : value.toString()) ?? '');
}
try {
let result = undefined;
const builtinRequestCtx = {
...(0, _builtinrequestcontext.getBuiltinRequestContext)(),
// FIXME(after):
// arguably, this is an abuse of "@next/request-context" --
// it'd make more sense to simply forward its existing value into the sandbox (in `createModuleContext`)
// but here we're using it to just pass in `waitUntil` regardless if we were running in this context or not.
waitUntil: params.request.waitUntil
};
await _context.edgeSandboxNextRequestContext.run(builtinRequestCtx, ()=>_context.requestStore.run({
headers
}, async ()=>{
result = await edgeFunction({
request: {
...params.request,
body: cloned && (0, _bodystreams.requestToBodyStream)(runtime.context, KUint8Array, cloned)
}
});
for (const headerName of FORBIDDEN_HEADERS){
result.response.headers.delete(headerName);
}
}));
if (!result) throw Object.defineProperty(new Error('Edge function did not return a response'), "__NEXT_ERROR_CODE", {
value: "E332",
enumerable: false,
configurable: true
});
return result;
} finally{
var _params_request_body1;
await ((_params_request_body1 = params.request.body) == null ? void 0 : _params_request_body1.finalize());
}
});
//# sourceMappingURL=sandbox.js.map

View File

@@ -1,192 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
HeadersAdapter: null,
ReadonlyHeadersError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
HeadersAdapter: function() {
return HeadersAdapter;
},
ReadonlyHeadersError: function() {
return ReadonlyHeadersError;
}
});
const _reflect = require("./reflect");
class ReadonlyHeadersError extends Error {
constructor(){
super('Headers cannot be modified. Read more: https://nextjs.org/docs/app/api-reference/functions/headers');
}
static callable() {
throw new ReadonlyHeadersError();
}
}
class HeadersAdapter extends Headers {
constructor(headers){
// We've already overridden the methods that would be called, so we're just
// calling the super constructor to ensure that the instanceof check works.
super();
this.headers = new Proxy(headers, {
get (target, prop, receiver) {
// Because this is just an object, we expect that all "get" operations
// are for properties. If it's a "get" for a symbol, we'll just return
// the symbol.
if (typeof prop === 'symbol') {
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, return undefined.
if (typeof original === 'undefined') return;
// If the original casing exists, return the value.
return _reflect.ReflectAdapter.get(target, original, receiver);
},
set (target, prop, value, receiver) {
if (typeof prop === 'symbol') {
return _reflect.ReflectAdapter.set(target, prop, value, receiver);
}
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, use the prop as the key.
return _reflect.ReflectAdapter.set(target, original ?? prop, value, receiver);
},
has (target, prop) {
if (typeof prop === 'symbol') return _reflect.ReflectAdapter.has(target, prop);
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, return false.
if (typeof original === 'undefined') return false;
// If the original casing exists, return true.
return _reflect.ReflectAdapter.has(target, original);
},
deleteProperty (target, prop) {
if (typeof prop === 'symbol') return _reflect.ReflectAdapter.deleteProperty(target, prop);
const lowercased = prop.toLowerCase();
// Let's find the original casing of the key. This assumes that there is
// no mixed case keys (e.g. "Content-Type" and "content-type") in the
// headers object.
const original = Object.keys(headers).find((o)=>o.toLowerCase() === lowercased);
// If the original casing doesn't exist, return true.
if (typeof original === 'undefined') return true;
// If the original casing exists, delete the property.
return _reflect.ReflectAdapter.deleteProperty(target, original);
}
});
}
/**
* Seals a Headers instance to prevent modification by throwing an error when
* any mutating method is called.
*/ static seal(headers) {
return new Proxy(headers, {
get (target, prop, receiver) {
switch(prop){
case 'append':
case 'delete':
case 'set':
return ReadonlyHeadersError.callable;
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
}
/**
* Merges a header value into a string. This stores multiple values as an
* array, so we need to merge them into a string.
*
* @param value a header value
* @returns a merged header value (a string)
*/ merge(value) {
if (Array.isArray(value)) return value.join(', ');
return value;
}
/**
* Creates a Headers instance from a plain object or a Headers instance.
*
* @param headers a plain object or a Headers instance
* @returns a headers instance
*/ static from(headers) {
if (headers instanceof Headers) return headers;
return new HeadersAdapter(headers);
}
append(name, value) {
const existing = this.headers[name];
if (typeof existing === 'string') {
this.headers[name] = [
existing,
value
];
} else if (Array.isArray(existing)) {
existing.push(value);
} else {
this.headers[name] = value;
}
}
delete(name) {
delete this.headers[name];
}
get(name) {
const value = this.headers[name];
if (typeof value !== 'undefined') return this.merge(value);
return null;
}
has(name) {
return typeof this.headers[name] !== 'undefined';
}
set(name, value) {
this.headers[name] = value;
}
forEach(callbackfn, thisArg) {
for (const [name, value] of this.entries()){
callbackfn.call(thisArg, value, name, this);
}
}
*entries() {
for (const key of Object.keys(this.headers)){
const name = key.toLowerCase();
// We assert here that this is a string because we got it from the
// Object.keys() call above.
const value = this.get(name);
yield [
name,
value
];
}
}
*keys() {
for (const key of Object.keys(this.headers)){
const name = key.toLowerCase();
yield name;
}
}
*values() {
for (const key of Object.keys(this.headers)){
// We assert here that this is a string because we got it from the
// Object.keys() call above.
const value = this.get(key);
yield value;
}
}
[Symbol.iterator]() {
return this.entries();
}
}
//# sourceMappingURL=headers.js.map

View File

@@ -1,142 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextRequestAdapter: null,
ResponseAborted: null,
ResponseAbortedName: null,
createAbortController: null,
signalFromNodeResponse: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextRequestAdapter: function() {
return NextRequestAdapter;
},
ResponseAborted: function() {
return ResponseAborted;
},
ResponseAbortedName: function() {
return ResponseAbortedName;
},
createAbortController: function() {
return createAbortController;
},
signalFromNodeResponse: function() {
return signalFromNodeResponse;
}
});
const _requestmeta = require("../../../request-meta");
const _utils = require("../../utils");
const _request = require("../request");
const _helpers = require("../../../base-http/helpers");
const ResponseAbortedName = 'ResponseAborted';
class ResponseAborted extends Error {
constructor(...args){
super(...args), this.name = ResponseAbortedName;
}
}
function createAbortController(response) {
const controller = new AbortController();
// If `finish` fires first, then `res.end()` has been called and the close is
// just us finishing the stream on our side. If `close` fires first, then we
// know the client disconnected before we finished.
response.once('close', ()=>{
if (response.writableFinished) return;
controller.abort(new ResponseAborted());
});
return controller;
}
function signalFromNodeResponse(response) {
const { errored, destroyed } = response;
if (errored || destroyed) {
return AbortSignal.abort(errored ?? new ResponseAborted());
}
const { signal } = createAbortController(response);
return signal;
}
class NextRequestAdapter {
static fromBaseNextRequest(request, signal) {
if (// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME === 'edge' && (0, _helpers.isWebNextRequest)(request)) {
return NextRequestAdapter.fromWebNextRequest(request);
} else if (// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextRequest)(request)) {
return NextRequestAdapter.fromNodeNextRequest(request, signal);
} else {
throw Object.defineProperty(new Error('Invariant: Unsupported NextRequest type'), "__NEXT_ERROR_CODE", {
value: "E345",
enumerable: false,
configurable: true
});
}
}
static fromNodeNextRequest(request, signal) {
// HEAD and GET requests can not have a body.
let body = null;
if (request.method !== 'GET' && request.method !== 'HEAD' && request.body) {
// @ts-expect-error - this is handled by undici, when streams/web land use it instead
body = request.body;
}
let url;
if (request.url.startsWith('http')) {
url = new URL(request.url);
} else {
// Grab the full URL from the request metadata.
const base = (0, _requestmeta.getRequestMeta)(request, 'initURL');
if (!base || !base.startsWith('http')) {
// Because the URL construction relies on the fact that the URL provided
// is absolute, we need to provide a base URL. We can't use the request
// URL because it's relative, so we use a dummy URL instead.
url = new URL(request.url, 'http://n');
} else {
url = new URL(request.url, base);
}
}
return new _request.NextRequest(url, {
method: request.method,
headers: (0, _utils.fromNodeOutgoingHttpHeaders)(request.headers),
duplex: 'half',
signal,
// geo
// ip
// nextConfig
// body can not be passed if request was aborted
// or we get a Request body was disturbed error
...signal.aborted ? {} : {
body
}
});
}
static fromWebNextRequest(request) {
// HEAD and GET requests can not have a body.
let body = null;
if (request.method !== 'GET' && request.method !== 'HEAD') {
body = request.body;
}
return new _request.NextRequest(request.url, {
method: request.method,
headers: (0, _utils.fromNodeOutgoingHttpHeaders)(request.headers),
duplex: 'half',
signal: request.request.signal,
// geo
// ip
// nextConfig
// body can not be passed if request was aborted
// or we get a Request body was disturbed error
...request.request.signal.aborted ? {} : {
body
}
});
}
}
//# sourceMappingURL=next-request.js.map

View File

@@ -1,30 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ReflectAdapter", {
enumerable: true,
get: function() {
return ReflectAdapter;
}
});
class ReflectAdapter {
static get(target, prop, receiver) {
const value = Reflect.get(target, prop, receiver);
if (typeof value === 'function') {
return value.bind(target);
}
return value;
}
static set(target, prop, value, receiver) {
return Reflect.set(target, prop, value, receiver);
}
static has(target, prop) {
return Reflect.has(target, prop);
}
static deleteProperty(target, prop) {
return Reflect.deleteProperty(target, prop);
}
}
//# sourceMappingURL=reflect.js.map

View File

@@ -1,211 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
MutableRequestCookiesAdapter: null,
ReadonlyRequestCookiesError: null,
RequestCookiesAdapter: null,
appendMutableCookies: null,
areCookiesMutableInCurrentPhase: null,
createCookiesWithMutableAccessCheck: null,
getModifiedCookieValues: null,
responseCookiesToRequestCookies: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
MutableRequestCookiesAdapter: function() {
return MutableRequestCookiesAdapter;
},
ReadonlyRequestCookiesError: function() {
return ReadonlyRequestCookiesError;
},
RequestCookiesAdapter: function() {
return RequestCookiesAdapter;
},
appendMutableCookies: function() {
return appendMutableCookies;
},
areCookiesMutableInCurrentPhase: function() {
return areCookiesMutableInCurrentPhase;
},
createCookiesWithMutableAccessCheck: function() {
return createCookiesWithMutableAccessCheck;
},
getModifiedCookieValues: function() {
return getModifiedCookieValues;
},
responseCookiesToRequestCookies: function() {
return responseCookiesToRequestCookies;
}
});
const _cookies = require("../cookies");
const _reflect = require("./reflect");
const _workasyncstorageexternal = require("../../../app-render/work-async-storage.external");
const _actionrevalidationkind = require("../../../../shared/lib/action-revalidation-kind");
class ReadonlyRequestCookiesError extends Error {
constructor(){
super('Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#options');
}
static callable() {
throw new ReadonlyRequestCookiesError();
}
}
class RequestCookiesAdapter {
static seal(cookies) {
return new Proxy(cookies, {
get (target, prop, receiver) {
switch(prop){
case 'clear':
case 'delete':
case 'set':
return ReadonlyRequestCookiesError.callable;
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
}
}
const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for('next.mutated.cookies');
function getModifiedCookieValues(cookies) {
const modified = cookies[SYMBOL_MODIFY_COOKIE_VALUES];
if (!modified || !Array.isArray(modified) || modified.length === 0) {
return [];
}
return modified;
}
function appendMutableCookies(headers, mutableCookies) {
const modifiedCookieValues = getModifiedCookieValues(mutableCookies);
if (modifiedCookieValues.length === 0) {
return false;
}
// Return a new response that extends the response with
// the modified cookies as fallbacks. `res` cookies
// will still take precedence.
const resCookies = new _cookies.ResponseCookies(headers);
const returnedCookies = resCookies.getAll();
// Set the modified cookies as fallbacks.
for (const cookie of modifiedCookieValues){
resCookies.set(cookie);
}
// Set the original cookies as the final values.
for (const cookie of returnedCookies){
resCookies.set(cookie);
}
return true;
}
class MutableRequestCookiesAdapter {
static wrap(cookies, onUpdateCookies) {
const responseCookies = new _cookies.ResponseCookies(new Headers());
for (const cookie of cookies.getAll()){
responseCookies.set(cookie);
}
let modifiedValues = [];
const modifiedCookies = new Set();
const updateResponseCookies = ()=>{
// TODO-APP: change method of getting workStore
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
if (workStore) {
workStore.pathWasRevalidated = _actionrevalidationkind.ActionDidRevalidateStaticAndDynamic;
}
const allCookies = responseCookies.getAll();
modifiedValues = allCookies.filter((c)=>modifiedCookies.has(c.name));
if (onUpdateCookies) {
const serializedCookies = [];
for (const cookie of modifiedValues){
const tempCookies = new _cookies.ResponseCookies(new Headers());
tempCookies.set(cookie);
serializedCookies.push(tempCookies.toString());
}
onUpdateCookies(serializedCookies);
}
};
const wrappedCookies = new Proxy(responseCookies, {
get (target, prop, receiver) {
switch(prop){
// A special symbol to get the modified cookie values
case SYMBOL_MODIFY_COOKIE_VALUES:
return modifiedValues;
// TODO: Throw error if trying to set a cookie after the response
// headers have been set.
case 'delete':
return function(...args) {
modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name);
try {
target.delete(...args);
return wrappedCookies;
} finally{
updateResponseCookies();
}
};
case 'set':
return function(...args) {
modifiedCookies.add(typeof args[0] === 'string' ? args[0] : args[0].name);
try {
target.set(...args);
return wrappedCookies;
} finally{
updateResponseCookies();
}
};
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
return wrappedCookies;
}
}
function createCookiesWithMutableAccessCheck(requestStore) {
const wrappedCookies = new Proxy(requestStore.mutableCookies, {
get (target, prop, receiver) {
switch(prop){
case 'delete':
return function(...args) {
ensureCookiesAreStillMutable(requestStore, 'cookies().delete');
target.delete(...args);
return wrappedCookies;
};
case 'set':
return function(...args) {
ensureCookiesAreStillMutable(requestStore, 'cookies().set');
target.set(...args);
return wrappedCookies;
};
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
return wrappedCookies;
}
function areCookiesMutableInCurrentPhase(requestStore) {
return requestStore.phase === 'action';
}
/** Ensure that cookies() starts throwing on mutation
* if we changed phases and can no longer mutate.
*
* This can happen when going:
* 'render' -> 'after'
* 'action' -> 'render'
* */ function ensureCookiesAreStillMutable(requestStore, _callingExpression) {
if (!areCookiesMutableInCurrentPhase(requestStore)) {
// TODO: maybe we can give a more precise error message based on callingExpression?
throw new ReadonlyRequestCookiesError();
}
}
function responseCookiesToRequestCookies(responseCookies) {
const requestCookies = new _cookies.RequestCookies(new Headers());
for (const cookie of responseCookies.getAll()){
requestCookies.set(cookie);
}
return requestCookies;
}
//# sourceMappingURL=request-cookies.js.map

View File

@@ -1,29 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
RequestCookies: null,
ResponseCookies: null,
stringifyCookie: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
RequestCookies: function() {
return _cookies.RequestCookies;
},
ResponseCookies: function() {
return _cookies.ResponseCookies;
},
stringifyCookie: function() {
return _cookies.stringifyCookie;
}
});
const _cookies = require("next/dist/compiled/@edge-runtime/cookies");
//# sourceMappingURL=cookies.js.map

View File

@@ -1,98 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
NextFetchEvent: null,
getWaitUntilPromiseFromEvent: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
NextFetchEvent: function() {
return NextFetchEvent;
},
getWaitUntilPromiseFromEvent: function() {
return getWaitUntilPromiseFromEvent;
}
});
const _error = require("../error");
const responseSymbol = Symbol('response');
const passThroughSymbol = Symbol('passThrough');
const waitUntilSymbol = Symbol('waitUntil');
class FetchEvent {
constructor(_request, waitUntil){
this[passThroughSymbol] = false;
this[waitUntilSymbol] = waitUntil ? {
kind: 'external',
function: waitUntil
} : {
kind: 'internal',
promises: []
};
}
// TODO: is this dead code? NextFetchEvent never lets this get called
respondWith(response) {
if (!this[responseSymbol]) {
this[responseSymbol] = Promise.resolve(response);
}
}
// TODO: is this dead code? passThroughSymbol is unused
passThroughOnException() {
this[passThroughSymbol] = true;
}
waitUntil(promise) {
if (this[waitUntilSymbol].kind === 'external') {
// if we received an external waitUntil, we delegate to it
// TODO(after): this will make us not go through `getServerError(error, 'edge-server')` in `sandbox`
const waitUntil = this[waitUntilSymbol].function;
return waitUntil(promise);
} else {
// if we didn't receive an external waitUntil, we make it work on our own
// (and expect the caller to do something with the promises)
this[waitUntilSymbol].promises.push(promise);
}
}
}
function getWaitUntilPromiseFromEvent(event) {
return event[waitUntilSymbol].kind === 'internal' ? Promise.all(event[waitUntilSymbol].promises).then(()=>{}) : undefined;
}
class NextFetchEvent extends FetchEvent {
constructor(params){
var _params_context;
super(params.request, (_params_context = params.context) == null ? void 0 : _params_context.waitUntil);
this.sourcePage = params.page;
}
/**
* @deprecated The `request` is now the first parameter and the API is now async.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ get request() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
/**
* @deprecated Using `respondWith` is no longer needed.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ respondWith() {
throw Object.defineProperty(new _error.PageSignatureError({
page: this.sourcePage
}), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
}
//# sourceMappingURL=fetch-event.js.map

View File

@@ -1,22 +0,0 @@
/**
* @deprecated ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead.
* Migration with codemods: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#next-og-import
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ImageResponse", {
enumerable: true,
get: function() {
return ImageResponse;
}
});
function ImageResponse() {
throw Object.defineProperty(new Error('ImageResponse moved from "next/server" to "next/og" since Next.js 14, please import from "next/og" instead'), "__NEXT_ERROR_CODE", {
value: "E183",
enumerable: false,
configurable: true
});
}
//# sourceMappingURL=image-response.js.map

View File

@@ -1,99 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
INTERNALS: null,
NextRequest: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
INTERNALS: function() {
return INTERNALS;
},
NextRequest: function() {
return NextRequest;
}
});
const _nexturl = require("../next-url");
const _utils = require("../utils");
const _error = require("../error");
const _cookies = require("./cookies");
const INTERNALS = Symbol('internal request');
class NextRequest extends Request {
constructor(input, init = {}){
const url = typeof input !== 'string' && 'url' in input ? input.url : String(input);
(0, _utils.validateURL)(url);
// node Request instance requires duplex option when a body
// is present or it errors, we don't handle this for
// Request being passed in since it would have already
// errored if this wasn't configured
if (process.env.NEXT_RUNTIME !== 'edge') {
if (init.body && init.duplex !== 'half') {
init.duplex = 'half';
}
}
if (input instanceof Request) super(input, init);
else super(url, init);
const nextUrl = new _nexturl.NextURL(url, {
headers: (0, _utils.toNodeOutgoingHttpHeaders)(this.headers),
nextConfig: init.nextConfig
});
this[INTERNALS] = {
cookies: new _cookies.RequestCookies(this.headers),
nextUrl,
url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url : nextUrl.toString()
};
}
[Symbol.for('edge-runtime.inspect.custom')]() {
return {
cookies: this.cookies,
nextUrl: this.nextUrl,
url: this.url,
// rest of props come from Request
bodyUsed: this.bodyUsed,
cache: this.cache,
credentials: this.credentials,
destination: this.destination,
headers: Object.fromEntries(this.headers),
integrity: this.integrity,
keepalive: this.keepalive,
method: this.method,
mode: this.mode,
redirect: this.redirect,
referrer: this.referrer,
referrerPolicy: this.referrerPolicy,
signal: this.signal
};
}
get cookies() {
return this[INTERNALS].cookies;
}
get nextUrl() {
return this[INTERNALS].nextUrl;
}
/**
* @deprecated
* `page` has been deprecated in favour of `URLPattern`.
* Read more: https://nextjs.org/docs/messages/middleware-request-page
*/ get page() {
throw new _error.RemovedPageError();
}
/**
* @deprecated
* `ua` has been removed in favour of \`userAgent\` function.
* Read more: https://nextjs.org/docs/messages/middleware-parse-user-agent
*/ get ua() {
throw new _error.RemovedUAError();
}
get url() {
return this[INTERNALS].url;
}
}
//# sourceMappingURL=request.js.map

View File

@@ -1,136 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "NextResponse", {
enumerable: true,
get: function() {
return NextResponse;
}
});
const _cookies = require("../../web/spec-extension/cookies");
const _nexturl = require("../next-url");
const _utils = require("../utils");
const _reflect = require("./adapters/reflect");
const _cookies1 = require("./cookies");
const INTERNALS = Symbol('internal response');
const REDIRECTS = new Set([
301,
302,
303,
307,
308
]);
function handleMiddlewareField(init, headers) {
var _init_request;
if (init == null ? void 0 : (_init_request = init.request) == null ? void 0 : _init_request.headers) {
if (!(init.request.headers instanceof Headers)) {
throw Object.defineProperty(new Error('request.headers must be an instance of Headers'), "__NEXT_ERROR_CODE", {
value: "E119",
enumerable: false,
configurable: true
});
}
const keys = [];
for (const [key, value] of init.request.headers){
headers.set('x-middleware-request-' + key, value);
keys.push(key);
}
headers.set('x-middleware-override-headers', keys.join(','));
}
}
class NextResponse extends Response {
constructor(body, init = {}){
super(body, init);
const headers = this.headers;
const cookies = new _cookies1.ResponseCookies(headers);
const cookiesProxy = new Proxy(cookies, {
get (target, prop, receiver) {
switch(prop){
case 'delete':
case 'set':
{
return (...args)=>{
const result = Reflect.apply(target[prop], target, args);
const newHeaders = new Headers(headers);
if (result instanceof _cookies1.ResponseCookies) {
headers.set('x-middleware-set-cookie', result.getAll().map((cookie)=>(0, _cookies.stringifyCookie)(cookie)).join(','));
}
handleMiddlewareField(init, newHeaders);
return result;
};
}
default:
return _reflect.ReflectAdapter.get(target, prop, receiver);
}
}
});
this[INTERNALS] = {
cookies: cookiesProxy,
url: init.url ? new _nexturl.NextURL(init.url, {
headers: (0, _utils.toNodeOutgoingHttpHeaders)(headers),
nextConfig: init.nextConfig
}) : undefined
};
}
[Symbol.for('edge-runtime.inspect.custom')]() {
return {
cookies: this.cookies,
url: this.url,
// rest of props come from Response
body: this.body,
bodyUsed: this.bodyUsed,
headers: Object.fromEntries(this.headers),
ok: this.ok,
redirected: this.redirected,
status: this.status,
statusText: this.statusText,
type: this.type
};
}
get cookies() {
return this[INTERNALS].cookies;
}
static json(body, init) {
const response = Response.json(body, init);
return new NextResponse(response.body, response);
}
static redirect(url, init) {
const status = typeof init === 'number' ? init : (init == null ? void 0 : init.status) ?? 307;
if (!REDIRECTS.has(status)) {
throw Object.defineProperty(new RangeError('Failed to execute "redirect" on "response": Invalid status code'), "__NEXT_ERROR_CODE", {
value: "E529",
enumerable: false,
configurable: true
});
}
const initObj = typeof init === 'object' ? init : {};
const headers = new Headers(initObj == null ? void 0 : initObj.headers);
headers.set('Location', (0, _utils.validateURL)(url));
return new NextResponse(null, {
...initObj,
headers,
status
});
}
static rewrite(destination, init) {
const headers = new Headers(init == null ? void 0 : init.headers);
headers.set('x-middleware-rewrite', (0, _utils.validateURL)(destination));
handleMiddlewareField(init, headers);
return new NextResponse(null, {
...init,
headers
});
}
static next(init) {
const headers = new Headers(init == null ? void 0 : init.headers);
headers.set('x-middleware-next', '1');
handleMiddlewareField(init, headers);
return new NextResponse(null, {
...init,
headers
});
}
}
//# sourceMappingURL=response.js.map

View File

@@ -1,214 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
refresh: null,
revalidatePath: null,
revalidateTag: null,
updateTag: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
refresh: function() {
return refresh;
},
revalidatePath: function() {
return revalidatePath;
},
revalidateTag: function() {
return revalidateTag;
},
updateTag: function() {
return updateTag;
}
});
const _dynamicrendering = require("../../app-render/dynamic-rendering");
const _utils = require("../../../shared/lib/router/utils");
const _constants = require("../../../lib/constants");
const _workasyncstorageexternal = require("../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _hooksservercontext = require("../../../client/components/hooks-server-context");
const _invarianterror = require("../../../shared/lib/invariant-error");
const _actionrevalidationkind = require("../../../shared/lib/action-revalidation-kind");
const _removetrailingslash = require("../../../shared/lib/router/utils/remove-trailing-slash");
function revalidateTag(tag, profile) {
if (!profile) {
console.warn('"revalidateTag" without the second argument is now deprecated, add second argument of "max" or use "updateTag". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg');
}
return revalidate([
tag
], `revalidateTag ${tag}`, profile);
}
function updateTag(tag) {
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
// TODO: change this after investigating why phase: 'action' is
// set for route handlers
if (!workStore || workStore.page.endsWith('/route')) {
throw Object.defineProperty(new Error('updateTag can only be called from within a Server Action. ' + 'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' + 'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'), "__NEXT_ERROR_CODE", {
value: "E872",
enumerable: false,
configurable: true
});
}
// updateTag uses immediate expiration (no profile) without deprecation warning
return revalidate([
tag
], `updateTag ${tag}`, undefined);
}
function refresh() {
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
if (!workStore || workStore.page.endsWith('/route') || (workUnitStore == null ? void 0 : workUnitStore.phase) !== 'action') {
throw Object.defineProperty(new Error('refresh can only be called from within a Server Action. ' + 'See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh'), "__NEXT_ERROR_CODE", {
value: "E870",
enumerable: false,
configurable: true
});
}
if (workStore) {
// The Server Action version of refresh() only revalidates the dynamic data
// on the client. It doesn't affect cached data.
workStore.pathWasRevalidated = _actionrevalidationkind.ActionDidRevalidateDynamicOnly;
}
}
function revalidatePath(originalPath, type) {
if (originalPath.length > _constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {
console.warn(`Warning: revalidatePath received "${originalPath}" which exceeded max length of ${_constants.NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);
return;
}
let normalizedPath = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${(0, _removetrailingslash.removeTrailingSlash)(originalPath)}`;
if (type) {
normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`;
} else if ((0, _utils.isDynamicRoute)(originalPath)) {
console.warn(`Warning: a dynamic page path "${originalPath}" was passed to "revalidatePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);
}
const tags = [
normalizedPath
];
if (normalizedPath === `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/`) {
tags.push(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/index`);
} else if (normalizedPath === `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {
tags.push(`${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}/`);
}
return revalidate(tags, `revalidatePath ${originalPath}`);
}
function revalidate(tags, expression, profile) {
var _store_cacheLifeProfiles;
const store = _workasyncstorageexternal.workAsyncStorage.getStore();
if (!store || !store.incrementalCache) {
throw Object.defineProperty(new Error(`Invariant: static generation store missing in ${expression}`), "__NEXT_ERROR_CODE", {
value: "E263",
enumerable: false,
configurable: true
});
}
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
if (workUnitStore) {
if (workUnitStore.phase === 'render') {
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" during render which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E7",
enumerable: false,
configurable: true
});
}
switch(workUnitStore.type){
case 'cache':
case 'private-cache':
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" inside a "use cache" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E181",
enumerable: false,
configurable: true
});
case 'unstable-cache':
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E306",
enumerable: false,
configurable: true
});
case 'generate-static-params':
throw Object.defineProperty(new Error(`Route ${store.route} used "${expression}" inside \`generateStaticParams\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`), "__NEXT_ERROR_CODE", {
value: "E1127",
enumerable: false,
configurable: true
});
case 'prerender':
case 'prerender-runtime':
// cacheComponents Prerender
const error = Object.defineProperty(new Error(`Route ${store.route} used ${expression} without first calling \`await connection()\`.`), "__NEXT_ERROR_CODE", {
value: "E406",
enumerable: false,
configurable: true
});
return (0, _dynamicrendering.abortAndThrowOnSynchronousRequestDataAccess)(store.route, expression, error, workUnitStore);
case 'prerender-client':
case 'validation-client':
throw Object.defineProperty(new _invarianterror.InvariantError(`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being included in client components statically, but did not in this case.`), "__NEXT_ERROR_CODE", {
value: "E693",
enumerable: false,
configurable: true
});
case 'prerender-ppr':
return (0, _dynamicrendering.postponeWithTracking)(store.route, expression, workUnitStore.dynamicTracking);
case 'prerender-legacy':
workUnitStore.revalidate = 0;
const err = Object.defineProperty(new _hooksservercontext.DynamicServerError(`Route ${store.route} couldn't be rendered statically because it used \`${expression}\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`), "__NEXT_ERROR_CODE", {
value: "E558",
enumerable: false,
configurable: true
});
store.dynamicUsageDescription = expression;
store.dynamicUsageStack = err.stack;
throw err;
case 'request':
if (process.env.NODE_ENV !== 'production') {
// TODO: This is most likely incorrect. It would lead to the ISR
// status being flipped when revalidating a static page with a server
// action.
workUnitStore.usedDynamic = true;
// TODO(restart-on-cache-miss): we should do a sync IO error here in dev
// to match prerender behavior
}
break;
default:
workUnitStore;
}
}
if (!store.pendingRevalidatedTags) {
store.pendingRevalidatedTags = [];
}
for (const tag of tags){
const existingIndex = store.pendingRevalidatedTags.findIndex((item)=>{
if (item.tag !== tag) return false;
// Compare profiles: both strings, both objects, or both undefined
if (typeof item.profile === 'string' && typeof profile === 'string') {
return item.profile === profile;
}
if (typeof item.profile === 'object' && typeof profile === 'object') {
return JSON.stringify(item.profile) === JSON.stringify(profile);
}
return item.profile === profile;
});
if (existingIndex === -1) {
store.pendingRevalidatedTags.push({
tag,
profile
});
}
}
// if profile is provided and this is a stale-while-revalidate
// update we do not mark the path as revalidated so that server
// actions don't pull their own writes
const cacheLife = profile && typeof profile === 'object' ? profile : profile && typeof profile === 'string' && (store == null ? void 0 : (_store_cacheLifeProfiles = store.cacheLifeProfiles) == null ? void 0 : _store_cacheLifeProfiles[profile]) ? store.cacheLifeProfiles[profile] : undefined;
if (!profile || (cacheLife == null ? void 0 : cacheLife.expire) === 0) {
// TODO: only revalidate if the path matches
store.pathWasRevalidated = _actionrevalidationkind.ActionDidRevalidateStaticAndDynamic;
}
}
//# sourceMappingURL=revalidate.js.map

View File

@@ -1,289 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "unstable_cache", {
enumerable: true,
get: function() {
return unstable_cache;
}
});
const _constants = require("../../../lib/constants");
const _patchfetch = require("../../lib/patch-fetch");
const _workasyncstorageexternal = require("../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _responsecache = require("../../response-cache");
let noStoreFetchIdx = 0;
async function cacheNewResult(result, incrementalCache, cacheKey, tags, revalidate, fetchIdx, fetchUrl) {
await incrementalCache.set(cacheKey, {
kind: _responsecache.CachedRouteKind.FETCH,
data: {
headers: {},
// TODO: handle non-JSON values?
body: JSON.stringify(result),
status: 200,
url: ''
},
revalidate: typeof revalidate !== 'number' ? _constants.CACHE_ONE_YEAR_SECONDS : revalidate
}, {
fetchCache: true,
tags,
fetchIdx,
fetchUrl
});
return;
}
function unstable_cache(cb, keyParts, options = {}) {
if (options.revalidate === 0) {
throw Object.defineProperty(new Error(`Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${cb.toString()}`), "__NEXT_ERROR_CODE", {
value: "E57",
enumerable: false,
configurable: true
});
}
// Validate the tags provided are valid
const tags = options.tags ? (0, _patchfetch.validateTags)(options.tags, `unstable_cache ${cb.toString()}`) : [];
// Validate the revalidate options
(0, _patchfetch.validateRevalidate)(options.revalidate, `unstable_cache ${cb.name || cb.toString()}`);
// Stash the fixed part of the key at construction time. The invocation key will combine
// the fixed key with the arguments when actually called
// @TODO if cb.toString() is long we should hash it
// @TODO come up with a collision-free way to combine keyParts
// @TODO consider validating the keyParts are all strings. TS can't provide runtime guarantees
// and the error produced by accidentally using something that cannot be safely coerced is likely
// hard to debug
const fixedKey = `${cb.toString()}-${Array.isArray(keyParts) && keyParts.join(',')}`;
const cachedCb = async (...args)=>{
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
// We must be able to find the incremental cache otherwise we throw
const maybeIncrementalCache = (workStore == null ? void 0 : workStore.incrementalCache) || globalThis.__incrementalCache;
if (!maybeIncrementalCache) {
throw Object.defineProperty(new Error(`Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`), "__NEXT_ERROR_CODE", {
value: "E469",
enumerable: false,
configurable: true
});
}
const incrementalCache = maybeIncrementalCache;
const cacheSignal = workUnitStore ? (0, _workunitasyncstorageexternal.getCacheSignal)(workUnitStore) : null;
if (cacheSignal) {
cacheSignal.beginRead();
}
try {
// If there's no request store, we aren't in a request (or we're not in
// app router) and if there's no static generation store, we aren't in app
// router. Default to an empty pathname and search params when there's no
// request store or static generation store available.
const fetchUrlPrefix = workStore && workUnitStore ? getFetchUrlPrefix(workStore, workUnitStore) : '';
// Construct the complete cache key for this function invocation
// @TODO stringify is likely not safe here. We will coerce undefined to null which will make
// the keyspace smaller than the execution space
const invocationKey = `${fixedKey}-${JSON.stringify(args)}`;
const cacheKey = await incrementalCache.generateCacheKey(invocationKey);
// $urlWithPath,$sortedQueryStringKeys,$hashOfEveryThingElse
const fetchUrl = `unstable_cache ${fetchUrlPrefix} ${cb.name ? ` ${cb.name}` : cacheKey}`;
const fetchIdx = (workStore ? workStore.nextFetchId : noStoreFetchIdx) ?? 1;
const implicitTags = workUnitStore == null ? void 0 : workUnitStore.implicitTags;
const innerCacheStore = {
type: 'unstable-cache',
phase: 'render',
implicitTags,
draftMode: workUnitStore && workStore && (0, _workunitasyncstorageexternal.getDraftModeProviderForCacheScope)(workStore, workUnitStore),
rootParams: undefined
};
if (workStore) {
workStore.nextFetchId = fetchIdx + 1;
// We are in an App Router context. We try to return the cached entry if it exists and is valid
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it.
let isNestedUnstableCache = false;
if (workUnitStore) {
switch(workUnitStore.type){
case 'cache':
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
// We update the store's revalidate property if the option.revalidate is a higher precedence
// options.revalidate === undefined doesn't affect timing.
// options.revalidate === false doesn't shrink timing. it stays at the maximum.
if (typeof options.revalidate === 'number') {
if (workUnitStore.revalidate < options.revalidate) {
// The store is already revalidating on a shorter time interval, leave it alone
} else {
workUnitStore.revalidate = options.revalidate;
}
}
// We need to accumulate the tags for this invocation within the store
const collectedTags = workUnitStore.tags;
if (collectedTags === null) {
workUnitStore.tags = tags.slice();
} else {
for (const tag of tags){
// @TODO refactor tags to be a set to avoid this O(n) lookup
if (!collectedTags.includes(tag)) {
collectedTags.push(tag);
}
}
}
break;
case 'unstable-cache':
isNestedUnstableCache = true;
break;
case 'prerender-client':
case 'validation-client':
case 'request':
case 'generate-static-params':
break;
default:
workUnitStore;
}
}
if (// when we are nested inside of other unstable_cache's
// we should bypass cache similar to fetches
!isNestedUnstableCache && workStore.fetchCache !== 'force-no-store' && !workStore.isOnDemandRevalidate && !incrementalCache.isOnDemandRevalidate && !workStore.isDraftMode) {
// We attempt to get the current cache entry from the incremental cache.
const cacheEntry = await incrementalCache.get(cacheKey, {
kind: _responsecache.IncrementalCacheKind.FETCH,
revalidate: options.revalidate,
tags,
softTags: implicitTags == null ? void 0 : implicitTags.tags,
fetchIdx,
fetchUrl
});
if (cacheEntry && cacheEntry.value) {
// The entry exists and has a value
if (cacheEntry.value.kind !== _responsecache.CachedRouteKind.FETCH) {
// The entry is invalid and we need a special warning
// @TODO why do we warn this way? Should this just be an error? How are these errors surfaced
// so bugs can be reported
// @TODO the invocation key can have sensitive data in it. we should not log this entire object
console.error(`Invariant invalid cacheEntry returned for ${invocationKey}`);
// will fall through to generating a new cache entry below
} else {
// We have a valid cache entry so we will be returning it. We also check to see if we need
// to background revalidate it by checking if it is stale.
const cachedResponse = cacheEntry.value.data.body !== undefined ? JSON.parse(cacheEntry.value.data.body) : undefined;
if (cacheEntry.isStale) {
if (!workStore.pendingRevalidates) {
workStore.pendingRevalidates = {};
}
// Check if there's already a pending revalidation to avoid duplicate work
if (!workStore.pendingRevalidates[invocationKey]) {
// Create the revalidation promise
const revalidationPromise = _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args).then(async (result)=>{
await cacheNewResult(result, incrementalCache, cacheKey, tags, options.revalidate, fetchIdx, fetchUrl);
return result;
}).catch((err)=>{
// @TODO This error handling seems wrong. We swallow the error?
console.error(`revalidating cache with key: ${invocationKey}`, err);
// Return the stale value on error for foreground revalidation
return cachedResponse;
});
// Attach the empty catch here so we don't get a "unhandled promise
// rejection" warning. (Behavior is matched with patch-fetch)
if (workStore.isStaticGeneration) {
revalidationPromise.catch(()=>{});
}
workStore.pendingRevalidates[invocationKey] = revalidationPromise;
}
// Check if we need to do foreground revalidation
if (workStore.isStaticGeneration) {
// When the page is revalidating and the cache entry is stale,
// we need to wait for fresh data (blocking revalidate)
return workStore.pendingRevalidates[invocationKey];
}
// Otherwise, we're doing background revalidation - return stale immediately
}
// We had a valid cache entry so we return it here
return cachedResponse;
}
}
}
// If we got this far then we had an invalid cache entry and need to generate a new one
const result = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args);
if (!workStore.isDraftMode) {
if (!workStore.pendingRevalidates) {
workStore.pendingRevalidates = {};
}
// We need to push the cache result promise to pending
// revalidates otherwise it won't be awaited and is just
// dangling
workStore.pendingRevalidates[invocationKey] = cacheNewResult(result, incrementalCache, cacheKey, tags, options.revalidate, fetchIdx, fetchUrl);
}
return result;
} else {
noStoreFetchIdx += 1;
// We are in Pages Router or were called outside of a render. We don't have a store
// so we just call the callback directly when it needs to run.
// If the entry is fresh we return it. If the entry is stale we return it but revalidate the entry in
// the background. If the entry is missing or invalid we generate a new entry and return it.
if (!incrementalCache.isOnDemandRevalidate) {
// We aren't doing an on demand revalidation so we check use the cache if valid
const cacheEntry = await incrementalCache.get(cacheKey, {
kind: _responsecache.IncrementalCacheKind.FETCH,
revalidate: options.revalidate,
tags,
fetchIdx,
fetchUrl,
softTags: implicitTags == null ? void 0 : implicitTags.tags
});
if (cacheEntry && cacheEntry.value) {
// The entry exists and has a value
if (cacheEntry.value.kind !== _responsecache.CachedRouteKind.FETCH) {
// The entry is invalid and we need a special warning
// @TODO why do we warn this way? Should this just be an error? How are these errors surfaced
// so bugs can be reported
console.error(`Invariant invalid cacheEntry returned for ${invocationKey}`);
// will fall through to generating a new cache entry below
} else if (!cacheEntry.isStale) {
// We have a valid cache entry and it is fresh so we return it
return cacheEntry.value.data.body !== undefined ? JSON.parse(cacheEntry.value.data.body) : undefined;
}
}
}
// If we got this far then we had an invalid cache entry and need to generate a new one
const result = await _workunitasyncstorageexternal.workUnitAsyncStorage.run(innerCacheStore, cb, ...args);
// we need to wait setting the new cache result here as
// we don't have pending revalidates on workStore to
// push to and we can't have a dangling promise
await cacheNewResult(result, incrementalCache, cacheKey, tags, options.revalidate, fetchIdx, fetchUrl);
return result;
}
} finally{
if (cacheSignal) {
cacheSignal.endRead();
}
}
};
// TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary
return cachedCb;
}
function getFetchUrlPrefix(workStore, workUnitStore) {
switch(workUnitStore.type){
case 'request':
const pathname = workUnitStore.url.pathname;
const searchParams = new URLSearchParams(workUnitStore.url.search);
const sortedSearch = [
...searchParams.keys()
].sort((a, b)=>a.localeCompare(b)).map((key)=>`${key}=${searchParams.get(key)}`).join('&');
return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`;
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return workStore.route;
default:
return workUnitStore;
}
}
//# sourceMappingURL=unstable-cache.js.map

View File

@@ -1,51 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "unstable_noStore", {
enumerable: true,
get: function() {
return unstable_noStore;
}
});
const _workasyncstorageexternal = require("../../app-render/work-async-storage.external");
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
const _dynamicrendering = require("../../app-render/dynamic-rendering");
function unstable_noStore() {
const callingExpression = 'unstable_noStore()';
const store = _workasyncstorageexternal.workAsyncStorage.getStore();
const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore();
if (!store) {
// This generally implies we are being called in Pages router. We should probably not support
// unstable_noStore in contexts outside of `react-server` condition but since we historically
// have not errored here previously, we maintain that behavior for now.
return;
} else if (store.forceStatic) {
return;
} else {
store.isUnstableNoStore = true;
if (workUnitStore) {
switch(workUnitStore.type){
case 'prerender':
case 'prerender-client':
case 'validation-client':
case 'prerender-runtime':
// unstable_noStore() is a noop in Dynamic I/O.
return;
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break;
default:
workUnitStore;
}
}
(0, _dynamicrendering.markCurrentScopeAsDynamic)(store, workUnitStore, callingExpression);
}
}
//# sourceMappingURL=unstable-no-store.js.map

View File

@@ -1,14 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "URLPattern", {
enumerable: true,
get: function() {
return GlobalURLPattern;
}
});
const GlobalURLPattern = // @ts-expect-error: URLPattern is not available in Node.js
typeof URLPattern === 'undefined' ? undefined : URLPattern;
//# sourceMappingURL=url-pattern.js.map

View File

@@ -1,46 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
isBot: null,
userAgent: null,
userAgentFromString: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
isBot: function() {
return isBot;
},
userAgent: function() {
return userAgent;
},
userAgentFromString: function() {
return userAgentFromString;
}
});
const _uaparserjs = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/ua-parser-js"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function isBot(input) {
return /Googlebot|Mediapartners-Google|AdsBot-Google|googleweblight|Storebot-Google|Google-PageRenderer|Google-InspectionTool|Bingbot|BingPreview|Slurp|DuckDuckBot|baiduspider|yandex|sogou|LinkedInBot|bitlybot|tumblr|vkShare|quora link preview|facebookexternalhit|facebookcatalog|Twitterbot|applebot|redditbot|Slackbot|Discordbot|WhatsApp|SkypeUriPreview|ia_archiver|GPTBot/i.test(input);
}
function userAgentFromString(input) {
return {
...(0, _uaparserjs.default)(input),
isBot: input === undefined ? false : isBot(input)
};
}
function userAgent({ headers }) {
return userAgentFromString(headers.get('user-agent') || undefined);
}
//# sourceMappingURL=user-agent.js.map

View File

@@ -1,6 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

View File

@@ -1,151 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
fromNodeOutgoingHttpHeaders: null,
normalizeNextQueryParam: null,
splitCookiesString: null,
toNodeOutgoingHttpHeaders: null,
validateURL: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
fromNodeOutgoingHttpHeaders: function() {
return fromNodeOutgoingHttpHeaders;
},
normalizeNextQueryParam: function() {
return normalizeNextQueryParam;
},
splitCookiesString: function() {
return splitCookiesString;
},
toNodeOutgoingHttpHeaders: function() {
return toNodeOutgoingHttpHeaders;
},
validateURL: function() {
return validateURL;
}
});
const _constants = require("../../lib/constants");
function fromNodeOutgoingHttpHeaders(nodeHeaders) {
const headers = new Headers();
for (let [key, value] of Object.entries(nodeHeaders)){
const values = Array.isArray(value) ? value : [
value
];
for (let v of values){
if (typeof v === 'undefined') continue;
if (typeof v === 'number') {
v = v.toString();
}
headers.append(key, v);
}
}
return headers;
}
function splitCookiesString(cookiesString) {
var cookiesStrings = [];
var pos = 0;
var start;
var ch;
var lastComma;
var nextStart;
var cookiesSeparatorFound;
function skipWhitespace() {
while(pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))){
pos += 1;
}
return pos < cookiesString.length;
}
function notSpecialChar() {
ch = cookiesString.charAt(pos);
return ch !== '=' && ch !== ';' && ch !== ',';
}
while(pos < cookiesString.length){
start = pos;
cookiesSeparatorFound = false;
while(skipWhitespace()){
ch = cookiesString.charAt(pos);
if (ch === ',') {
// ',' is a cookie separator if we have later first '=', not ';' or ','
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while(pos < cookiesString.length && notSpecialChar()){
pos += 1;
}
// currently special character
if (pos < cookiesString.length && cookiesString.charAt(pos) === '=') {
// we found cookies separator
cookiesSeparatorFound = true;
// pos is inside the next cookie, so back up and return it.
pos = nextStart;
cookiesStrings.push(cookiesString.substring(start, lastComma));
start = pos;
} else {
// in param ',' or param separator ';',
// we continue from that comma
pos = lastComma + 1;
}
} else {
pos += 1;
}
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) {
cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
}
}
return cookiesStrings;
}
function toNodeOutgoingHttpHeaders(headers) {
const nodeHeaders = {};
const cookies = [];
if (headers) {
for (const [key, value] of headers.entries()){
if (key.toLowerCase() === 'set-cookie') {
// We may have gotten a comma joined string of cookies, or multiple
// set-cookie headers. We need to merge them into one header array
// to represent all the cookies.
cookies.push(...splitCookiesString(value));
nodeHeaders[key] = cookies.length === 1 ? cookies[0] : cookies;
} else {
nodeHeaders[key] = value;
}
}
}
return nodeHeaders;
}
function validateURL(url) {
try {
return String(new URL(String(url)));
} catch (error) {
throw Object.defineProperty(new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, {
cause: error
}), "__NEXT_ERROR_CODE", {
value: "E61",
enumerable: false,
configurable: true
});
}
}
function normalizeNextQueryParam(key) {
const prefixes = [
_constants.NEXT_QUERY_PARAM_PREFIX,
_constants.NEXT_INTERCEPTION_MARKER_PREFIX
];
for (const prefix of prefixes){
if (key !== prefix && key.startsWith(prefix)) {
return key.substring(prefix.length);
}
}
return null;
}
//# sourceMappingURL=utils.js.map

View File

@@ -1,87 +0,0 @@
/** Monitor when the consumer finishes reading the response body.
that's as close as we can get to `res.on('close')` using web APIs.
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
CloseController: null,
trackBodyConsumed: null,
trackStreamConsumed: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
CloseController: function() {
return CloseController;
},
trackBodyConsumed: function() {
return trackBodyConsumed;
},
trackStreamConsumed: function() {
return trackStreamConsumed;
}
});
function trackBodyConsumed(body, onEnd) {
if (typeof body === 'string') {
const generator = async function* generate() {
const encoder = new TextEncoder();
yield encoder.encode(body);
onEnd();
};
// @ts-expect-error BodyInit typings doesn't seem to include AsyncIterables even though it's supported in practice
return generator();
} else {
return trackStreamConsumed(body, onEnd);
}
}
function trackStreamConsumed(stream, onEnd) {
// NOTE: This function must handle `stream` being aborted or cancelled,
// so it can't just be this:
//
// return stream.pipeThrough(new TransformStream({ flush() { onEnd() } }))
//
// because that doesn't handle cancellations.
// (and cancellation handling via `Transformer.cancel` is only available in node >20)
const dest = new TransformStream();
const runOnEnd = ()=>onEnd();
stream.pipeTo(dest.writable).then(runOnEnd, runOnEnd);
return dest.readable;
}
class CloseController {
onClose(callback) {
if (this.isClosed) {
throw Object.defineProperty(new Error('Cannot subscribe to a closed CloseController'), "__NEXT_ERROR_CODE", {
value: "E365",
enumerable: false,
configurable: true
});
}
this.target.addEventListener('close', callback);
this.listeners++;
}
dispatchClose() {
if (this.isClosed) {
throw Object.defineProperty(new Error('Cannot close a CloseController multiple times'), "__NEXT_ERROR_CODE", {
value: "E229",
enumerable: false,
configurable: true
});
}
if (this.listeners > 0) {
this.target.dispatchEvent(new Event('close'));
}
this.isClosed = true;
}
constructor(){
this.target = new EventTarget();
this.listeners = 0;
this.isClosed = false;
}
}
//# sourceMappingURL=web-on-close.js.map