main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

253
node_modules/next/dist/esm/server/web/adapter.js generated vendored Normal file
View File

@@ -0,0 +1,253 @@
import { PageSignatureError } from "./error";
import { fromNodeOutgoingHttpHeaders } from "./utils";
import { NextFetchEvent } from "./spec-extension/fetch-event";
import { NextRequest } from "./spec-extension/request";
import { NextResponse } from "./spec-extension/response";
import { relativizeURL } from "../../shared/lib/router/utils/relativize-url";
import { waitUntilSymbol } from "./spec-extension/fetch-event";
import { NextURL } from "./next-url";
import { stripInternalSearchParams } from "../internal-utils";
import { normalizeRscPath } from "../../shared/lib/router/utils/app-paths";
import { NEXT_ROUTER_PREFETCH, NEXT_ROUTER_STATE_TREE, RSC } from "../../client/components/app-router-headers";
import { NEXT_QUERY_PARAM_PREFIX } from "../../lib/constants";
import { ensureInstrumentationRegistered } from "./globals";
import { RequestAsyncStorageWrapper } from "../async-storage/request-async-storage-wrapper";
import { requestAsyncStorage } from "../../client/components/request-async-storage.external";
class NextRequestHint extends NextRequest {
constructor(params){
super(params.input, params.init);
this.sourcePage = params.page;
}
get request() {
throw new PageSignatureError({
page: this.sourcePage
});
}
respondWith() {
throw new PageSignatureError({
page: this.sourcePage
});
}
waitUntil() {
throw new PageSignatureError({
page: this.sourcePage
});
}
}
const FLIGHT_PARAMETERS = [
[
RSC
],
[
NEXT_ROUTER_STATE_TREE
],
[
NEXT_ROUTER_PREFETCH
]
];
export async function adapter(params) {
await ensureInstrumentationRegistered();
// TODO-APP: use explicit marker for this
const isEdgeRendering = typeof self.__BUILD_MANIFEST !== "undefined";
const prerenderManifest = typeof self.__PRERENDER_MANIFEST === "string" ? JSON.parse(self.__PRERENDER_MANIFEST) : undefined;
params.request.url = normalizeRscPath(params.request.url, true);
const requestUrl = new 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);
if (key !== NEXT_QUERY_PARAM_PREFIX && key.startsWith(NEXT_QUERY_PARAM_PREFIX)) {
const normalizedKey = key.substring(NEXT_QUERY_PARAM_PREFIX.length);
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.
const buildId = requestUrl.buildId;
requestUrl.buildId = "";
const isDataReq = params.request.headers["x-nextjs-data"];
if (isDataReq && requestUrl.pathname === "/index") {
requestUrl.pathname = "/";
}
const requestHeaders = fromNodeOutgoingHttpHeaders(params.request.headers);
const flightHeaders = new Map();
// Parameters should only be stripped for middleware
if (!isEdgeRendering) {
for (const param of FLIGHT_PARAMETERS){
const key = param.toString().toLowerCase();
const value = requestHeaders.get(key);
if (value) {
flightHeaders.set(key, requestHeaders.get(key));
requestHeaders.delete(key);
}
}
}
const normalizeUrl = process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? new URL(params.request.url) : requestUrl;
const request = new NextRequestHint({
page: params.page,
// Strip internal query parameters off the request.
input: stripInternalSearchParams(normalizeUrl, true).toString(),
init: {
body: params.request.body,
geo: params.request.geo,
headers: requestHeaders,
ip: params.request.ip,
method: params.request.method,
nextConfig: params.request.nextConfig,
signal: params.request.signal
}
});
/**
* 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 (isDataReq) {
Object.defineProperty(request, "__isData", {
enumerable: false,
value: true
});
}
if (!globalThis.__incrementalCache && params.IncrementalCache) {
globalThis.__incrementalCache = new params.IncrementalCache({
appDir: true,
fetchCache: true,
minimalMode: process.env.NODE_ENV !== "development",
fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,
dev: process.env.NODE_ENV === "development",
requestHeaders: params.request.headers,
requestProtocol: "https",
getPrerenderManifest: ()=>{
return {
version: -1,
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: "development-id"
}
};
}
});
}
const event = new NextFetchEvent({
request,
page: params.page
});
let response;
let cookiesFromResponse;
// we only care to make async storage available for middleware
const isMiddleware = params.page === "/middleware" || params.page === "/src/middleware";
if (isMiddleware) {
response = await RequestAsyncStorageWrapper.wrap(requestAsyncStorage, {
req: request,
renderOpts: {
onUpdateCookies: (cookies)=>{
cookiesFromResponse = cookies;
},
// @ts-expect-error: TODO: investigate why previewProps isn't on RenderOpts
previewProps: (prerenderManifest == null ? void 0 : prerenderManifest.preview) || {
previewModeId: "development-id",
previewModeEncryptionKey: "",
previewModeSigningKey: ""
}
}
}, ()=>params.handler(request, event));
} else {
response = await params.handler(request, event);
}
// check if response is a Response object
if (response && !(response instanceof Response)) {
throw new TypeError("Expected an instance of Response to be returned");
}
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) {
const rewriteUrl = new NextURL(rewrite, {
forceLocale: true,
headers: params.request.headers,
nextConfig: params.request.nextConfig
});
if (!process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE) {
if (rewriteUrl.host === request.nextUrl.host) {
rewriteUrl.buildId = buildId || rewriteUrl.buildId;
response.headers.set("x-middleware-rewrite", String(rewriteUrl));
}
}
/**
* 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 relativizedRewrite = relativizeURL(String(rewriteUrl), String(requestUrl));
if (isDataReq && // 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 && relativizedRewrite.match(/http(s)?:\/\//))) {
response.headers.set("x-nextjs-rewrite", relativizedRewrite);
}
}
/**
* 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(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 === request.nextUrl.host) {
redirectURL.buildId = buildId || redirectURL.buildId;
response.headers.set("Location", String(redirectURL));
}
}
/**
* 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 (isDataReq) {
response.headers.delete("Location");
response.headers.set("x-nextjs-redirect", relativizeURL(String(redirectURL), String(requestUrl)));
}
}
const finalResponse = 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: Promise.all(event[waitUntilSymbol])
};
}
//# sourceMappingURL=adapter.js.map

1
node_modules/next/dist/esm/server/web/adapter.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,84 @@
import "./globals";
import { adapter } from "./adapter";
import { IncrementalCache } from "../lib/incremental-cache";
import { RouteMatcher } from "../future/route-matchers/route-matcher";
import { removeTrailingSlash } from "../../shared/lib/router/utils/remove-trailing-slash";
import { removePathPrefix } from "../../shared/lib/router/utils/remove-path-prefix";
/**
* EdgeRouteModuleWrapper is a wrapper around a route module.
*
* Note that this class should only be used in the edge runtime.
*/ export 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){
this.routeModule = routeModule;
// TODO: (wyattjoh) possibly allow the module to define it's own matcher
this.matcher = new 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);
// Return the wrapping function.
return (opts)=>{
return adapter({
...opts,
...options,
IncrementalCache,
// Bind the handler method to the wrapper so it still has context.
handler: wrapper.handler.bind(wrapper)
});
};
}
async handler(request) {
// Get the pathname for the matcher. Pathnames should not have trailing
// slashes for matching.
let pathname = removeTrailingSlash(new URL(request.url).pathname);
// Get the base path and strip it from the pathname if it exists.
const { basePath } = request.nextUrl;
if (basePath) {
// If the path prefix doesn't exist, then this will do nothing.
pathname = removePathPrefix(pathname, basePath);
}
// Get the match for this request.
const match = this.matcher.match(pathname);
if (!match) {
throw new Error(`Invariant: no match found for request. Pathname '${pathname}' should have matched '${this.matcher.definition.pathname}'`);
}
const prerenderManifest = typeof self.__PRERENDER_MANIFEST === "string" ? JSON.parse(self.__PRERENDER_MANIFEST) : undefined;
// Create the context for the handler. This contains the params from the
// match (if any).
const context = {
params: match.params,
prerenderManifest: {
version: 4,
routes: {},
dynamicRoutes: {},
preview: (prerenderManifest == null ? void 0 : prerenderManifest.preview) || {
previewModeEncryptionKey: "",
previewModeId: "development-id",
previewModeSigningKey: ""
},
notFoundRoutes: []
},
staticGenerationContext: {
supportsDynamicHTML: true
}
};
// Get the response from the handler.
return await this.routeModule.handle(request, context);
}
}
//# sourceMappingURL=edge-route-module-wrapper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/edge-route-module-wrapper.ts"],"names":["adapter","IncrementalCache","RouteMatcher","removeTrailingSlash","removePathPrefix","EdgeRouteModuleWrapper","routeModule","matcher","definition","wrap","options","wrapper","opts","handler","bind","request","pathname","URL","url","basePath","nextUrl","match","Error","prerenderManifest","self","__PRERENDER_MANIFEST","JSON","parse","undefined","context","params","version","routes","dynamicRoutes","preview","previewModeEncryptionKey","previewModeId","previewModeSigningKey","notFoundRoutes","staticGenerationContext","supportsDynamicHTML","handle"],"mappings":"AAOA,OAAO,YAAW;AAElB,SAASA,OAAO,QAA6B,YAAW;AACxD,SAASC,gBAAgB,QAAQ,2BAA0B;AAC3D,SAASC,YAAY,QAAQ,yCAAwC;AACrE,SAASC,mBAAmB,QAAQ,sDAAqD;AACzF,SAASC,gBAAgB,QAAQ,mDAAkD;AAInF;;;;CAIC,GACD,OAAO,MAAMC;IAGX;;;;;GAKC,GACD,YAAqCC,YAAkC;2BAAlCA;QACnC,wEAAwE;QACxE,IAAI,CAACC,OAAO,GAAG,IAAIL,aAAaI,YAAYE,UAAU;IACxD;IAEA;;;;;;;;GAQC,GACD,OAAcC,KACZH,WAAgC,EAChCI,UAAuB,CAAC,CAAC,EACzB;QACA,6BAA6B;QAC7B,MAAMC,UAAU,IAAIN,uBAAuBC;QAE3C,gCAAgC;QAChC,OAAO,CAACM;YACN,OAAOZ,QAAQ;gBACb,GAAGY,IAAI;gBACP,GAAGF,OAAO;gBACVT;gBACA,kEAAkE;gBAClEY,SAASF,QAAQE,OAAO,CAACC,IAAI,CAACH;YAChC;QACF;IACF;IAEA,MAAcE,QAAQE,OAAoB,EAAqB;QAC7D,uEAAuE;QACvE,wBAAwB;QACxB,IAAIC,WAAWb,oBAAoB,IAAIc,IAAIF,QAAQG,GAAG,EAAEF,QAAQ;QAEhE,iEAAiE;QACjE,MAAM,EAAEG,QAAQ,EAAE,GAAGJ,QAAQK,OAAO;QACpC,IAAID,UAAU;YACZ,+DAA+D;YAC/DH,WAAWZ,iBAAiBY,UAAUG;QACxC;QAEA,kCAAkC;QAClC,MAAME,QAAQ,IAAI,CAACd,OAAO,CAACc,KAAK,CAACL;QACjC,IAAI,CAACK,OAAO;YACV,MAAM,IAAIC,MACR,CAAC,iDAAiD,EAAEN,SAAS,uBAAuB,EAAE,IAAI,CAACT,OAAO,CAACC,UAAU,CAACQ,QAAQ,CAAC,CAAC,CAAC;QAE7H;QAEA,MAAMO,oBACJ,OAAOC,KAAKC,oBAAoB,KAAK,WACjCC,KAAKC,KAAK,CAACH,KAAKC,oBAAoB,IACpCG;QAEN,wEAAwE;QACxE,kBAAkB;QAClB,MAAMC,UAAuC;YAC3CC,QAAQT,MAAMS,MAAM;YACpBP,mBAAmB;gBACjBQ,SAAS;gBACTC,QAAQ,CAAC;gBACTC,eAAe,CAAC;gBAChBC,SAASX,CAAAA,qCAAAA,kBAAmBW,OAAO,KAAI;oBACrCC,0BAA0B;oBAC1BC,eAAe;oBACfC,uBAAuB;gBACzB;gBACAC,gBAAgB,EAAE;YACpB;YACAC,yBAAyB;gBACvBC,qBAAqB;YACvB;QACF;QAEA,qCAAqC;QACrC,OAAO,MAAM,IAAI,CAAClC,WAAW,CAACmC,MAAM,CAAC1B,SAASc;IAChD;AACF"}

28
node_modules/next/dist/esm/server/web/error.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
export 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
`);
}
}
export 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
`);
}
}
export 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

1
node_modules/next/dist/esm/server/web/error.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/error.ts"],"names":["PageSignatureError","Error","constructor","page","RemovedPageError","RemovedUAError"],"mappings":"AAAA,OAAO,MAAMA,2BAA2BC;IACtCC,YAAY,EAAEC,IAAI,EAAoB,CAAE;QACtC,KAAK,CAAC,CAAC,gBAAgB,EAAEA,KAAK;;;;;;;EAOhC,CAAC;IACD;AACF;AAEA,OAAO,MAAMC,yBAAyBH;IACpCC,aAAc;QACZ,KAAK,CAAC,CAAC;;EAET,CAAC;IACD;AACF;AAEA,OAAO,MAAMG,uBAAuBJ;IAClCC,aAAc;QACZ,KAAK,CAAC,CAAC;;EAET,CAAC;IACD;AACF"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { ImageResponse as default } from "../spec-extension/image-response";
//# sourceMappingURL=image-response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/image-response.ts"],"names":["ImageResponse","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,iBAAiBC,OAAO,QAAQ,mCAAkC"}

View File

@@ -0,0 +1,9 @@
// Alias index file of next/server for edge runtime for tree-shaking purpose
export { default as ImageResponse } from "./image-response";
export { default as NextRequest } from "./next-request";
export { default as NextResponse } from "./next-response";
export { default as userAgent } from "./user-agent";
export { default as userAgentFromString } from "./user-agent-from-string";
export { default as URLPattern } from "./url-pattern";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/index.ts"],"names":["default","ImageResponse","NextRequest","NextResponse","userAgent","userAgentFromString","URLPattern"],"mappings":"AAAA,4EAA4E;AAE5E,SAASA,WAAWC,aAAa,QAAQ,mBAAkB;AAC3D,SAASD,WAAWE,WAAW,QAAQ,iBAAgB;AACvD,SAASF,WAAWG,YAAY,QAAQ,kBAAiB;AACzD,SAASH,WAAWI,SAAS,QAAQ,eAAc;AACnD,SAASJ,WAAWK,mBAAmB,QAAQ,2BAA0B;AACzE,SAASL,WAAWM,UAAU,QAAQ,gBAAe"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { NextRequest as default } from "../spec-extension/request";
//# sourceMappingURL=next-request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/next-request.ts"],"names":["NextRequest","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,eAAeC,OAAO,QAAQ,4BAA2B"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { NextResponse as default } from "../spec-extension/response";
//# sourceMappingURL=next-response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/next-response.ts"],"names":["NextResponse","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,gBAAgBC,OAAO,QAAQ,6BAA4B"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { revalidatePath as default } from "../spec-extension/revalidate-path";
//# sourceMappingURL=revalidate-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/revalidate-path.ts"],"names":["revalidatePath","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,kBAAkBC,OAAO,QAAQ,oCAAmC"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { revalidateTag as default } from "../spec-extension/revalidate-tag";
//# sourceMappingURL=revalidate-tag.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/revalidate-tag.ts"],"names":["revalidateTag","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,iBAAiBC,OAAO,QAAQ,mCAAkC"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { unstable_cache as default } from "../spec-extension/unstable-cache";
//# sourceMappingURL=unstable-cache.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/unstable-cache.ts"],"names":["unstable_cache","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,kBAAkBC,OAAO,QAAQ,mCAAkC"}

View File

@@ -0,0 +1,5 @@
const GlobalURLPattern = // @ts-expect-error: URLPattern is not available in Node.js
typeof URLPattern === "undefined" ? undefined : URLPattern;
export default GlobalURLPattern;
//# sourceMappingURL=url-pattern.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/url-pattern.ts"],"names":["GlobalURLPattern","URLPattern","undefined"],"mappings":"AAAA,MAAMA,mBACJ,2DAA2D;AAC3D,OAAOC,eAAe,cAAcC,YAAYD;AAElD,eAAeD,iBAAgB"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { userAgentFromString as default } from "../spec-extension/user-agent";
//# sourceMappingURL=user-agent-from-string.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/user-agent-from-string.ts"],"names":["userAgentFromString","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,uBAAuBC,OAAO,QAAQ,+BAA8B"}

View File

@@ -0,0 +1,4 @@
// This file is for modularized imports for next/server to get fully-treeshaking.
export { userAgent as default } from "../spec-extension/user-agent";
//# sourceMappingURL=user-agent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/exports/user-agent.ts"],"names":["userAgent","default"],"mappings":"AAAA,iFAAiF;AACjF,SAASA,aAAaC,OAAO,QAAQ,+BAA8B"}

64
node_modules/next/dist/esm/server/web/globals.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
async function registerInstrumentation() {
if ("_ENTRIES" in globalThis && _ENTRIES.middleware_instrumentation && _ENTRIES.middleware_instrumentation.register) {
try {
await _ENTRIES.middleware_instrumentation.register();
} catch (err) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
throw err;
}
}
}
let registerInstrumentationPromise = null;
export function ensureInstrumentationRegistered() {
if (!registerInstrumentationPromise) {
registerInstrumentationPromise = registerInstrumentation();
}
return registerInstrumentationPromise;
}
function getUnsupportedModuleErrorMessage(module) {
// warning: if you change these messages, you must adjust how react-dev-overlay's middleware detects modules not found
return `The edge runtime does not support Node.js '${module}' 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 new Error(getUnsupportedModuleErrorMessage(moduleName));
},
construct () {
throw new Error(getUnsupportedModuleErrorMessage(moduleName));
},
apply (_target, _this, args) {
if (typeof args[0] === "function") {
return args[0](proxy);
}
throw new Error(getUnsupportedModuleErrorMessage(moduleName));
}
});
return new Proxy({}, {
get: ()=>proxy
});
}
function enhanceGlobals() {
// 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
Object.defineProperty(globalThis, "__import_unsupported", {
value: __import_unsupported,
enumerable: false,
configurable: false
});
// Eagerly fire instrumentation hook to make the startup faster.
void ensureInstrumentationRegistered();
}
enhanceGlobals();
//# sourceMappingURL=globals.js.map

1
node_modules/next/dist/esm/server/web/globals.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/globals.ts"],"names":["registerInstrumentation","globalThis","_ENTRIES","middleware_instrumentation","register","err","message","registerInstrumentationPromise","ensureInstrumentationRegistered","getUnsupportedModuleErrorMessage","module","__import_unsupported","moduleName","proxy","Proxy","get","_obj","prop","Error","construct","apply","_target","_this","args","enhanceGlobals","process","global","env","Object","defineProperty","value","enumerable","configurable"],"mappings":"AAEA,eAAeA;IACb,IACE,cAAcC,cACdC,SAASC,0BAA0B,IACnCD,SAASC,0BAA0B,CAACC,QAAQ,EAC5C;QACA,IAAI;YACF,MAAMF,SAASC,0BAA0B,CAACC,QAAQ;QACpD,EAAE,OAAOC,KAAU;YACjBA,IAAIC,OAAO,GAAG,CAAC,sDAAsD,EAAED,IAAIC,OAAO,CAAC,CAAC;YACpF,MAAMD;QACR;IACF;AACF;AAEA,IAAIE,iCAAuD;AAC3D,OAAO,SAASC;IACd,IAAI,CAACD,gCAAgC;QACnCA,iCAAiCP;IACnC;IACA,OAAOO;AACT;AAEA,SAASE,iCAAiCC,MAAc;IACtD,sHAAsH;IACtH,OAAO,CAAC,2CAA2C,EAAEA,OAAO;wEACU,CAAC;AACzE;AAEA,SAASC,qBAAqBC,UAAkB;IAC9C,MAAMC,QAAa,IAAIC,MAAM,YAAa,GAAG;QAC3CC,KAAIC,IAAI,EAAEC,IAAI;YACZ,IAAIA,SAAS,QAAQ;gBACnB,OAAO,CAAC;YACV;YACA,MAAM,IAAIC,MAAMT,iCAAiCG;QACnD;QACAO;YACE,MAAM,IAAID,MAAMT,iCAAiCG;QACnD;QACAQ,OAAMC,OAAO,EAAEC,KAAK,EAAEC,IAAI;YACxB,IAAI,OAAOA,IAAI,CAAC,EAAE,KAAK,YAAY;gBACjC,OAAOA,IAAI,CAAC,EAAE,CAACV;YACjB;YACA,MAAM,IAAIK,MAAMT,iCAAiCG;QACnD;IACF;IACA,OAAO,IAAIE,MAAM,CAAC,GAAG;QAAEC,KAAK,IAAMF;IAAM;AAC1C;AAEA,SAASW;IACP,8DAA8D;IAC9D,IAAIC,YAAYC,OAAOD,OAAO,EAAE;QAC9B,4DAA4D;QAC5DA,QAAQE,GAAG,GAAGD,OAAOD,OAAO,CAACE,GAAG;QAChCD,OAAOD,OAAO,GAAGA;IACnB;IAEA,uEAAuE;IACvE,6DAA6D;IAC7DG,OAAOC,cAAc,CAAC5B,YAAY,wBAAwB;QACxD6B,OAAOnB;QACPoB,YAAY;QACZC,cAAc;IAChB;IAEA,gEAAgE;IAChE,KAAKxB;AACP;AAEAgB"}

23
node_modules/next/dist/esm/server/web/http.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
/**
* List of valid HTTP methods that can be implemented by Next.js's Custom App
* Routes.
*/ export const HTTP_METHODS = [
"GET",
"HEAD",
"OPTIONS",
"POST",
"PUT",
"DELETE",
"PATCH"
];
/**
* Checks to see if the passed string is an HTTP method. Note that this is case
* sensitive.
*
* @param maybeMethod the string that may be an HTTP method
* @returns true if the string is an HTTP method
*/ export function isHTTPMethod(maybeMethod) {
return HTTP_METHODS.includes(maybeMethod);
}
//# sourceMappingURL=http.js.map

1
node_modules/next/dist/esm/server/web/http.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/http.ts"],"names":["HTTP_METHODS","isHTTPMethod","maybeMethod","includes"],"mappings":"AAAA;;;CAGC,GACD,OAAO,MAAMA,eAAe;IAC1B;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAS;AAQV;;;;;;CAMC,GACD,OAAO,SAASC,aAAaC,WAAmB;IAC9C,OAAOF,aAAaG,QAAQ,CAACD;AAC/B"}

181
node_modules/next/dist/esm/server/web/next-url.js generated vendored Normal file
View File

@@ -0,0 +1,181 @@
import { detectDomainLocale } from "../../shared/lib/i18n/detect-domain-locale";
import { formatNextPathnameInfo } from "../../shared/lib/router/utils/format-next-pathname-info";
import { getHostname } from "../../shared/lib/get-hostname";
import { getNextPathnameInfo } from "../../shared/lib/router/utils/get-next-pathname-info";
const REGEX_LOCALHOST_HOSTNAME = /(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|\[::1\]|localhost)/;
function parseURL(url, base) {
return new URL(String(url).replace(REGEX_LOCALHOST_HOSTNAME, "localhost"), base && String(base).replace(REGEX_LOCALHOST_HOSTNAME, "localhost"));
}
const Internal = Symbol("NextURLInternal");
export 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 = 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 = getHostname(this[Internal].url, this[Internal].options.headers);
this[Internal].domainLocale = this[Internal].options.i18nProvider ? this[Internal].options.i18nProvider.detectDomainLocale(hostname) : 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 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 new TypeError(`The NextURL configuration includes no locale "${locale}"`);
}
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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,357 @@
import { AsyncLocalStorage } from "async_hooks";
import { decorateServerError, getServerError } from "next/dist/compiled/@next/react-dev-overlay/dist/middleware";
import { COMPILER_NAMES, EDGE_UNSUPPORTED_NODE_APIS } from "../../../shared/lib/constants";
import { EdgeRuntime } from "next/dist/compiled/edge-runtime";
import { readFileSync, promises as fs } from "fs";
import { validateURL } from "../utils";
import { pick } from "../../../lib/pick";
import { fetchInlineAsset } from "./fetch-inline-assets";
import { runInContext } from "vm";
import BufferImplementation from "node:buffer";
import EventsImplementation from "node:events";
import AssertImplementation from "node:assert";
import UtilImplementation from "node:util";
import AsyncHooksImplementation from "node:async_hooks";
/**
* 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();
/**
* For a given path a context, this function checks if there is any module
* context that contains the path with an older content and, if that's the
* case, removes the context from the cache.
*/ export async function clearModuleContext(path) {
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 module = await WebAssembly.compile(await fs.readFile(binding.filePath));
modules[binding.name] = module;
}));
return modules;
}
function buildEnvironmentVariablesFrom() {
const pairs = Object.keys(process.env).map((key)=>[
key,
process.env[key]
]);
const env = Object.fromEntries(pairs);
env.NEXT_RUNTIME = "edge";
return env;
}
function throwUnsupportedAPIError(name) {
const error = 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`);
decorateServerError(error, COMPILER_NAMES.edgeServer);
throw error;
}
function createProcessPolyfill() {
const processPolyfill = {
env: buildEnvironmentVariablesFrom()
};
const overridenValue = {};
for (const key of Object.keys(process)){
if (key === "env") continue;
Object.defineProperty(processPolyfill, key, {
get () {
if (overridenValue[key] !== undefined) {
return overridenValue[key];
}
if (typeof process[key] === "function") {
return ()=>throwUnsupportedAPIError(`process.${key}`);
}
return undefined;
},
set (value) {
overridenValue[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, COMPILER_NAMES.edgeServer);
}
};
}
function getDecorateUnhandledRejection(runtime) {
const EdgeRuntimeError = runtime.evaluate(`Error`);
return (rejected)=>{
if (rejected.reason instanceof EdgeRuntimeError) {
decorateServerError(rejected.reason, COMPILER_NAMES.edgeServer);
}
};
}
const NativeModuleMap = (()=>{
const mods = {
"node:buffer": pick(BufferImplementation, [
"constants",
"kMaxLength",
"kStringMaxLength",
"Buffer",
"SlowBuffer"
]),
"node:events": pick(EventsImplementation, [
"EventEmitter",
"captureRejectionSymbol",
"defaultMaxListeners",
"errorMonitor",
"listenerCount",
"on",
"once"
]),
"node:async_hooks": pick(AsyncHooksImplementation, [
"AsyncLocalStorage",
"AsyncResource"
]),
"node:assert": pick(AssertImplementation, [
"AssertionError",
"deepEqual",
"deepStrictEqual",
"doesNotMatch",
"doesNotReject",
"doesNotThrow",
"equal",
"fail",
"ifError",
"match",
"notDeepEqual",
"notDeepStrictEqual",
"notEqual",
"notStrictEqual",
"ok",
"rejects",
"strict",
"strictEqual",
"throws"
]),
"node:util": pick(UtilImplementation, [
"_extend",
"callbackify",
"format",
"inherits",
"promisify",
"types"
])
};
return new Map(Object.entries(mods));
})();
/**
* 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 wasm = await loadWasm(options.edgeFunctionEntry.wasm ?? []);
const runtime = new EdgeRuntime({
codeGeneration: process.env.NODE_ENV !== "production" ? {
strings: true,
wasm: true
} : undefined,
extend: (context)=>{
context.process = createProcessPolyfill();
Object.defineProperty(context, "require", {
enumerable: false,
value: (id)=>{
const value = NativeModuleMap.get(id);
if (!value) {
throw TypeError("Native module not found: " + id);
}
return value;
}
});
context.__next_eval__ = function __next_eval__(fn) {
const key = fn.toString();
if (!warnedEvals.has(key)) {
const warning = getServerError(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`), 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(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`), 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(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`), 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 = {})=>{
var _init_headers_get;
const callingError = new Error("[internal]");
const assetResponse = await fetchInlineAsset({
input,
assets: options.edgeFunctionEntry.assets,
distDir: options.distDir,
context
});
if (assetResponse) {
return assetResponse;
}
init.headers = new Headers(init.headers ?? {});
const prevs = ((_init_headers_get = init.headers.get(`x-middleware-subrequest`)) == null ? void 0 : _init_headers_get.split(":")) || [];
const value = prevs.concat(options.moduleName).join(":");
init.headers.set("x-middleware-subrequest", value);
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, {
...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);
validateURL(url);
super(url, init);
this.next = init == null ? void 0 : init.next;
}
};
const __redirect = context.Response.redirect.bind(context.Response);
context.Response.redirect = (...args)=>{
validateURL(args[0]);
return __redirect(...args);
};
for (const name of EDGE_UNSUPPORTED_NODE_APIS){
addStub(context, name);
}
Object.assign(context, wasm);
context.AsyncLocalStorage = AsyncLocalStorage;
return context;
}
});
const decorateUnhandledError = getDecorateUnhandledError(runtime);
runtime.context.addEventListener("error", decorateUnhandledError);
const decorateUnhandledRejection = getDecorateUnhandledRejection(runtime);
runtime.context.addEventListener("unhandledrejection", decorateUnhandledRejection);
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;
}
/**
* For a given module name this function will get a cached module
* context or create it. It will return the module context along
* with a function that allows to run some code from a given
* filepath within the context.
*/ export 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 = readFileSync(filepath, "utf-8");
try {
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

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,27 @@
import { createReadStream, promises as fs } from "fs";
import { requestToBodyStream } from "../../body-streams";
import { resolve } from "path";
/**
* Short-circuits the `fetch` function
* to return a stream for a given asset, if a user used `new URL("file", import.meta.url)`.
* This allows to embed assets in Edge Runtime.
*/ export async function fetchInlineAsset(options) {
var _options_assets;
const inputString = String(options.input);
if (!inputString.startsWith("blob:")) {
return;
}
const hash = inputString.replace("blob:", "");
const asset = (_options_assets = options.assets) == null ? void 0 : _options_assets.find((x)=>x.name === hash);
if (!asset) {
return;
}
const filePath = resolve(options.distDir, asset.filePath);
const fileIsReadable = await fs.access(filePath).then(()=>true, ()=>false);
if (fileIsReadable) {
const readStream = createReadStream(filePath);
return new options.context.Response(requestToBodyStream(options.context, Uint8Array, readStream));
}
}
//# sourceMappingURL=fetch-inline-assets.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/sandbox/fetch-inline-assets.ts"],"names":["createReadStream","promises","fs","requestToBodyStream","resolve","fetchInlineAsset","options","inputString","String","input","startsWith","hash","replace","asset","assets","find","x","name","filePath","distDir","fileIsReadable","access","then","readStream","context","Response","Uint8Array"],"mappings":"AACA,SAASA,gBAAgB,EAAEC,YAAYC,EAAE,QAAQ,KAAI;AACrD,SAASC,mBAAmB,QAAQ,qBAAoB;AACxD,SAASC,OAAO,QAAQ,OAAM;AAE9B;;;;CAIC,GACD,OAAO,eAAeC,iBAAiBC,OAKtC;QAOeA;IANd,MAAMC,cAAcC,OAAOF,QAAQG,KAAK;IACxC,IAAI,CAACF,YAAYG,UAAU,CAAC,UAAU;QACpC;IACF;IAEA,MAAMC,OAAOJ,YAAYK,OAAO,CAAC,SAAS;IAC1C,MAAMC,SAAQP,kBAAAA,QAAQQ,MAAM,qBAAdR,gBAAgBS,IAAI,CAAC,CAACC,IAAMA,EAAEC,IAAI,KAAKN;IACrD,IAAI,CAACE,OAAO;QACV;IACF;IAEA,MAAMK,WAAWd,QAAQE,QAAQa,OAAO,EAAEN,MAAMK,QAAQ;IACxD,MAAME,iBAAiB,MAAMlB,GAAGmB,MAAM,CAACH,UAAUI,IAAI,CACnD,IAAM,MACN,IAAM;IAGR,IAAIF,gBAAgB;QAClB,MAAMG,aAAavB,iBAAiBkB;QACpC,OAAO,IAAIZ,QAAQkB,OAAO,CAACC,QAAQ,CACjCtB,oBAAoBG,QAAQkB,OAAO,EAAEE,YAAYH;IAErD;AACF"}

View File

@@ -0,0 +1,4 @@
export * from "./sandbox";
export { clearModuleContext } from "./context";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/sandbox/index.ts"],"names":["clearModuleContext"],"mappings":"AAAA,cAAc,YAAW;AACzB,SAASA,kBAAkB,QAAQ,YAAW"}

View File

@@ -0,0 +1,86 @@
import { getServerError } from "next/dist/compiled/@next/react-dev-overlay/dist/middleware";
import { getModuleContext } from "./context";
import { requestToBodyStream } from "../../body-streams";
import { NEXT_RSC_UNION_QUERY } from "../../../client/components/app-router-headers";
export 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) {
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");
});
}
export async function getRuntimeContext(params) {
const { runtime, evaluateInContext } = await getModuleContext({
moduleName: params.name,
onWarning: params.onWarning ?? (()=>{}),
useCache: params.useCache !== false,
edgeFunctionEntry: params.edgeFunctionEntry,
distDir: params.distDir
});
if (params.incrementalCache) {
runtime.context.globalThis.__incrementalCache = params.incrementalCache;
}
for (const paramPath of params.paths){
evaluateInContext(paramPath);
}
return runtime;
}
export const run = withTaggedErrors(async function runWithTaggedErrors(params) {
var _params_request_body;
const runtime = await getRuntimeContext(params);
const subreq = params.request.headers[`x-middleware-subrequest`];
const subrequests = typeof subreq === "string" ? subreq.split(":") : [];
if (subrequests.includes(params.name)) {
return {
waitUntil: Promise.resolve(),
response: new runtime.context.Response(null, {
headers: {
"x-middleware-next": "1"
}
})
};
}
const edgeFunction = 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);
urlInstance.searchParams.delete(NEXT_RSC_UNION_QUERY);
params.request.url = urlInstance.toString();
try {
const result = await edgeFunction({
request: {
...params.request,
body: cloned && requestToBodyStream(runtime.context, KUint8Array, cloned)
}
});
for (const headerName of FORBIDDEN_HEADERS){
result.response.headers.delete(headerName);
}
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

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/sandbox/sandbox.ts"],"names":["getServerError","getModuleContext","requestToBodyStream","NEXT_RSC_UNION_QUERY","ErrorSource","Symbol","FORBIDDEN_HEADERS","withTaggedErrors","fn","params","then","result","waitUntil","catch","error","getRuntimeContext","runtime","evaluateInContext","moduleName","name","onWarning","useCache","edgeFunctionEntry","distDir","incrementalCache","context","globalThis","__incrementalCache","paramPath","paths","run","runWithTaggedErrors","subreq","request","headers","subrequests","split","includes","Promise","resolve","response","Response","edgeFunction","_ENTRIES","default","cloned","method","body","cloneBodyStream","undefined","KUint8Array","evaluate","urlInstance","URL","url","searchParams","delete","toString","headerName","finalize"],"mappings":"AACA,SAASA,cAAc,QAAQ,6DAA4D;AAC3F,SAASC,gBAAgB,QAAQ,YAAW;AAE5C,SAASC,mBAAmB,QAAQ,qBAAoB;AAExD,SAASC,oBAAoB,QAAQ,gDAA+C;AAEpF,OAAO,MAAMC,cAAcC,OAAO,gBAAe;AAEjD,MAAMC,oBAAoB;IACxB;IACA;IACA;CACD;AAaD;;;CAGC,GACD,SAASC,iBAAiBC,EAAY;IACpC,OAAO,CAACC,SACND,GAAGC,QACAC,IAAI,CAAC,CAACC;gBAEMA;mBAFM;gBACjB,GAAGA,MAAM;gBACTC,SAAS,EAAED,2BAAAA,oBAAAA,OAAQC,SAAS,qBAAjBD,kBAAmBE,KAAK,CAAC,CAACC;oBACnC,mGAAmG;oBACnG,MAAMd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,QAAQ,CAAC5B,OAAOwB,OAAO,CAACa,MAAM,KAC1DrC,uBAAAA,OAAOwB,OAAO,CAACc,IAAI,qBAAnBtC,qBAAqBuC,eAAe,KACpCC;IAEJ,MAAMC,cAAclC,QAAQmC,QAAQ,CAAC;IACrC,MAAMC,cAAc,IAAIC,IAAI5C,OAAOwB,OAAO,CAACqB,GAAG;IAC9CF,YAAYG,YAAY,CAACC,MAAM,CAACrD;IAEhCM,OAAOwB,OAAO,CAACqB,GAAG,GAAGF,YAAYK,QAAQ;IAEzC,IAAI;QACF,MAAM9C,SAAS,MAAM+B,aAAa;YAChCT,SAAS;gBACP,GAAGxB,OAAOwB,OAAO;gBACjBc,MACEF,UAAU3C,oBAAoBc,QAAQS,OAAO,EAAEyB,aAAaL;YAChE;QACF;QACA,KAAK,MAAMa,cAAcpD,kBAAmB;YAC1CK,OAAO6B,QAAQ,CAACN,OAAO,CAACsB,MAAM,CAACE;QACjC;QACA,OAAO/C;IACT,SAAU;YACFF;QAAN,QAAMA,wBAAAA,OAAOwB,OAAO,CAACc,IAAI,qBAAnBtC,sBAAqBkD,QAAQ;IACrC;AACF,GAAE"}

View File

@@ -0,0 +1,172 @@
import { ReflectAdapter } from "./reflect";
/**
* @internal
*/ export 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();
}
}
export 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 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 ReflectAdapter.get(target, original, receiver);
},
set (target, prop, value, receiver) {
if (typeof prop === "symbol") {
return 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 ReflectAdapter.set(target, original ?? prop, value, receiver);
},
has (target, prop) {
if (typeof prop === "symbol") return 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 ReflectAdapter.has(target, original);
},
deleteProperty (target, prop) {
if (typeof prop === "symbol") return 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 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 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

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/headers.ts"],"names":["ReflectAdapter","ReadonlyHeadersError","Error","constructor","callable","HeadersAdapter","Headers","headers","Proxy","get","target","prop","receiver","lowercased","toLowerCase","original","Object","keys","find","o","set","value","has","deleteProperty","seal","merge","Array","isArray","join","from","append","name","existing","push","delete","forEach","callbackfn","thisArg","entries","call","key","values","Symbol","iterator"],"mappings":"AAEA,SAASA,cAAc,QAAQ,YAAW;AAE1C;;CAEC,GACD,OAAO,MAAMC,6BAA6BC;IACxCC,aAAc;QACZ,KAAK,CACH;IAEJ;IAEA,OAAcC,WAAW;QACvB,MAAM,IAAIH;IACZ;AACF;AAUA,OAAO,MAAMI,uBAAuBC;IAGlCH,YAAYI,OAA4B,CAAE;QACxC,2EAA2E;QAC3E,2EAA2E;QAC3E,KAAK;QAE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AAI,CAAC,IAAI,CAACV,OAAO,EAAG;YAC3C,kEAAkE;YAClE,4BAA4B;YAC5B,MAAMc,QAAQ,IAAI,CAACZ,GAAG,CAAC+B;YAEvB,MAAMnB;QACR;IACF;IAEO,CAACqB,OAAOC,QAAQ,CAAC,GAAuC;QAC7D,OAAO,IAAI,CAACL,OAAO;IACrB;AACF"}

View File

@@ -0,0 +1,86 @@
import { getRequestMeta } from "../../../request-meta";
import { fromNodeOutgoingHttpHeaders } from "../../utils";
import { NextRequest } from "../request";
/**
* Creates an AbortSignal tied to the closing of a ServerResponse (or other
* appropriate Writable).
*
* This cannot be done with the request (IncomingMessage or Readable) because
* the `abort` event will not fire if to data has been fully read (because that
* will "close" the readable stream and nothing fires after that).
*/ export function signalFromNodeResponse(response) {
const { errored, destroyed } = response;
if (errored || destroyed) return AbortSignal.abort(errored);
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.
function onClose() {
controller.abort();
// eslint-disable-next-line @typescript-eslint/no-use-before-define
response.off("finish", onFinish);
}
function onFinish() {
response.off("close", onClose);
}
response.once("close", onClose);
response.once("finish", onFinish);
return controller.signal;
}
export class NextRequestAdapter {
static fromBaseNextRequest(request, signal) {
// TODO: look at refining this check
if ("request" in request && request.request) {
return NextRequestAdapter.fromWebNextRequest(request);
}
return NextRequestAdapter.fromNodeNextRequest(request, signal);
}
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 = getRequestMeta(request, "__NEXT_INIT_URL");
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 NextRequest(url, {
body,
method: request.method,
headers: fromNodeOutgoingHttpHeaders(request.headers),
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: "half",
signal
});
}
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 NextRequest(request.url, {
body,
method: request.method,
headers: fromNodeOutgoingHttpHeaders(request.headers),
// @ts-expect-error - see https://github.com/whatwg/fetch/pull/1457
duplex: "half",
signal: request.request.signal
});
}
}
//# sourceMappingURL=next-request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/next-request.ts"],"names":["getRequestMeta","fromNodeOutgoingHttpHeaders","NextRequest","signalFromNodeResponse","response","errored","destroyed","AbortSignal","abort","controller","AbortController","onClose","off","onFinish","once","signal","NextRequestAdapter","fromBaseNextRequest","request","fromWebNextRequest","fromNodeNextRequest","body","method","url","startsWith","URL","base","headers","duplex"],"mappings":"AAKA,SAASA,cAAc,QAAQ,wBAAuB;AACtD,SAASC,2BAA2B,QAAQ,cAAa;AACzD,SAASC,WAAW,QAAQ,aAAY;AAExC;;;;;;;CAOC,GACD,OAAO,SAASC,uBAAuBC,QAAkB;IACvD,MAAM,EAAEC,OAAO,EAAEC,SAAS,EAAE,GAAGF;IAC/B,IAAIC,WAAWC,WAAW,OAAOC,YAAYC,KAAK,CAACH;IAEnD,MAAMI,aAAa,IAAIC;IACvB,6EAA6E;IAC7E,4EAA4E;IAC5E,mDAAmD;IACnD,SAASC;QACPF,WAAWD,KAAK;QAChB,mEAAmE;QACnEJ,SAASQ,GAAG,CAAC,UAAUC;IACzB;IACA,SAASA;QACPT,SAASQ,GAAG,CAAC,SAASD;IACxB;IACAP,SAASU,IAAI,CAAC,SAASH;IACvBP,SAASU,IAAI,CAAC,UAAUD;IAExB,OAAOJ,WAAWM,MAAM;AAC1B;AAEA,OAAO,MAAM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M;YACtBK,SAAS1B,4BAA4BiB,QAAQS,OAAO;YACpD,mEAAmE;YACnEC,QAAQ;YACRb,QAAQG,QAAQA,OAAO,CAACH,MAAM;QAIhC;IACF;AACF"}

View File

@@ -0,0 +1,20 @@
export 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

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/reflect.ts"],"names":["ReflectAdapter","get","target","prop","receiver","value","Reflect","bind","set","has","deleteProperty"],"mappings":"AAAA,OAAO,MAAMA;IACX,OAAOC,IACLC,MAAS,EACTC,IAAqB,EACrBC,QAAiB,EACZ;QACL,MAAMC,QAAQC,QAAQL,GAAG,CAACC,QAAQC,MAAMC;QACxC,IAAI,OAAOC,UAAU,YAAY;YAC/B,OAAOA,MAAME,IAAI,CAACL;QACpB;QAEA,OAAOG;IACT;IAEA,OAAOG,IACLN,MAAS,EACTC,IAAqB,EACrBE,KAAU,EACVD,QAAa,EACJ;QACT,OAAOE,QAAQE,GAAG,CAACN,QAAQC,MAAME,OAAOD;IAC1C;IAEA,OAAOK,IAAsBP,MAAS,EAAEC,IAAqB,EAAW;QACtE,OAAOG,QAAQG,GAAG,CAACP,QAAQC;IAC7B;IAEA,OAAOO,eACLR,MAAS,EACTC,IAAqB,EACZ;QACT,OAAOG,QAAQI,cAAc,CAACR,QAAQC;IACxC;AACF"}

View File

@@ -0,0 +1,118 @@
import { ResponseCookies } from "../cookies";
import { ReflectAdapter } from "./reflect";
/**
* @internal
*/ export 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#cookiessetname-value-options");
}
static callable() {
throw new ReadonlyRequestCookiesError();
}
}
export 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 ReflectAdapter.get(target, prop, receiver);
}
}
});
}
}
const SYMBOL_MODIFY_COOKIE_VALUES = Symbol.for("next.mutated.cookies");
export function getModifiedCookieValues(cookies) {
const modified = cookies[SYMBOL_MODIFY_COOKIE_VALUES];
if (!modified || !Array.isArray(modified) || modified.length === 0) {
return [];
}
return modified;
}
export 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 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;
}
export class MutableRequestCookiesAdapter {
static wrap(cookies, onUpdateCookies) {
const responseCookes = new ResponseCookies(new Headers());
for (const cookie of cookies.getAll()){
responseCookes.set(cookie);
}
let modifiedValues = [];
const modifiedCookies = new Set();
const updateResponseCookies = ()=>{
var _fetch___nextGetStaticStore;
// TODO-APP: change method of getting staticGenerationAsyncStore
const staticGenerationAsyncStore = fetch.__nextGetStaticStore == null ? void 0 : (_fetch___nextGetStaticStore = fetch.__nextGetStaticStore.call(fetch)) == null ? void 0 : _fetch___nextGetStaticStore.getStore();
if (staticGenerationAsyncStore) {
staticGenerationAsyncStore.pathWasRevalidated = true;
}
const allCookies = responseCookes.getAll();
modifiedValues = allCookies.filter((c)=>modifiedCookies.has(c.name));
if (onUpdateCookies) {
const serializedCookies = [];
for (const cookie of modifiedValues){
const tempCookies = new ResponseCookies(new Headers());
tempCookies.set(cookie);
serializedCookies.push(tempCookies.toString());
}
onUpdateCookies(serializedCookies);
}
};
return new Proxy(responseCookes, {
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);
} finally{
updateResponseCookies();
}
};
case "set":
return function(...args) {
modifiedCookies.add(typeof args[0] === "string" ? args[0] : args[0].name);
try {
return target.set(...args);
} finally{
updateResponseCookies();
}
};
default:
return ReflectAdapter.get(target, prop, receiver);
}
}
});
}
}
//# sourceMappingURL=request-cookies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../../src/server/web/spec-extension/adapters/request-cookies.ts"],"names":["ResponseCookies","ReflectAdapter","ReadonlyRequestCookiesError","Error","constructor","callable","RequestCookiesAdapter","seal","cookies","Proxy","get","target","prop","receiver","SYMBOL_MODIFY_COOKIE_VALUES","Symbol","for","getModifiedCookieValues","modified","Array","isArray","length","appendMutableCookies","headers","mutableCookies","modifiedCookieValues","resCookies","returnedCookies","getAll","cookie","set","MutableRequestCookiesAdapter","wrap","onUpdateCookies","responseCookes","Headers","modifiedValues","modifiedCookies","Set","updateResponseCookies","staticGenerationAsyncStore","fetch","__nextGetStaticStore","getStore","pathWasRevalidated","allCookies","filter","c","has","name","serializedCookies","tempCookies","push","toString","args","add","delete"],"mappings":"AAGA,SAASA,eAAe,QAAQ,aAAY;AAC5C,SAASC,cAAc,QAAQ,YAAW;AAE1C;;CAEC,GACD,OAAO,MAAMC,oCAAoCC;IAC/CC,aAAc;QACZ,KAAK,CACH;IAEJ;IAEA,OAAcC,WAAW;QACvB,MAAM,IAAIH;IACZ;AACF;AAWA,OAAO,MAAMI;IACX,OAAcC,KAAKC,OAAuB,EAA0B;QAClE,OAAO,IAAIC,MAAMD,SAAgB;YAC/BE,KAAIC,MAAM,EAAEC,IA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

View File

@@ -0,0 +1,3 @@
export { RequestCookies, ResponseCookies } from "next/dist/compiled/@edge-runtime/cookies";
//# sourceMappingURL=cookies.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/cookies.ts"],"names":["RequestCookies","ResponseCookies"],"mappings":"AAAA,SACEA,cAAc,EACdC,eAAe,QACV,2CAA0C"}

View File

@@ -0,0 +1,48 @@
import { PageSignatureError } from "../error";
const responseSymbol = Symbol("response");
const passThroughSymbol = Symbol("passThrough");
export const waitUntilSymbol = Symbol("waitUntil");
class FetchEvent {
// eslint-disable-next-line @typescript-eslint/no-useless-constructor
constructor(_request){
this[waitUntilSymbol] = [];
this[passThroughSymbol] = false;
}
respondWith(response) {
if (!this[responseSymbol]) {
this[responseSymbol] = Promise.resolve(response);
}
}
passThroughOnException() {
this[passThroughSymbol] = true;
}
waitUntil(promise) {
this[waitUntilSymbol].push(promise);
}
}
export class NextFetchEvent extends FetchEvent {
constructor(params){
super(params.request);
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 new PageSignatureError({
page: this.sourcePage
});
}
/**
* @deprecated Using `respondWith` is no longer needed.
*
* Read more: https://nextjs.org/docs/messages/middleware-new-signature
*/ respondWith() {
throw new PageSignatureError({
page: this.sourcePage
});
}
}
//# sourceMappingURL=fetch-event.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/fetch-event.ts"],"names":["PageSignatureError","responseSymbol","Symbol","passThroughSymbol","waitUntilSymbol","FetchEvent","constructor","_request","respondWith","response","Promise","resolve","passThroughOnException","waitUntil","promise","push","NextFetchEvent","params","request","sourcePage","page"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,WAAU;AAG7C,MAAMC,iBAAiBC,OAAO;AAC9B,MAAMC,oBAAoBD,OAAO;AACjC,OAAO,MAAME,kBAAkBF,OAAO,aAAY;AAElD,MAAMG;IAKJ,qEAAqE;IACrEC,YAAYC,QAAiB,CAAE;YALtB,CAACH,gBAAgB,GAAmB,EAAE;YAE/C,CAACD,kBAAkB,GAAG;IAGU;IAEhCK,YAAYC,QAAsC,EAAQ;QACxD,IAAI,CAAC,IAAI,CAACR,eAAe,EAAE;YACzB,IAAI,CAACA,eAAe,GAAGS,QAAQC,OAAO,CAACF;QACzC;IACF;IAEAG,yBAA+B;QAC7B,IAAI,CAACT,kBAAkB,GAAG;IAC5B;IAEAU,UAAUC,OAAqB,EAAQ;QACrC,IAAI,CAACV,gBAAgB,CAACW,IAAI,CAACD;IAC7B;AACF;AAEA,OAAO,MAAME,uBAAuBX;IAGlCC,YAAYW,MAA8C,CAAE;QAC1D,KAAK,CAACA,OAAOC,OAAO;QACpB,IAAI,CAACC,UAAU,GAAGF,OAAOG,IAAI;IAC/B;IAEA;;;;GAIC,GACD,IAAIF,UAAU;QACZ,MAAM,IAAIlB,mBAAmB;YAC3BoB,MAAM,IAAI,CAACD,UAAU;QACvB;IACF;IAEA;;;;GAIC,GACDX,cAAc;QACZ,MAAM,IAAIR,mBAAmB;YAC3BoB,MAAM,IAAI,CAACD,UAAU;QACvB;IACF;AACF"}

View File

@@ -0,0 +1,36 @@
export class ImageResponse extends Response {
static #_ = this.displayName = "NextImageResponse";
constructor(...args){
const readable = new ReadableStream({
async start (controller) {
const OGImageResponse = // So far we have to manually determine which build to use,
// as the auto resolving is not working
(await import(process.env.NEXT_RUNTIME === "edge" ? "next/dist/compiled/@vercel/og/index.edge.js" : "next/dist/compiled/@vercel/og/index.node.js")).ImageResponse;
const imageResponse = new OGImageResponse(...args);
if (!imageResponse.body) {
return controller.close();
}
const reader = imageResponse.body.getReader();
while(true){
const { done, value } = await reader.read();
if (done) {
return controller.close();
}
controller.enqueue(value);
}
}
});
const options = args[1] || {};
super(readable, {
headers: {
"content-type": "image/png",
"cache-control": process.env.NODE_ENV === "development" ? "no-cache, no-store" : "public, immutable, no-transform, max-age=31536000",
...options.headers
},
status: options.status,
statusText: options.statusText
});
}
}
//# sourceMappingURL=image-response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/image-response.ts"],"names":["ImageResponse","Response","displayName","constructor","args","readable","ReadableStream","start","controller","OGImageResponse","process","env","NEXT_RUNTIME","imageResponse","body","close","reader","getReader","done","value","read","enqueue","options","headers","NODE_ENV","status","statusText"],"mappings":"AAAA,OAAO,MAAMA,sBAAsBC;qBACnBC,cAAc;IAC5BC,YACE,GAAGC,IAEF,CACD;QACA,MAAMC,WAAW,IAAIC,eAAe;YAClC,MAAMC,OAAMC,UAAU;gBACpB,MAAMC,kBAGJ,AAFA,2DAA2D;gBAC3D,uCAAuC;gBAErC,CAAA,MAAM,MAAM,CACVC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzB,gDACA,8CACN,EACAZ,aAAa;gBACjB,MAAMa,gBAAgB,IAAIJ,mBAAmBL;gBAE7C,IAAI,CAACS,cAAcC,IAAI,EAAE;oBACvB,OAAON,WAAWO,KAAK;gBACzB;gBAEA,MAAMC,SAASH,cAAcC,IAAI,CAAEG,SAAS;gBAC5C,MAAO,KAAM;oBACX,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAE,GAAG,MAAMH,OAAOI,IAAI;oBACzC,IAAIF,MAAM;wBACR,OAAOV,WAAWO,KAAK;oBACzB;oBACAP,WAAWa,OAAO,CAACF;gBACrB;YACF;QACF;QAEA,MAAMG,UAAUlB,IAAI,CAAC,EAAE,IAAI,CAAC;QAE5B,KAAK,CAACC,UAAU;YACdkB,SAAS;gBACP,gBAAgB;gBAChB,iBACEb,QAAQC,GAAG,CAACa,QAAQ,KAAK,gBACrB,uBACA;gBACN,GAAGF,QAAQC,OAAO;YACpB;YACAE,QAAQH,QAAQG,MAAM;YACtBC,YAAYJ,QAAQI,UAAU;QAChC;IACF;AACF"}

View File

@@ -0,0 +1,78 @@
import { NextURL } from "../next-url";
import { toNodeOutgoingHttpHeaders, validateURL } from "../utils";
import { RemovedUAError, RemovedPageError } from "../error";
import { RequestCookies } from "./cookies";
export const INTERNALS = Symbol("internal request");
export class NextRequest extends Request {
constructor(input, init = {}){
const url = typeof input !== "string" && "url" in input ? input.url : String(input);
validateURL(url);
if (input instanceof Request) super(input, init);
else super(url, init);
const nextUrl = new NextURL(url, {
headers: toNodeOutgoingHttpHeaders(this.headers),
nextConfig: init.nextConfig
});
this[INTERNALS] = {
cookies: new RequestCookies(this.headers),
geo: init.geo || {},
ip: init.ip,
nextUrl,
url: process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE ? url : nextUrl.toString()
};
}
[Symbol.for("edge-runtime.inspect.custom")]() {
return {
cookies: this.cookies,
geo: this.geo,
ip: this.ip,
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 geo() {
return this[INTERNALS].geo;
}
get ip() {
return this[INTERNALS].ip;
}
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 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 RemovedUAError();
}
get url() {
return this[INTERNALS].url;
}
}
//# sourceMappingURL=request.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/request.ts"],"names":["NextURL","toNodeOutgoingHttpHeaders","validateURL","RemovedUAError","RemovedPageError","RequestCookies","INTERNALS","Symbol","NextRequest","Request","constructor","input","init","url","String","nextUrl","headers","nextConfig","cookies","geo","ip","process","env","__NEXT_NO_MIDDLEWARE_URL_NORMALIZE","toString","for","bodyUsed","cache","credentials","destination","Object","fromEntries","integrity","keepalive","method","mode","redirect","referrer","referrerPolicy","signal","page","ua"],"mappings":"AAEA,SAASA,OAAO,QAAQ,cAAa;AACrC,SAASC,yBAAyB,EAAEC,WAAW,QAAQ,WAAU;AACjE,SAASC,cAAc,EAAEC,gBAAgB,QAAQ,WAAU;AAC3D,SAASC,cAAc,QAAQ,YAAW;AAE1C,OAAO,MAAMC,YAAYC,OAAO,oBAAmB;AAEnD,OAAO,MAAMC,oBAAoBC;IAS/BC,YAAYC,KAAwB,EAAEC,OAAoB,CAAC,CAAC,CAAE;QAC5D,MAAMC,MACJ,OAAOF,UAAU,YAAY,SAASA,QAAQA,MAAME,GAAG,GAAGC,OAAOH;QACnET,YAAYW;QACZ,IAAIF,iBAAiBF,SAAS,KAAK,CAACE,OAAOC;aACtC,KAAK,CAACC,KAAKD;QAChB,MAAMG,UAAU,IAAIf,QAAQa,KAAK;YAC/BG,SAASf,0BAA0B,IAAI,CAACe,OAAO;YAC/CC,YAAYL,KAAKK,UAAU;QAC7B;QACA,IAAI,CAACX,UAAU,GAAG;YAChBY,SAAS,IAAIb,eAAe,IAAI,CAACW,OAAO;YACxCG,KAAKP,KAAKO,GAAG,IAAI,CAAC;YAClBC,IAAIR,KAAKQ,EAAE;YACXL;YACAF,KAAKQ,QAAQC,GAAG,CAACC,kCAAkC,GAC/CV,MACAE,QAAQS,QAAQ;QACtB;IACF;IAEA,CAACjB,OAAOkB,GAAG,CAAC,+BAA+B,GAAG;QAC5C,OAAO;YACLP,SAAS,IAAI,CAACA,OAAO;YACrBC,KAAK,IAAI,CAACA,GAAG;YACbC,IAAI,IAAI,CAACA,EAAE;YACXL,SAAS,IAAI,CAACA,OAAO;YACrBF,KAAK,IAAI,CAACA,GAAG;YACb,kCAAkC;YAClCa,UAAU,IAAI,CAACA,QAAQ;YACvBC,OAAO,IAAI,CAACA,KAAK;YACjBC,aAAa,IAAI,CAACA,WAAW;YAC7BC,aAAa,IAAI,CAACA,WAAW;YAC7Bb,SAASc,OAAOC,WAAW,CAAC,IAAI,CAACf,OAAO;YACxCgB,WAAW,IAAI,CAACA,SAAS;YACzBC,WAAW,IAAI,CAACA,SAAS;YACzBC,QAAQ,IAAI,CAACA,MAAM;YACnBC,MAAM,IAAI,CAACA,IAAI;YACfC,UAAU,IAAI,CAACA,QAAQ;YACvBC,UAAU,IAAI,CAACA,QAAQ;YACvBC,gBAAgB,IAAI,CAACA,cAAc;YACnCC,QAAQ,IAAI,CAACA,MAAM;QACrB;IACF;IAEA,IAAWrB,UAAU;QACnB,OAAO,IAAI,CAACZ,UAAU,CAACY,OAAO;IAChC;IAEA,IAAWC,MAAM;QACf,OAAO,IAAI,CAACb,UAAU,CAACa,GAAG;IAC5B;IAEA,IAAWC,KAAK;QACd,OAAO,IAAI,CAACd,UAAU,CAACc,EAAE;IAC3B;IAEA,IAAWL,UAAU;QACnB,OAAO,IAAI,CAACT,UAAU,CAACS,OAAO;IAChC;IAEA;;;;GAIC,GACD,IAAWyB,OAAO;QAChB,MAAM,IAAIpC;IACZ;IAEA;;;;GAIC,GACD,IAAWqC,KAAK;QACd,MAAM,IAAItC;IACZ;IAEA,IAAWU,MAAM;QACf,OAAO,IAAI,CAACP,UAAU,CAACO,GAAG;IAC5B;AACF"}

View File

@@ -0,0 +1,93 @@
import { NextURL } from "../next-url";
import { toNodeOutgoingHttpHeaders, validateURL } from "../utils";
import { ResponseCookies } from "./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 new Error("request.headers must be an instance of Headers");
}
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(","));
}
}
export class NextResponse extends Response {
constructor(body, init = {}){
super(body, init);
this[INTERNALS] = {
cookies: new ResponseCookies(this.headers),
url: init.url ? new NextURL(init.url, {
headers: toNodeOutgoingHttpHeaders(this.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 new RangeError('Failed to execute "redirect" on "response": Invalid status code');
}
const initObj = typeof init === "object" ? init : {};
const headers = new Headers(initObj == null ? void 0 : initObj.headers);
headers.set("Location", 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", 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

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/response.ts"],"names":["NextURL","toNodeOutgoingHttpHeaders","validateURL","ResponseCookies","INTERNALS","Symbol","REDIRECTS","Set","handleMiddlewareField","init","headers","request","Headers","Error","keys","key","value","set","push","join","NextResponse","Response","constructor","body","cookies","url","nextConfig","undefined","for","bodyUsed","Object","fromEntries","ok","redirected","status","statusText","type","json","response","redirect","has","RangeError","initObj","rewrite","destination","next"],"mappings":"AACA,SAASA,OAAO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AAC,qBAAqB;QAEjCT,sBAAsBC,MAAMC;QAC5B,OAAO,IAAIU,aAAa,MAAM;YAAE,GAAGX,IAAI;YAAEC;QAAQ;IACnD;AACF"}

View File

@@ -0,0 +1,18 @@
import { revalidateTag } from "./revalidate-tag";
import { isDynamicRoute } from "../../../shared/lib/router/utils";
import { NEXT_CACHE_IMPLICIT_TAG_ID, NEXT_CACHE_SOFT_TAG_MAX_LENGTH } from "../../../lib/constants";
export function revalidatePath(originalPath, type) {
if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {
console.warn(`Warning: revalidatePath received "${originalPath}" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);
return;
}
let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${originalPath}`;
if (type) {
normalizedPath += `${normalizedPath.endsWith("/") ? "" : "/"}${type}`;
} else if (isDynamicRoute(originalPath)) {
console.warn(`Warning: a dynamic page path "${originalPath}" was passed to "revalidatePath" without the "page" argument. This has no affect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`);
}
return revalidateTag(normalizedPath);
}
//# sourceMappingURL=revalidate-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate-path.ts"],"names":["revalidateTag","isDynamicRoute","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","revalidatePath","originalPath","type","length","console","warn","normalizedPath","endsWith"],"mappings":"AAAA,SAASA,aAAa,QAAQ,mBAAkB;AAChD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,8BAA8B,QACzB,yBAAwB;AAE/B,OAAO,SAASC,eAAeC,YAAoB,EAAEC,IAAwB;IAC3E,IAAID,aAAaE,MAAM,GAAGJ,gCAAgC;QACxDK,QAAQC,IAAI,CACV,CAAC,kCAAkC,EAAEJ,aAAa,+BAA+B,EAAEF,+BAA+B,uFAAuF,CAAC;QAE5M;IACF;IAEA,IAAIO,iBAAiB,CAAC,EAAER,2BAA2B,EAAEG,aAAa,CAAC;IAEnE,IAAIC,MAAM;QACRI,kBAAkB,CAAC,EAAEA,eAAeC,QAAQ,CAAC,OAAO,KAAK,IAAI,EAAEL,KAAK,CAAC;IACvE,OAAO,IAAIL,eAAeI,eAAe;QACvCG,QAAQC,IAAI,CACV,CAAC,8BAA8B,EAAEJ,aAAa,kLAAkL,CAAC;IAErO;IACA,OAAOL,cAAcU;AACvB"}

View File

@@ -0,0 +1,23 @@
export function revalidateTag(tag) {
const staticGenerationAsyncStorage = fetch.__nextGetStaticStore == null ? void 0 : fetch.__nextGetStaticStore.call(fetch);
const store = staticGenerationAsyncStorage == null ? void 0 : staticGenerationAsyncStorage.getStore();
if (!store || !store.incrementalCache) {
throw new Error(`Invariant: static generation store missing in revalidateTag ${tag}`);
}
if (!store.revalidatedTags) {
store.revalidatedTags = [];
}
if (!store.revalidatedTags.includes(tag)) {
store.revalidatedTags.push(tag);
}
if (!store.pendingRevalidates) {
store.pendingRevalidates = [];
}
store.pendingRevalidates.push(store.incrementalCache.revalidateTag == null ? void 0 : store.incrementalCache.revalidateTag.call(store.incrementalCache, tag).catch((err)=>{
console.error(`revalidateTag failed for ${tag}`, err);
}));
// TODO: only revalidate if the path matches
store.pathWasRevalidated = true;
}
//# sourceMappingURL=revalidate-tag.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/revalidate-tag.ts"],"names":["revalidateTag","tag","staticGenerationAsyncStorage","fetch","__nextGetStaticStore","store","getStore","incrementalCache","Error","revalidatedTags","includes","push","pendingRevalidates","catch","err","console","error","pathWasRevalidated"],"mappings":"AAKA,OAAO,SAASA,cAAcC,GAAW;IACvC,MAAMC,+BAA+B,AACnCC,MACAC,oBAAoB,oBAFe,AACnCD,MACAC,oBAAoB,MADpBD;IAGF,MAAME,QACJH,gDAAAA,6BAA8BI,QAAQ;IAExC,IAAI,CAACD,SAAS,CAACA,MAAME,gBAAgB,EAAE;QACrC,MAAM,IAAIC,MACR,CAAC,4DAA4D,EAAEP,IAAI,CAAC;IAExE;IACA,IAAI,CAACI,MAAMI,eAAe,EAAE;QAC1BJ,MAAMI,eAAe,GAAG,EAAE;IAC5B;IACA,IAAI,CAACJ,MAAMI,eAAe,CAACC,QAAQ,CAACT,MAAM;QACxCI,MAAMI,eAAe,CAACE,IAAI,CAACV;IAC7B;IAEA,IAAI,CAACI,MAAMO,kBAAkB,EAAE;QAC7BP,MAAMO,kBAAkB,GAAG,EAAE;IAC/B;IACAP,MAAMO,kBAAkB,CAACD,IAAI,CAC3BN,MAAME,gBAAgB,CAACP,aAAa,oBAApCK,MAAME,gBAAgB,CAACP,aAAa,MAApCK,MAAME,gBAAgB,EAAiBN,KAAKY,KAAK,CAAC,CAACC;QACjDC,QAAQC,KAAK,CAAC,CAAC,yBAAyB,EAAEf,IAAI,CAAC,EAAEa;IACnD;IAGF,4CAA4C;IAC5CT,MAAMY,kBAAkB,GAAG;AAC7B"}

View File

@@ -0,0 +1,96 @@
import { staticGenerationAsyncStorage as _staticGenerationAsyncStorage } from "../../../client/components/static-generation-async-storage.external";
import { CACHE_ONE_YEAR } from "../../../lib/constants";
import { addImplicitTags, validateTags } from "../../lib/patch-fetch";
export function unstable_cache(cb, keyParts, options = {}) {
const staticGenerationAsyncStorage = (fetch.__nextGetStaticStore == null ? void 0 : fetch.__nextGetStaticStore.call(fetch)) || _staticGenerationAsyncStorage;
if (options.revalidate === 0) {
throw new Error(`Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${cb.toString()}`);
}
const cachedCb = async (...args)=>{
const store = staticGenerationAsyncStorage == null ? void 0 : staticGenerationAsyncStorage.getStore();
const incrementalCache = (store == null ? void 0 : store.incrementalCache) || globalThis.__incrementalCache;
if (!incrementalCache) {
throw new Error(`Invariant: incrementalCache missing in unstable_cache ${cb.toString()}`);
}
const joinedKey = `${cb.toString()}-${Array.isArray(keyParts) && keyParts.join(",")}-${JSON.stringify(args)}`;
// We override the default fetch cache handling inside of the
// cache callback so that we only cache the specific values returned
// from the callback instead of also caching any fetches done inside
// of the callback as well
return staticGenerationAsyncStorage.run({
...store,
fetchCache: "only-no-store",
urlPathname: (store == null ? void 0 : store.urlPathname) || "/",
isStaticGeneration: !!(store == null ? void 0 : store.isStaticGeneration)
}, async ()=>{
const tags = validateTags(options.tags || [], `unstable_cache ${cb.toString()}`);
if (Array.isArray(tags) && store) {
if (!store.tags) {
store.tags = [];
}
for (const tag of tags){
if (!store.tags.includes(tag)) {
store.tags.push(tag);
}
}
}
const implicitTags = addImplicitTags(store);
const cacheKey = await (incrementalCache == null ? void 0 : incrementalCache.fetchCacheKey(joinedKey));
const cacheEntry = cacheKey && !((store == null ? void 0 : store.isOnDemandRevalidate) || incrementalCache.isOnDemandRevalidate) && await (incrementalCache == null ? void 0 : incrementalCache.get(cacheKey, {
fetchCache: true,
revalidate: options.revalidate,
tags,
softTags: implicitTags
}));
const invokeCallback = async ()=>{
const result = await cb(...args);
if (cacheKey && incrementalCache) {
await incrementalCache.set(cacheKey, {
kind: "FETCH",
data: {
headers: {},
// TODO: handle non-JSON values?
body: JSON.stringify(result),
status: 200,
url: ""
},
revalidate: typeof options.revalidate !== "number" ? CACHE_ONE_YEAR : options.revalidate
}, {
revalidate: options.revalidate,
fetchCache: true,
tags
});
}
return result;
};
if (!cacheEntry || !cacheEntry.value) {
return invokeCallback();
}
if (cacheEntry.value.kind !== "FETCH") {
console.error(`Invariant invalid cacheEntry returned for ${joinedKey}`);
return invokeCallback();
}
let cachedValue;
const isStale = cacheEntry.isStale;
if (cacheEntry) {
const resData = cacheEntry.value.data;
cachedValue = JSON.parse(resData.body);
}
if (isStale) {
if (!store) {
return invokeCallback();
} else {
if (!store.pendingRevalidates) {
store.pendingRevalidates = [];
}
store.pendingRevalidates.push(invokeCallback().catch((err)=>console.error(`revalidating cache with key: ${joinedKey}`, err)));
}
}
return cachedValue;
});
};
// TODO: once AsyncLocalStorage.run() returns the correct types this override will no longer be necessary
return cachedCb;
}
//# sourceMappingURL=unstable-cache.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/unstable-cache.ts"],"names":["staticGenerationAsyncStorage","_staticGenerationAsyncStorage","CACHE_ONE_YEAR","addImplicitTags","validateTags","unstable_cache","cb","keyParts","options","fetch","__nextGetStaticStore","revalidate","Error","toString","cachedCb","args","store","getStore","incrementalCache","globalThis","__incrementalCache","joinedKey","Array","isArray","join","JSON","stringify","run","fetchCache","urlPathname","isStaticGeneration","tags","tag","includes","push","implicitTags","cacheKey","fetchCacheKey","cacheEntry","isOnDemandRevalidate","get","softTags","invokeCallback","result","set","kind","data","headers","body","status","url","value","console","error","cachedValue","isStale","resData","parse","pendingRevalidates","catch","err"],"mappings":"AAAA,SAEEA,gCAAgCC,6BAA6B,QAExD,sEAAqE;AAC5E,SAASC,cAAc,QAAQ,yBAAwB;AACvD,SAASC,eAAe,EAAEC,YAAY,QAAQ,wBAAuB;AAIrE,OAAO,SAASC,eACdC,EAAK,EACLC,QAAmB,EACnBC,UAGI,CAAC,CAAC;IAEN,MAAMR,+BACJ,CAAA,AAACS,MAAcC,oBAAoB,oBAAnC,AAACD,MAAcC,oBAAoB,MAAlCD,WAA0CR;IAE7C,IAAIO,QAAQG,UAAU,KAAK,GAAG;QAC5B,MAAM,IAAIC,MACR,CAAC,wFAAwF,EAAEN,GAAGO,QAAQ,GAAG,CAAC;IAE9G;IAEA,MAAMC,WAAW,OAAO,GAAGC;QACzB,MAAMC,QACJhB,gDAAAA,6BAA8BiB,QAAQ;QAExC,MAAMC,mBAGJF,CAAAA,yBAAAA,MAAOE,gBAAgB,KAAI,AAACC,WAAmBC,kBAAkB;QAEnE,IAAI,CAACF,kBAAkB;YACrB,MAAM,IAAIN,MACR,CAAC,sDAAsD,EAAEN,GAAGO,QAAQ,GAAG,CAAC;QAE5E;QAE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R,UACA;wBACES,MAAM;wBACNC,MAAM;4BACJC,SAAS,CAAC;4BACV,gCAAgC;4BAChCC,MAAMvB,KAAKC,SAAS,CAACiB;4BACrBM,QAAQ;4BACRC,KAAK;wBACP;wBACAvC,YACE,OAAOH,QAAQG,UAAU,KAAK,WAC1BT,iBACAM,QAAQG,UAAU;oBAC1B,GACA;wBACEA,YAAYH,QAAQG,UAAU;wBAC9BiB,YAAY;wBACZG;oBACF;gBAEJ;gBACA,OAAOY;YACT;YAEA,IAAI,CAACL,cAAc,CAACA,WAAWa,KAAK,EAAE;gBACpC,OAAOT;YACT;YAEA,IAAIJ,WAAWa,KAAK,CAACN,IAAI,KAAK,SAAS;gBACrCO,QAAQC,KAAK,CACX,CAAC,0CAA0C,EAAEhC,UAAU,CAAC;gBAE1D,OAAOqB;YACT;YACA,IAAIY;YACJ,MAAMC,UAAUjB,WAAWiB,OAAO;YAElC,IAAIjB,YAAY;gBACd,MAAMkB,UAAUlB,WAAWa,KAAK,CAACL,IAAI;gBACrCQ,cAAc7B,KAAKgC,KAAK,CAACD,QAAQR,IAAI;YACvC;YAEA,IAAIO,SAAS;gBACX,IAAI,CAACvC,OAAO;oBACV,OAAO0B;gBACT,OAAO;oBACL,IAAI,CAAC1B,MAAM0C,kBAAkB,EAAE;wBAC7B1C,MAAM0C,kBAAkB,GAAG,EAAE;oBAC/B;oBACA1C,MAAM0C,kBAAkB,CAACxB,IAAI,CAC3BQ,iBAAiBiB,KAAK,CAAC,CAACC,MACtBR,QAAQC,KAAK,CAAC,CAAC,6BAA6B,EAAEhC,UAAU,CAAC,EAAEuC;gBAGjE;YACF;YACA,OAAON;QACT;IAEJ;IACA,yGAAyG;IACzG,OAAOxC;AACT"}

View File

@@ -0,0 +1,15 @@
import parseua from "next/dist/compiled/ua-parser-js";
export 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/i.test(input);
}
export function userAgentFromString(input) {
return {
...parseua(input),
isBot: input === undefined ? false : isBot(input)
};
}
export function userAgent({ headers }) {
return userAgentFromString(headers.get("user-agent") || undefined);
}
//# sourceMappingURL=user-agent.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/web/spec-extension/user-agent.ts"],"names":["parseua","isBot","input","test","userAgentFromString","undefined","userAgent","headers","get"],"mappings":"AAAA,OAAOA,aAAa,kCAAiC;AA2BrD,OAAO,SAASC,MAAMC,KAAa;IACjC,OAAO,0WAA0WC,IAAI,CACnXD;AAEJ;AAEA,OAAO,SAASE,oBAAoBF,KAAyB;IAC3D,OAAO;QACL,GAAGF,QAAQE,MAAM;QACjBD,OAAOC,UAAUG,YAAY,QAAQJ,MAAMC;IAC7C;AACF;AAEA,OAAO,SAASI,UAAU,EAAEC,OAAO,EAAwB;IACzD,OAAOH,oBAAoBG,QAAQC,GAAG,CAAC,iBAAiBH;AAC1D"}

3
node_modules/next/dist/esm/server/web/types.js generated vendored Normal file
View File

@@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=types.js.map

1
node_modules/next/dist/esm/server/web/types.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/types.ts"],"names":[],"mappings":"AAAA,WAmDyD"}

125
node_modules/next/dist/esm/server/web/utils.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
/**
* Converts a Node.js IncomingHttpHeaders object to a Headers object. Any
* headers with multiple values will be joined with a comma and space. Any
* headers that have an undefined value will be ignored and others will be
* coerced to strings.
*
* @param nodeHeaders the headers object to convert
* @returns the converted headers object
*/ export 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;
}
/*
Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
that are within a single set-cookie field-value, such as in the Expires portion.
This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
React Native's fetch does this for *every* header, including set-cookie.
Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
*/ export 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;
}
/**
* Converts a Headers object to a Node.js OutgoingHttpHeaders object. This is
* required to support the set-cookie header, which may have multiple values.
*
* @param headers the headers object to convert
* @returns the converted headers object
*/ export 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;
}
/**
* Validate the correctness of a user-provided URL.
*/ export function validateURL(url) {
try {
return String(new URL(String(url)));
} catch (error) {
throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, {
cause: error
});
}
}
//# sourceMappingURL=utils.js.map

1
node_modules/next/dist/esm/server/web/utils.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/web/utils.ts"],"names":["fromNodeOutgoingHttpHeaders","nodeHeaders","headers","Headers","key","value","Object","entries","values","Array","isArray","v","toString","append","splitCookiesString","cookiesString","cookiesStrings","pos","start","ch","lastComma","nextStart","cookiesSeparatorFound","skipWhitespace","length","test","charAt","notSpecialChar","push","substring","toNodeOutgoingHttpHeaders","cookies","toLowerCase","validateURL","url","String","URL","error","Error","cause"],"mappings":"AAEA;;;;;;;;CAQC,GACD,OAAO,SAASA,4BACdC,WAAgC;IAEhC,MAAMC,UAAU,IAAIC;IACpB,KAAK,IAAI,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,aAAc;QACpD,MAAMO,SAASC,MAAMC,OAAO,CAACL,SAASA,QAAQ;YAACA;SAAM;QACrD,KAAK,IAAIM,KAAKH,OAAQ;YACpB,IAAI,OAAOG,MAAM,aAAa;YAC9B,IAAI,OAAOA,MAAM,UAAU;gBACzBA,IAAIA,EAAEC,QAAQ;YAChB;YAEAV,QAAQW,MAAM,C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