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

110
node_modules/next/dist/esm/server/accept-header.js generated vendored Normal file
View File

@@ -0,0 +1,110 @@
function parse(raw, preferences, options) {
const lowers = new Map();
const header = raw.replace(/[ \t]/g, "");
if (preferences) {
let pos = 0;
for (const preference of preferences){
const lower = preference.toLowerCase();
lowers.set(lower, {
orig: preference,
pos: pos++
});
if (options.prefixMatch) {
const parts = lower.split("-");
while(parts.pop(), parts.length > 0){
const joined = parts.join("-");
if (!lowers.has(joined)) {
lowers.set(joined, {
orig: preference,
pos: pos++
});
}
}
}
}
}
const parts = header.split(",");
const selections = [];
const map = new Set();
for(let i = 0; i < parts.length; ++i){
const part = parts[i];
if (!part) {
continue;
}
const params = part.split(";");
if (params.length > 2) {
throw new Error(`Invalid ${options.type} header`);
}
let token = params[0].toLowerCase();
if (!token) {
throw new Error(`Invalid ${options.type} header`);
}
const selection = {
token,
pos: i,
q: 1
};
if (preferences && lowers.has(token)) {
selection.pref = lowers.get(token).pos;
}
map.add(selection.token);
if (params.length === 2) {
const q = params[1];
const [key, value] = q.split("=");
if (!value || key !== "q" && key !== "Q") {
throw new Error(`Invalid ${options.type} header`);
}
const score = parseFloat(value);
if (score === 0) {
continue;
}
if (Number.isFinite(score) && score <= 1 && score >= 0.001) {
selection.q = score;
}
}
selections.push(selection);
}
selections.sort((a, b)=>{
if (b.q !== a.q) {
return b.q - a.q;
}
if (b.pref !== a.pref) {
if (a.pref === undefined) {
return 1;
}
if (b.pref === undefined) {
return -1;
}
return a.pref - b.pref;
}
return a.pos - b.pos;
});
const values = selections.map((selection)=>selection.token);
if (!preferences || !preferences.length) {
return values;
}
const preferred = [];
for (const selection of values){
if (selection === "*") {
for (const [preference, value] of lowers){
if (!map.has(preference)) {
preferred.push(value.orig);
}
}
} else {
const lower = selection.toLowerCase();
if (lowers.has(lower)) {
preferred.push(lowers.get(lower).orig);
}
}
}
return preferred;
}
export function acceptLanguage(header = "", preferences) {
return parse(header, preferences, {
type: "accept-language",
prefixMatch: true
})[0] || "";
}
//# sourceMappingURL=accept-header.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/server/accept-header.ts"],"names":["parse","raw","preferences","options","lowers","Map","header","replace","pos","preference","lower","toLowerCase","set","orig","prefixMatch","parts","split","pop","length","joined","join","has","selections","map","Set","i","part","params","Error","type","token","selection","q","pref","get","add","key","value","score","parseFloat","Number","isFinite","push","sort","a","b","undefined","values","preferred","acceptLanguage"],"mappings":"AAYA,SAASA,MACPC,GAAW,EACXC,WAAiC,EACjCC,OAAgB;IAEhB,MAAMC,SAAS,IAAIC;IACnB,MAAMC,SAASL,IAAIM,OAAO,CAAC,UAAU;IAErC,IAAIL,aAAa;QACf,IAAIM,MAAM;QACV,KAAK,MAAMC,cAAcP,YAAa;YACpC,MAAMQ,QAAQD,WAAWE,WAAW;YACpCP,OAAOQ,GAAG,CAACF,OAAO;gBAAEG,MAAMJ;gBAAYD,KAAKA;YAAM;YACjD,IAAIL,QAAQW,WAAW,EAAE;gBACvB,MAAMC,QAAQL,MAAMM,KAAK,CAAC;gBAC1B,MAAQD,MAAME,GAAG,IAAIF,MAAMG,MAAM,GAAG,EAAI;oBACtC,MAAMC,SAASJ,MAAMK,IAAI,CAAC;oBAC1B,IAAI,CAAChB,OAAOiB,GAAG,CAACF,SAAS;wBACvBf,OAAOQ,GAAG,CAACO,QAAQ;4BAAEN,MAAMJ;4BAAYD,KAAKA;wBAAM;oBACpD;gBACF;YACF;QACF;IACF;IAEA,MAAMO,QAAQT,OAAOU,KAAK,CAAC;IAC3B,MAAMM,aAA0B,EAAE;IAClC,MAAMC,MAAM,IAAIC;IAEhB,IAAK,IAAIC,IAAI,GAAGA,IAAIV,MAAMG,MAAM,EAAE,EAAEO,EAAG;QACrC,MAAMC,OAAOX,KAAK,CAACU,EAAE;QACrB,IAAI,CAACC,MAAM;YACT;QACF;QAEA,MAAMC,SAASD,KAAKV,KAAK,CAAC;QAC1B,IAAIW,OAAOT,MAAM,GAAG,GAAG;YACrB,MAAM,IAAIU,MAAM,CAAC,QAAQ,EAAEzB,QAAQ0B,IAAI,CAAC,OAAO,CAAC;QAClD;QAEA,IAAIC,QAAQH,MAAM,CAAC,EAAE,CAAChB,WAAW;QACjC,IAAI,CAACmB,OAAO;YACV,MAAM,IAAIF,MAAM,CAAC,QAAQ,EAAEzB,QAAQ0B,IAAI,CAAC,OAAO,CAAC;QAClD;QAEA,MAAME,YAAuB;YAAED;YAAOtB,KAAKiB;YAAGO,GAAG;QAAE;QACnD,IAAI9B,eAAeE,OAAOiB,GAAG,CAACS,QAAQ;YACpCC,UAAUE,IAAI,GAAG7B,OAAO8B,GAAG,CAACJ,OAAQtB,GAAG;QACzC;QAEAe,IAAIY,GAAG,CAACJ,UAAUD,KAAK;QAEvB,IAAIH,OAAOT,MAAM,KAAK,GAAG;YACvB,MAAMc,IAAIL,MAAM,CAAC,EAAE;YACnB,MAAM,CAACS,KAAKC,MAAM,GAAGL,EAAEhB,KAAK,CAAC;YAE7B,IAAI,CAACqB,SAAUD,QAAQ,OAAOA,QAAQ,KAAM;gBAC1C,MAAM,IAAIR,MAAM,CAAC,QAAQ,EAAEzB,QAAQ0B,IAAI,CAAC,OAAO,CAAC;YAClD;YAEA,MAAMS,QAAQC,WAAWF;YACzB,IAAIC,UAAU,GAAG;gBACf;YACF;YAEA,IAAIE,OAAOC,QAAQ,CAACH,UAAUA,SAAS,KAAKA,SAAS,OAAO;gBAC1DP,UAAUC,CAAC,GAAGM;YAChB;QACF;QAEAhB,WAAWoB,IAAI,CAACX;IAClB;IAEAT,WAAWqB,IAAI,CAAC,CAACC,GAAGC;QAClB,IAAIA,EAAEb,CAAC,KAAKY,EAAEZ,CAAC,EAAE;YACf,OAAOa,EAAEb,CAAC,GAAGY,EAAEZ,CAAC;QAClB;QAEA,IAAIa,EAAEZ,IAAI,KAAKW,EAAEX,IAAI,EAAE;YACrB,IAAIW,EAAEX,IAAI,KAAKa,WAAW;gBACxB,OAAO;YACT;YAEA,IAAID,EAAEZ,IAAI,KAAKa,WAAW;gBACxB,OAAO,CAAC;YACV;YAEA,OAAOF,EAAEX,IAAI,GAAGY,EAAEZ,IAAI;QACxB;QAEA,OAAOW,EAAEpC,GAAG,GAAGqC,EAAErC,GAAG;IACtB;IAEA,MAAMuC,SAASzB,WAAWC,GAAG,CAAC,CAACQ,YAAcA,UAAUD,KAAK;IAC5D,IAAI,CAAC5B,eAAe,CAACA,YAAYgB,MAAM,EAAE;QACvC,OAAO6B;IACT;IAEA,MAAMC,YAAsB,EAAE;IAC9B,KAAK,MAAMjB,aAAagB,OAAQ;QAC9B,IAAIhB,cAAc,KAAK;YACrB,KAAK,MAAM,CAACtB,YAAY4B,MAAM,IAAIjC,OAAQ;gBACxC,IAAI,CAACmB,IAAIF,GAAG,CAACZ,aAAa;oBACxBuC,UAAUN,IAAI,CAACL,MAAMxB,IAAI;gBAC3B;YACF;QACF,OAAO;YACL,MAAMH,QAAQqB,UAAUpB,WAAW;YACnC,IAAIP,OAAOiB,GAAG,CAACX,QAAQ;gBACrBsC,UAAUN,IAAI,CAACtC,OAAO8B,GAAG,CAACxB,OAAQG,IAAI;YACxC;QACF;IACF;IAEA,OAAOmC;AACT;AAEA,OAAO,SAASC,eAAe3C,SAAS,EAAE,EAAEJ,WAAsB;IAChE,OACEF,MAAMM,QAAQJ,aAAa;QACzB2B,MAAM;QACNf,aAAa;IACf,EAAE,CAAC,EAAE,IAAI;AAEb"}

View File

@@ -0,0 +1,15 @@
/**
* Parse cookies from the `headers` of request
* @param req request object
*/ export function getCookieParser(headers) {
return function parseCookie() {
const { cookie } = headers;
if (!cookie) {
return {};
}
const { parse: parseCookieFn } = require("next/dist/compiled/cookie");
return parseCookieFn(Array.isArray(cookie) ? cookie.join("; ") : cookie);
};
}
//# sourceMappingURL=get-cookie-parser.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/api-utils/get-cookie-parser.ts"],"names":["getCookieParser","headers","parseCookie","cookie","parse","parseCookieFn","require","Array","isArray","join"],"mappings":"AAEA;;;CAGC,GAED,OAAO,SAASA,gBAAgBC,OAE/B;IACC,OAAO,SAASC;QACd,MAAM,EAAEC,MAAM,EAAE,GAAGF;QAEnB,IAAI,CAACE,QAAQ;YACX,OAAO,CAAC;QACV;QAEA,MAAM,EAAEC,OAAOC,aAAa,EAAE,GAAGC,QAAQ;QACzC,OAAOD,cAAcE,MAAMC,OAAO,CAACL,UAAUA,OAAOM,IAAI,CAAC,QAAQN;IACnE;AACF"}

141
node_modules/next/dist/esm/server/api-utils/index.js generated vendored Normal file
View File

@@ -0,0 +1,141 @@
import { HeadersAdapter } from "../web/spec-extension/adapters/headers";
import { PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER } from "../../lib/constants";
/**
*
* @param res response object
* @param statusCode `HTTP` status code of response
*/ export function sendStatusCode(res, statusCode) {
res.statusCode = statusCode;
return res;
}
/**
*
* @param res response object
* @param [statusOrUrl] `HTTP` status code of redirect
* @param url URL of redirect
*/ export function redirect(res, statusOrUrl, url) {
if (typeof statusOrUrl === "string") {
url = statusOrUrl;
statusOrUrl = 307;
}
if (typeof statusOrUrl !== "number" || typeof url !== "string") {
throw new Error(`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`);
}
res.writeHead(statusOrUrl, {
Location: url
});
res.write(url);
res.end();
return res;
}
export function checkIsOnDemandRevalidate(req, previewProps) {
const headers = HeadersAdapter.from(req.headers);
const previewModeId = headers.get(PRERENDER_REVALIDATE_HEADER);
const isOnDemandRevalidate = previewModeId === previewProps.previewModeId;
const revalidateOnlyGenerated = headers.has(PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER);
return {
isOnDemandRevalidate,
revalidateOnlyGenerated
};
}
export const COOKIE_NAME_PRERENDER_BYPASS = `__prerender_bypass`;
export const COOKIE_NAME_PRERENDER_DATA = `__next_preview_data`;
export const RESPONSE_LIMIT_DEFAULT = 4 * 1024 * 1024;
export const SYMBOL_PREVIEW_DATA = Symbol(COOKIE_NAME_PRERENDER_DATA);
export const SYMBOL_CLEARED_COOKIES = Symbol(COOKIE_NAME_PRERENDER_BYPASS);
export function clearPreviewData(res, options = {}) {
if (SYMBOL_CLEARED_COOKIES in res) {
return res;
}
const { serialize } = require("next/dist/compiled/cookie");
const previous = res.getHeader("Set-Cookie");
res.setHeader(`Set-Cookie`, [
...typeof previous === "string" ? [
previous
] : Array.isArray(previous) ? previous : [],
serialize(COOKIE_NAME_PRERENDER_BYPASS, "", {
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
expires: new Date(0),
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/",
...options.path !== undefined ? {
path: options.path
} : undefined
}),
serialize(COOKIE_NAME_PRERENDER_DATA, "", {
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
expires: new Date(0),
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/",
...options.path !== undefined ? {
path: options.path
} : undefined
})
]);
Object.defineProperty(res, SYMBOL_CLEARED_COOKIES, {
value: true,
enumerable: false
});
return res;
}
/**
* Custom error class
*/ export class ApiError extends Error {
constructor(statusCode, message){
super(message);
this.statusCode = statusCode;
}
}
/**
* Sends error in `response`
* @param res response object
* @param statusCode of response
* @param message of response
*/ export function sendError(res, statusCode, message) {
res.statusCode = statusCode;
res.statusMessage = message;
res.end(message);
}
/**
* Execute getter function only if its needed
* @param LazyProps `req` and `params` for lazyProp
* @param prop name of property
* @param getter function to get data
*/ export function setLazyProp({ req }, prop, getter) {
const opts = {
configurable: true,
enumerable: true
};
const optsReset = {
...opts,
writable: true
};
Object.defineProperty(req, prop, {
...opts,
get: ()=>{
const value = getter();
// we set the property on the object to avoid recalculating it
Object.defineProperty(req, prop, {
...optsReset,
value
});
return value;
},
set: (value)=>{
Object.defineProperty(req, prop, {
...optsReset,
value
});
}
});
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/api-utils/index.ts"],"names":["HeadersAdapter","PRERENDER_REVALIDATE_HEADER","PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER","sendStatusCode","res","statusCode","redirect","statusOrUrl","url","Error","writeHead","Location","write","end","checkIsOnDemandRevalidate","req","previewProps","headers","from","previewModeId","get","isOnDemandRevalidate","revalidateOnlyGenerated","has","COOKIE_NAME_PRERENDER_BYPASS","COOKIE_NAME_PRERENDER_DATA","RESPONSE_LIMIT_DEFAULT","SYMBOL_PREVIEW_DATA","Symbol","SYMBOL_CLEARED_COOKIES","clearPreviewData","options","serialize","require","previous","getHeader","setHeader","Array","isArray","expires","Date","httpOnly","sameSite","process","env","NODE_ENV","secure","path","undefined","Object","defineProperty","value","enumerable","ApiError","constructor","message","sendError","statusMessage","setLazyProp","prop","getter","opts","configurable","optsReset","writable","set"],"mappings":"AAKA,SAASA,cAAc,QAAQ,yCAAwC;AACvE,SACEC,2BAA2B,EAC3BC,0CAA0C,QACrC,sBAAqB;AAW5B;;;;CAIC,GACD,OAAO,SAASC,eACdC,GAAoB,EACpBC,UAAkB;IAElBD,IAAIC,UAAU,GAAGA;IACjB,OAAOD;AACT;AAEA;;;;;CAKC,GACD,OAAO,SAASE,SACdF,GAAoB,EACpBG,WAA4B,EAC5BC,GAAY;IAEZ,IAAI,OAAOD,gBAAgB,UAAU;QACnCC,MAAMD;QACNA,cAAc;IAChB;IACA,IAAI,OAAOA,gBAAgB,YAAY,OAAOC,QAAQ,UAAU;QAC9D,MAAM,IAAIC,MACR,CAAC,qKAAqK,CAAC;IAE3K;IACAL,IAAIM,SAAS,CAACH,aAAa;QAAEI,UAAUH;IAAI;IAC3CJ,IAAIQ,KAAK,CAACJ;IACVJ,IAAIS,GAAG;IACP,OAAOT;AACT;AAEA,OAAO,SAASU,0BACdC,GAAgD,EAChDC,YAA+B;IAK/B,MAAMC,UAAUjB,eAAekB,IAAI,CAACH,IAAIE,OAAO;IAE/C,MAAME,gBAAgBF,QAAQG,GAAG,CAACnB;IAClC,MAAMoB,uBAAuBF,kBAAkBH,aAAaG,aAAa;IAEzE,MAAMG,0BAA0BL,QAAQM,GAAG,CACzCrB;IAGF,OAAO;QAAEmB;QAAsBC;IAAwB;AACzD;AAEA,OAAO,MAAME,+BAA+B,CAAC,kBAAkB,CAAC,CAAA;AAChE,OAAO,MAAMC,6BAA6B,CAAC,mBAAmB,CAAC,CAAA;AAE/D,OAAO,MAAMC,yBAAyB,IAAI,OAAO,KAAI;AAErD,OAAO,MAAMC,sBAAsBC,OAAOH,4BAA2B;AACrE,OAAO,MAAMI,yBAAyBD,OAAOJ,8BAA6B;AAE1E,OAAO,SAASM,iBACd1B,GAAuB,EACvB2B,UAEI,CAAC,CAAC;IAEN,IAAIF,0BAA0BzB,KAAK;QACjC,OAAOA;IACT;IAEA,MAAM,EAAE4B,SAAS,EAAE,GACjBC,QAAQ;IACV,MAAMC,WAAW9B,IAAI+B,SAAS,CAAC;IAC/B/B,IAAIgC,SAAS,CAAC,CAAC,UAAU,CAAC,EAAE;WACtB,OAAOF,aAAa,WACpB;YAACA;SAAS,GACVG,MAAMC,OAAO,CAACJ,YACdA,WACA,EAAE;QACNF,UAAUR,8BAA8B,IAAI;YAC1C,2DAA2D;YAC3D,oDAAoD;YACpD,wEAAwE;YACxEe,SAAS,IAAIC,KAAK;YAClBC,UAAU;YACVC,UAAUC,QAAQC,GAAG,CAACC,QAAQ,KAAK,gBAAgB,SAAS;YAC5DC,QAAQH,QAAQC,GAAG,CAACC,QAAQ,KAAK;YACjCE,MAAM;YACN,GAAIhB,QAAQgB,IAAI,KAAKC,YAChB;gBAAED,MAAMhB,QAAQgB,IAAI;YAAC,IACtBC,SAAS;QACf;QACAhB,UAAUP,4BAA4B,IAAI;YACxC,2DAA2D;YAC3D,oDAAoD;YACpD,wEAAwE;YACxEc,SAAS,IAAIC,KAAK;YAClBC,UAAU;YACVC,UAAUC,QAAQC,GAAG,CAACC,QAAQ,KAAK,gBAAgB,SAAS;YAC5DC,QAAQH,QAAQC,GAAG,CAACC,QAAQ,KAAK;YACjCE,MAAM;YACN,GAAIhB,QAAQgB,IAAI,KAAKC,YAChB;gBAAED,MAAMhB,QAAQgB,IAAI;YAAC,IACtBC,SAAS;QACf;KACD;IAEDC,OAAOC,cAAc,CAAC9C,KAAKyB,wBAAwB;QACjDsB,OAAO;QACPC,YAAY;IACd;IACA,OAAOhD;AACT;AAEA;;CAEC,GACD,OAAO,MAAMiD,iBAAiB5C;IAG5B6C,YAAYjD,UAAkB,EAAEkD,OAAe,CAAE;QAC/C,KAAK,CAACA;QACN,IAAI,CAAClD,UAAU,GAAGA;IACpB;AACF;AAEA;;;;;CAKC,GACD,OAAO,SAASmD,UACdpD,GAAoB,EACpBC,UAAkB,EAClBkD,OAAe;IAEfnD,IAAIC,UAAU,GAAGA;IACjBD,IAAIqD,aAAa,GAAGF;IACpBnD,IAAIS,GAAG,CAAC0C;AACV;AAMA;;;;;CAKC,GACD,OAAO,SAASG,YACd,EAAE3C,GAAG,EAAa,EAClB4C,IAAY,EACZC,MAAe;IAEf,MAAMC,OAAO;QAAEC,cAAc;QAAMV,YAAY;IAAK;IACpD,MAAMW,YAAY;QAAE,GAAGF,IAAI;QAAEG,UAAU;IAAK;IAE5Cf,OAAOC,cAAc,CAACnC,KAAK4C,MAAM;QAC/B,GAAGE,IAAI;QACPzC,KAAK;YACH,MAAM+B,QAAQS;YACd,8DAA8D;YAC9DX,OAAOC,cAAc,CAACnC,KAAK4C,MAAM;gBAAE,GAAGI,SAAS;gBAAEZ;YAAM;YACvD,OAAOA;QACT;QACAc,KAAK,CAACd;YACJF,OAAOC,cAAc,CAACnC,KAAK4C,MAAM;gBAAE,GAAGI,SAAS;gBAAEZ;YAAM;QACzD;IACF;AACF"}

439
node_modules/next/dist/esm/server/api-utils/node.js generated vendored Normal file
View File

@@ -0,0 +1,439 @@
import { checkIsOnDemandRevalidate } from ".";
import bytes from "next/dist/compiled/bytes";
import { generateETag } from "../lib/etag";
import { sendEtagResponse } from "../send-payload";
import { Stream } from "stream";
import { parse } from "next/dist/compiled/content-type";
import isError from "../../lib/is-error";
import { isResSent } from "../../shared/lib/utils";
import { interopDefault } from "../../lib/interop-default";
import { setLazyProp, sendStatusCode, redirect, clearPreviewData, sendError, ApiError, COOKIE_NAME_PRERENDER_BYPASS, COOKIE_NAME_PRERENDER_DATA, SYMBOL_PREVIEW_DATA, RESPONSE_LIMIT_DEFAULT } from "./index";
import { getCookieParser } from "./get-cookie-parser";
import { getTracer } from "../lib/trace/tracer";
import { NodeSpan } from "../lib/trace/constants";
import { RequestCookies } from "../web/spec-extension/cookies";
import { HeadersAdapter } from "../web/spec-extension/adapters/headers";
import { PRERENDER_REVALIDATE_HEADER, PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER } from "../../lib/constants";
export function tryGetPreviewData(req, res, options) {
var _cookies_get, _cookies_get1;
// if an On-Demand revalidation is being done preview mode
// is disabled
if (options && checkIsOnDemandRevalidate(req, options).isOnDemandRevalidate) {
return false;
}
// Read cached preview data if present
// TODO: use request metadata instead of a symbol
if (SYMBOL_PREVIEW_DATA in req) {
return req[SYMBOL_PREVIEW_DATA];
}
const headers = HeadersAdapter.from(req.headers);
const cookies = new RequestCookies(headers);
const previewModeId = (_cookies_get = cookies.get(COOKIE_NAME_PRERENDER_BYPASS)) == null ? void 0 : _cookies_get.value;
const tokenPreviewData = (_cookies_get1 = cookies.get(COOKIE_NAME_PRERENDER_DATA)) == null ? void 0 : _cookies_get1.value;
// Case: preview mode cookie set but data cookie is not set
if (previewModeId && !tokenPreviewData && previewModeId === options.previewModeId) {
// This is "Draft Mode" which doesn't use
// previewData, so we return an empty object
// for backwards compat with "Preview Mode".
const data = {};
Object.defineProperty(req, SYMBOL_PREVIEW_DATA, {
value: data,
enumerable: false
});
return data;
}
// Case: neither cookie is set.
if (!previewModeId && !tokenPreviewData) {
return false;
}
// Case: one cookie is set, but not the other.
if (!previewModeId || !tokenPreviewData) {
clearPreviewData(res);
return false;
}
// Case: preview session is for an old build.
if (previewModeId !== options.previewModeId) {
clearPreviewData(res);
return false;
}
let encryptedPreviewData;
try {
const jsonwebtoken = require("next/dist/compiled/jsonwebtoken");
encryptedPreviewData = jsonwebtoken.verify(tokenPreviewData, options.previewModeSigningKey);
} catch {
// TODO: warn
clearPreviewData(res);
return false;
}
const { decryptWithSecret } = require("../crypto-utils");
const decryptedPreviewData = decryptWithSecret(Buffer.from(options.previewModeEncryptionKey), encryptedPreviewData.data);
try {
// TODO: strict runtime type checking
const data = JSON.parse(decryptedPreviewData);
// Cache lookup
Object.defineProperty(req, SYMBOL_PREVIEW_DATA, {
value: data,
enumerable: false
});
return data;
} catch {
return false;
}
}
/**
* Parse `JSON` and handles invalid `JSON` strings
* @param str `JSON` string
*/ function parseJson(str) {
if (str.length === 0) {
// special-case empty json body, as it's a common client-side mistake
return {};
}
try {
return JSON.parse(str);
} catch (e) {
throw new ApiError(400, "Invalid JSON");
}
}
/**
* Parse incoming message like `json` or `urlencoded`
* @param req request object
*/ export async function parseBody(req, limit) {
let contentType;
try {
contentType = parse(req.headers["content-type"] || "text/plain");
} catch {
contentType = parse("text/plain");
}
const { type, parameters } = contentType;
const encoding = parameters.charset || "utf-8";
let buffer;
try {
const getRawBody = require("next/dist/compiled/raw-body");
buffer = await getRawBody(req, {
encoding,
limit
});
} catch (e) {
if (isError(e) && e.type === "entity.too.large") {
throw new ApiError(413, `Body exceeded ${limit} limit`);
} else {
throw new ApiError(400, "Invalid body");
}
}
const body = buffer.toString();
if (type === "application/json" || type === "application/ld+json") {
return parseJson(body);
} else if (type === "application/x-www-form-urlencoded") {
const qs = require("querystring");
return qs.decode(body);
} else {
return body;
}
}
function getMaxContentLength(responseLimit) {
if (responseLimit && typeof responseLimit !== "boolean") {
return bytes.parse(responseLimit);
}
return RESPONSE_LIMIT_DEFAULT;
}
/**
* Send `any` body to response
* @param req request object
* @param res response object
* @param body of response
*/ function sendData(req, res, body) {
if (body === null || body === undefined) {
res.end();
return;
}
// strip irrelevant headers/body
if (res.statusCode === 204 || res.statusCode === 304) {
res.removeHeader("Content-Type");
res.removeHeader("Content-Length");
res.removeHeader("Transfer-Encoding");
if (process.env.NODE_ENV === "development" && body) {
console.warn(`A body was attempted to be set with a 204 statusCode for ${req.url}, this is invalid and the body was ignored.\n` + `See more info here https://nextjs.org/docs/messages/invalid-api-status-body`);
}
res.end();
return;
}
const contentType = res.getHeader("Content-Type");
if (body instanceof Stream) {
if (!contentType) {
res.setHeader("Content-Type", "application/octet-stream");
}
body.pipe(res);
return;
}
const isJSONLike = [
"object",
"number",
"boolean"
].includes(typeof body);
const stringifiedBody = isJSONLike ? JSON.stringify(body) : body;
const etag = generateETag(stringifiedBody);
if (sendEtagResponse(req, res, etag)) {
return;
}
if (Buffer.isBuffer(body)) {
if (!contentType) {
res.setHeader("Content-Type", "application/octet-stream");
}
res.setHeader("Content-Length", body.length);
res.end(body);
return;
}
if (isJSONLike) {
res.setHeader("Content-Type", "application/json; charset=utf-8");
}
res.setHeader("Content-Length", Buffer.byteLength(stringifiedBody));
res.end(stringifiedBody);
}
/**
* Send `JSON` object
* @param res response object
* @param jsonBody of data
*/ function sendJson(res, jsonBody) {
// Set header to application/json
res.setHeader("Content-Type", "application/json; charset=utf-8");
// Use send to handle request
res.send(JSON.stringify(jsonBody));
}
function isValidData(str) {
return typeof str === "string" && str.length >= 16;
}
function setDraftMode(res, options) {
if (!isValidData(options.previewModeId)) {
throw new Error("invariant: invalid previewModeId");
}
const expires = options.enable ? undefined : new Date(0);
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
const { serialize } = require("next/dist/compiled/cookie");
const previous = res.getHeader("Set-Cookie");
res.setHeader(`Set-Cookie`, [
...typeof previous === "string" ? [
previous
] : Array.isArray(previous) ? previous : [],
serialize(COOKIE_NAME_PRERENDER_BYPASS, options.previewModeId, {
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/",
expires
})
]);
return res;
}
function setPreviewData(res, data, options) {
if (!isValidData(options.previewModeId)) {
throw new Error("invariant: invalid previewModeId");
}
if (!isValidData(options.previewModeEncryptionKey)) {
throw new Error("invariant: invalid previewModeEncryptionKey");
}
if (!isValidData(options.previewModeSigningKey)) {
throw new Error("invariant: invalid previewModeSigningKey");
}
const jsonwebtoken = require("next/dist/compiled/jsonwebtoken");
const { encryptWithSecret } = require("../crypto-utils");
const payload = jsonwebtoken.sign({
data: encryptWithSecret(Buffer.from(options.previewModeEncryptionKey), JSON.stringify(data))
}, options.previewModeSigningKey, {
algorithm: "HS256",
...options.maxAge !== undefined ? {
expiresIn: options.maxAge
} : undefined
});
// limit preview mode cookie to 2KB since we shouldn't store too much
// data here and browsers drop cookies over 4KB
if (payload.length > 2048) {
throw new Error(`Preview data is limited to 2KB currently, reduce how much data you are storing as preview data to continue`);
}
const { serialize } = require("next/dist/compiled/cookie");
const previous = res.getHeader("Set-Cookie");
res.setHeader(`Set-Cookie`, [
...typeof previous === "string" ? [
previous
] : Array.isArray(previous) ? previous : [],
serialize(COOKIE_NAME_PRERENDER_BYPASS, options.previewModeId, {
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/",
...options.maxAge !== undefined ? {
maxAge: options.maxAge
} : undefined,
...options.path !== undefined ? {
path: options.path
} : undefined
}),
serialize(COOKIE_NAME_PRERENDER_DATA, payload, {
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/",
...options.maxAge !== undefined ? {
maxAge: options.maxAge
} : undefined,
...options.path !== undefined ? {
path: options.path
} : undefined
})
]);
return res;
}
async function revalidate(urlPath, opts, req, context) {
if (typeof urlPath !== "string" || !urlPath.startsWith("/")) {
throw new Error(`Invalid urlPath provided to revalidate(), must be a path e.g. /blog/post-1, received ${urlPath}`);
}
const revalidateHeaders = {
[PRERENDER_REVALIDATE_HEADER]: context.previewModeId,
...opts.unstable_onlyGenerated ? {
[PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER]: "1"
} : {}
};
const allowedRevalidateHeaderKeys = [
...context.allowedRevalidateHeaderKeys || [],
...context.trustHostHeader ? [
"cookie",
"x-vercel-protection-bypass"
] : []
];
for (const key of Object.keys(req.headers)){
if (allowedRevalidateHeaderKeys.includes(key)) {
revalidateHeaders[key] = req.headers[key];
}
}
try {
if (context.trustHostHeader) {
const res = await fetch(`https://${req.headers.host}${urlPath}`, {
method: "HEAD",
headers: revalidateHeaders
});
// we use the cache header to determine successful revalidate as
// a non-200 status code can be returned from a successful revalidate
// e.g. notFound: true returns 404 status code but is successful
const cacheHeader = res.headers.get("x-vercel-cache") || res.headers.get("x-nextjs-cache");
if ((cacheHeader == null ? void 0 : cacheHeader.toUpperCase()) !== "REVALIDATED" && !(res.status === 404 && opts.unstable_onlyGenerated)) {
throw new Error(`Invalid response ${res.status}`);
}
} else if (context.revalidate) {
await context.revalidate({
urlPath,
revalidateHeaders,
opts
});
} else {
throw new Error(`Invariant: required internal revalidate method not passed to api-utils`);
}
} catch (err) {
throw new Error(`Failed to revalidate ${urlPath}: ${isError(err) ? err.message : err}`);
}
}
export async function apiResolver(req, res, query, resolverModule, apiContext, propagateError, dev, page) {
const apiReq = req;
const apiRes = res;
try {
var _config_api, _config_api1, _config_api2, _getTracer_getRootSpanAttributes;
if (!resolverModule) {
res.statusCode = 404;
res.end("Not Found");
return;
}
const config = resolverModule.config || {};
const bodyParser = ((_config_api = config.api) == null ? void 0 : _config_api.bodyParser) !== false;
const responseLimit = ((_config_api1 = config.api) == null ? void 0 : _config_api1.responseLimit) ?? true;
const externalResolver = ((_config_api2 = config.api) == null ? void 0 : _config_api2.externalResolver) || false;
// Parsing of cookies
setLazyProp({
req: apiReq
}, "cookies", getCookieParser(req.headers));
// Parsing query string
apiReq.query = query;
// Parsing preview data
setLazyProp({
req: apiReq
}, "previewData", ()=>tryGetPreviewData(req, res, apiContext));
// Checking if preview mode is enabled
setLazyProp({
req: apiReq
}, "preview", ()=>apiReq.previewData !== false ? true : undefined);
// Set draftMode to the same value as preview
setLazyProp({
req: apiReq
}, "draftMode", ()=>apiReq.preview);
// Parsing of body
if (bodyParser && !apiReq.body) {
apiReq.body = await parseBody(apiReq, config.api && config.api.bodyParser && config.api.bodyParser.sizeLimit ? config.api.bodyParser.sizeLimit : "1mb");
}
let contentLength = 0;
const maxContentLength = getMaxContentLength(responseLimit);
const writeData = apiRes.write;
const endResponse = apiRes.end;
apiRes.write = (...args)=>{
contentLength += Buffer.byteLength(args[0] || "");
return writeData.apply(apiRes, args);
};
apiRes.end = (...args)=>{
if (args.length && typeof args[0] !== "function") {
contentLength += Buffer.byteLength(args[0] || "");
}
if (responseLimit && contentLength >= maxContentLength) {
console.warn(`API response for ${req.url} exceeds ${bytes.format(maxContentLength)}. API Routes are meant to respond quickly. https://nextjs.org/docs/messages/api-routes-response-size-limit`);
}
return endResponse.apply(apiRes, args);
};
apiRes.status = (statusCode)=>sendStatusCode(apiRes, statusCode);
apiRes.send = (data)=>sendData(apiReq, apiRes, data);
apiRes.json = (data)=>sendJson(apiRes, data);
apiRes.redirect = (statusOrUrl, url)=>redirect(apiRes, statusOrUrl, url);
apiRes.setDraftMode = (options = {
enable: true
})=>setDraftMode(apiRes, Object.assign({}, apiContext, options));
apiRes.setPreviewData = (data, options = {})=>setPreviewData(apiRes, data, Object.assign({}, apiContext, options));
apiRes.clearPreviewData = (options = {})=>clearPreviewData(apiRes, options);
apiRes.revalidate = (urlPath, opts)=>revalidate(urlPath, opts || {}, req, apiContext);
const resolver = interopDefault(resolverModule);
let wasPiped = false;
if (process.env.NODE_ENV !== "production") {
// listen for pipe event and don't show resolve warning
res.once("pipe", ()=>wasPiped = true);
}
(_getTracer_getRootSpanAttributes = getTracer().getRootSpanAttributes()) == null ? void 0 : _getTracer_getRootSpanAttributes.set("next.route", page);
// Call API route method
const apiRouteResult = await getTracer().trace(NodeSpan.runHandler, {
spanName: `executing api route (pages) ${page}`
}, ()=>resolver(req, res));
if (process.env.NODE_ENV !== "production") {
if (typeof apiRouteResult !== "undefined") {
if (apiRouteResult instanceof Response) {
throw new Error('API route returned a Response object in the Node.js runtime, this is not supported. Please use `runtime: "edge"` instead: https://nextjs.org/docs/api-routes/edge-api-routes');
}
console.warn(`API handler should not return a value, received ${typeof apiRouteResult}.`);
}
if (!externalResolver && !isResSent(res) && !wasPiped) {
console.warn(`API resolved without sending a response for ${req.url}, this may result in stalled requests.`);
}
}
} catch (err) {
if (err instanceof ApiError) {
sendError(apiRes, err.statusCode, err.message);
} else {
if (dev) {
if (isError(err)) {
err.page = page;
}
throw err;
}
console.error(err);
if (propagateError) {
throw err;
}
sendError(apiRes, 500, "Internal Server Error");
}
}
}
//# sourceMappingURL=node.js.map

File diff suppressed because one or more lines are too long

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

@@ -0,0 +1,7 @@
// Buffer.byteLength polyfill in the Edge runtime, with only utf8 strings
// supported at the moment.
export function byteLength(payload) {
return new TextEncoder().encode(payload).buffer.byteLength;
}
//# sourceMappingURL=web.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/api-utils/web.ts"],"names":["byteLength","payload","TextEncoder","encode","buffer"],"mappings":"AAAA,yEAAyE;AACzE,2BAA2B;AAC3B,OAAO,SAASA,WAAWC,OAAe;IACxC,OAAO,IAAIC,cAAcC,MAAM,CAACF,SAASG,MAAM,CAACJ,UAAU;AAC5D"}

View File

@@ -0,0 +1,345 @@
import { ACTION, RSC, RSC_CONTENT_TYPE_HEADER } from "../../client/components/app-router-headers";
import { isNotFoundError } from "../../client/components/not-found";
import { getURLFromRedirectError, isRedirectError } from "../../client/components/redirect";
import RenderResult from "../render-result";
import { FlightRenderResult } from "./flight-render-result";
import { filterReqHeaders, actionsForbiddenHeaders } from "../lib/server-ipc/utils";
import { appendMutableCookies, getModifiedCookieValues } from "../web/spec-extension/adapters/request-cookies";
import { NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER } from "../../lib/constants";
function nodeToWebReadableStream(nodeReadable) {
if (process.env.NEXT_RUNTIME !== "edge") {
const { Readable } = require("stream");
if ("toWeb" in Readable && typeof Readable.toWeb === "function") {
return Readable.toWeb(nodeReadable);
}
return new ReadableStream({
start (controller) {
nodeReadable.on("data", (chunk)=>{
controller.enqueue(chunk);
});
nodeReadable.on("end", ()=>{
controller.close();
});
nodeReadable.on("error", (error)=>{
controller.error(error);
});
}
});
} else {
throw new Error("Invalid runtime");
}
}
function formDataFromSearchQueryString(query) {
const searchParams = new URLSearchParams(query);
const formData = new FormData();
for (const [key, value] of searchParams){
formData.append(key, value);
}
return formData;
}
function nodeHeadersToRecord(headers) {
const record = {};
for (const [key, value] of Object.entries(headers)){
if (value !== undefined) {
record[key] = Array.isArray(value) ? value.join(", ") : `${value}`;
}
}
return record;
}
function getForwardedHeaders(req, res) {
// Get request headers and cookies
const requestHeaders = req.headers;
const requestCookies = requestHeaders["cookie"] ?? "";
// Get response headers and Set-Cookie header
const responseHeaders = res.getHeaders();
const rawSetCookies = responseHeaders["set-cookie"];
const setCookies = (Array.isArray(rawSetCookies) ? rawSetCookies : [
rawSetCookies
]).map((setCookie)=>{
// remove the suffixes like 'HttpOnly' and 'SameSite'
const [cookie] = `${setCookie}`.split(";");
return cookie;
});
// Merge request and response headers
const mergedHeaders = filterReqHeaders({
...nodeHeadersToRecord(requestHeaders),
...nodeHeadersToRecord(responseHeaders)
}, actionsForbiddenHeaders);
// Merge cookies
const mergedCookies = requestCookies.split("; ").concat(setCookies).join("; ");
// Update the 'cookie' header with the merged cookies
mergedHeaders["cookie"] = mergedCookies;
// Remove headers that should not be forwarded
delete mergedHeaders["transfer-encoding"];
return new Headers(mergedHeaders);
}
async function addRevalidationHeader(res, { staticGenerationStore, requestStore }) {
var _staticGenerationStore_revalidatedTags;
await Promise.all(staticGenerationStore.pendingRevalidates || []);
// If a tag was revalidated, the client router needs to invalidate all the
// client router cache as they may be stale. And if a path was revalidated, the
// client needs to invalidate all subtrees below that path.
// To keep the header size small, we use a tuple of
// [[revalidatedPaths], isTagRevalidated ? 1 : 0, isCookieRevalidated ? 1 : 0]
// instead of a JSON object.
// TODO-APP: Currently the prefetch cache doesn't have subtree information,
// so we need to invalidate the entire cache if a path was revalidated.
// TODO-APP: Currently paths are treated as tags, so the second element of the tuple
// is always empty.
const isTagRevalidated = ((_staticGenerationStore_revalidatedTags = staticGenerationStore.revalidatedTags) == null ? void 0 : _staticGenerationStore_revalidatedTags.length) ? 1 : 0;
const isCookieRevalidated = getModifiedCookieValues(requestStore.mutableCookies).length ? 1 : 0;
res.setHeader("x-action-revalidated", JSON.stringify([
[],
isTagRevalidated,
isCookieRevalidated
]));
}
async function createRedirectRenderResult(req, res, redirectUrl, staticGenerationStore) {
res.setHeader("x-action-redirect", redirectUrl);
// if we're redirecting to a relative path, we'll try to stream the response
if (redirectUrl.startsWith("/")) {
var _staticGenerationStore_incrementalCache;
const forwardedHeaders = getForwardedHeaders(req, res);
forwardedHeaders.set(RSC, "1");
const host = req.headers["host"];
const proto = ((_staticGenerationStore_incrementalCache = staticGenerationStore.incrementalCache) == null ? void 0 : _staticGenerationStore_incrementalCache.requestProtocol) || "https";
const fetchUrl = new URL(`${proto}://${host}${redirectUrl}`);
if (staticGenerationStore.revalidatedTags) {
var _staticGenerationStore_incrementalCache_prerenderManifest_preview, _staticGenerationStore_incrementalCache_prerenderManifest, _staticGenerationStore_incrementalCache1;
forwardedHeaders.set(NEXT_CACHE_REVALIDATED_TAGS_HEADER, staticGenerationStore.revalidatedTags.join(","));
forwardedHeaders.set(NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, ((_staticGenerationStore_incrementalCache1 = staticGenerationStore.incrementalCache) == null ? void 0 : (_staticGenerationStore_incrementalCache_prerenderManifest = _staticGenerationStore_incrementalCache1.prerenderManifest) == null ? void 0 : (_staticGenerationStore_incrementalCache_prerenderManifest_preview = _staticGenerationStore_incrementalCache_prerenderManifest.preview) == null ? void 0 : _staticGenerationStore_incrementalCache_prerenderManifest_preview.previewModeId) || "");
}
// Ensures that when the path was revalidated we don't return a partial response on redirects
// if (staticGenerationStore.pathWasRevalidated) {
forwardedHeaders.delete("next-router-state-tree");
// }
try {
const headResponse = await fetch(fetchUrl, {
method: "HEAD",
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1
}
});
if (headResponse.headers.get("content-type") === RSC_CONTENT_TYPE_HEADER) {
const response = await fetch(fetchUrl, {
method: "GET",
headers: forwardedHeaders,
next: {
// @ts-ignore
internal: 1
}
});
// copy the headers from the redirect response to the response we're sending
for (const [key, value] of response.headers){
if (!actionsForbiddenHeaders.includes(key)) {
res.setHeader(key, value);
}
}
return new FlightRenderResult(response.body);
}
} catch (err) {
// we couldn't stream the redirect response, so we'll just do a normal redirect
console.error(`failed to get redirect response`, err);
}
}
return new RenderResult(JSON.stringify({}));
}
export async function handleAction({ req, res, ComponentMod, page, serverActionsManifest, generateFlight, staticGenerationStore, requestStore, serverActionsBodySizeLimit }) {
let actionId = req.headers[ACTION.toLowerCase()];
const contentType = req.headers["content-type"];
const isURLEncodedAction = req.method === "POST" && contentType === "application/x-www-form-urlencoded";
const isMultipartAction = req.method === "POST" && (contentType == null ? void 0 : contentType.startsWith("multipart/form-data"));
const isFetchAction = actionId !== undefined && typeof actionId === "string" && req.method === "POST";
if (isFetchAction || isURLEncodedAction || isMultipartAction) {
// ensure we avoid caching server actions unexpectedly
res.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
let bound = [];
const workerName = "app" + page;
const serverModuleMap = new Proxy({}, {
get: (_, id)=>{
return {
id: serverActionsManifest[process.env.NEXT_RUNTIME === "edge" ? "edge" : "node"][id].workers[workerName],
name: id,
chunks: []
};
}
});
const { actionAsyncStorage } = ComponentMod;
let actionResult;
try {
await actionAsyncStorage.run({
isAction: true
}, async ()=>{
if (process.env.NEXT_RUNTIME === "edge") {
// Use react-server-dom-webpack/server.edge
const { decodeReply, decodeAction } = ComponentMod;
const webRequest = req;
if (!webRequest.body) {
throw new Error("invariant: Missing request body.");
}
if (isMultipartAction) {
// TODO-APP: Add streaming support
const formData = await webRequest.request.formData();
if (isFetchAction) {
bound = await decodeReply(formData, serverModuleMap);
} else {
const action = await decodeAction(formData, serverModuleMap);
await action();
// Skip the fetch path
return;
}
} else {
let actionData = "";
const reader = webRequest.body.getReader();
while(true){
const { done, value } = await reader.read();
if (done) {
break;
}
actionData += new TextDecoder().decode(value);
}
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData);
bound = await decodeReply(formData, serverModuleMap);
} else {
bound = await decodeReply(actionData, serverModuleMap);
}
}
} else {
// Use react-server-dom-webpack/server.node which supports streaming
const { decodeReply, decodeReplyFromBusboy, decodeAction } = require(`react-server-dom-webpack/server.node`);
if (isMultipartAction) {
if (isFetchAction) {
const busboy = require("busboy");
const bb = busboy({
headers: req.headers
});
req.pipe(bb);
bound = await decodeReplyFromBusboy(bb, serverModuleMap);
} else {
// React doesn't yet publish a busboy version of decodeAction
// so we polyfill the parsing of FormData.
const UndiciRequest = require("next/dist/compiled/undici").Request;
const fakeRequest = new UndiciRequest("http://localhost", {
method: "POST",
headers: {
"Content-Type": req.headers["content-type"]
},
body: nodeToWebReadableStream(req),
duplex: "half"
});
const formData = await fakeRequest.formData();
const action = await decodeAction(formData, serverModuleMap);
await action();
// Skip the fetch path
return;
}
} else {
const { parseBody } = require("../api-utils/node");
let actionData;
try {
actionData = await parseBody(req, serverActionsBodySizeLimit ?? "1mb") || "";
} catch (e) {
if (e && e.statusCode === 413) {
// Exceeded the size limit
e.message = e.message + "\nTo configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/server-actions#size-limitation";
}
throw e;
}
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData);
bound = await decodeReply(formData, serverModuleMap);
} else {
bound = await decodeReply(actionData, serverModuleMap);
}
}
}
// actions.js
// app/page.js
// action worker1
// appRender1
// app/foo/page.js
// action worker2
// appRender
// / -> fire action -> POST / -> appRender1 -> modId for the action file
// /foo -> fire action -> POST /foo -> appRender2 -> modId for the action file
const actionModId = serverActionsManifest[process.env.NEXT_RUNTIME === "edge" ? "edge" : "node"][actionId].workers[workerName];
const actionHandler = ComponentMod.__next_app__.require(actionModId)[actionId];
const returnVal = await actionHandler.apply(null, bound);
// For form actions, we need to continue rendering the page.
if (isFetchAction) {
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore
});
actionResult = await generateFlight({
actionResult: Promise.resolve(returnVal),
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated
});
}
});
return actionResult;
} catch (err) {
if (isRedirectError(err)) {
const redirectUrl = getURLFromRedirectError(err);
// if it's a fetch action, we don't want to mess with the status code
// and we'll handle it on the client router
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore
});
if (isFetchAction) {
return createRedirectRenderResult(req, res, redirectUrl, staticGenerationStore);
}
if (err.mutableCookies) {
const headers = new Headers();
// If there were mutable cookies set, we need to set them on the
// response.
if (appendMutableCookies(headers, err.mutableCookies)) {
res.setHeader("set-cookie", Array.from(headers.values()));
}
}
res.setHeader("Location", redirectUrl);
res.statusCode = 303;
return new RenderResult("");
} else if (isNotFoundError(err)) {
res.statusCode = 404;
await addRevalidationHeader(res, {
staticGenerationStore,
requestStore
});
if (isFetchAction) {
const promise = Promise.reject(err);
try {
await promise;
} catch {}
return generateFlight({
skipFlight: false,
actionResult: promise,
asNotFound: true
});
}
return "not-found";
}
if (isFetchAction) {
res.statusCode = 500;
await Promise.all(staticGenerationStore.pendingRevalidates || []);
const promise = Promise.reject(err);
try {
await promise;
} catch {}
return generateFlight({
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated
});
}
throw err;
}
}
}
//# sourceMappingURL=action-handler.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,59 @@
import { DYNAMIC_ERROR_CODE } from "../../client/components/hooks-server-context";
import stringHash from "next/dist/compiled/string-hash";
import { formatServerError } from "../../lib/format-server-error";
import { isNotFoundError } from "../../client/components/not-found";
import { isRedirectError } from "../../client/components/redirect";
import { NEXT_DYNAMIC_NO_SSR_CODE } from "../../shared/lib/lazy-dynamic/no-ssr-error";
import { SpanStatusCode, getTracer } from "../lib/trace/tracer";
/**
* Create error handler for renderers.
* Tolerate dynamic server errors during prerendering so console
* isn't spammed with unactionable errors
*/ export function createErrorHandler({ /**
* Used for debugging
*/ _source, dev, isNextExport, errorLogger, capturedErrors, allCapturedErrors }) {
return (err)=>{
var _err_message;
if (allCapturedErrors) allCapturedErrors.push(err);
if (err && (err.digest === DYNAMIC_ERROR_CODE || isNotFoundError(err) || err.digest === NEXT_DYNAMIC_NO_SSR_CODE || isRedirectError(err))) {
return err.digest;
}
// Format server errors in development to add more helpful error messages
if (dev) {
formatServerError(err);
}
// Used for debugging error source
// console.error(_source, err)
// Don't log the suppressed error during export
if (!(isNextExport && (err == null ? void 0 : (_err_message = err.message) == null ? void 0 : _err_message.includes("The specific message is omitted in production builds to avoid leaking sensitive details.")))) {
// Record exception in an active span, if available.
const span = getTracer().getActiveScopeSpan();
if (span) {
span.recordException(err);
span.setStatus({
code: SpanStatusCode.ERROR,
message: err.message
});
}
if (errorLogger) {
errorLogger(err).catch(()=>{});
} else {
// The error logger is currently not provided in the edge runtime.
// Use `log-app-dir-error` instead.
// It won't log the source code, but the error will be more useful.
if (process.env.NODE_ENV !== "production") {
const { logAppDirError } = require("../dev/log-app-dir-error");
logAppDirError(err);
}
if (process.env.NODE_ENV === "production") {
console.error(err);
}
}
}
capturedErrors.push(err);
// TODO-APP: look at using webcrypto instead. Requires a promise to be awaited.
return stringHash(err.message + err.stack + (err.digest || "")).toString();
};
}
//# sourceMappingURL=create-error-handler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/create-error-handler.tsx"],"names":["DYNAMIC_ERROR_CODE","stringHash","formatServerError","isNotFoundError","isRedirectError","NEXT_DYNAMIC_NO_SSR_CODE","SpanStatusCode","getTracer","createErrorHandler","_source","dev","isNextExport","errorLogger","capturedErrors","allCapturedErrors","err","push","digest","message","includes","span","getActiveScopeSpan","recordException","setStatus","code","ERROR","catch","process","env","NODE_ENV","logAppDirError","require","console","error","stack","toString"],"mappings":"AAAA,SAASA,kBAAkB,QAAQ,+CAA8C;AACjF,OAAOC,gBAAgB,iCAAgC;AACvD,SAASC,iBAAiB,QAAQ,gCAA+B;AACjE,SAASC,eAAe,QAAQ,oCAAmC;AACnE,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,wBAAwB,QAAQ,6CAA4C;AACrF,SAASC,cAAc,EAAEC,SAAS,QAAQ,sBAAqB;AAE/D;;;;CAIC,GACD,OAAO,SAASC,mBAAmB,EACjC;;GAEC,GACDC,OAAO,EACPC,GAAG,EACHC,YAAY,EACZC,WAAW,EACXC,cAAc,EACdC,iBAAiB,EAQlB;IACC,OAAO,CAACC;YAuBFA;QAtBJ,IAAID,mBAAmBA,kBAAkBE,IAAI,CAACD;QAE9C,IACEA,OACCA,CAAAA,IAAIE,MAAM,KAAKjB,sBACdG,gBAAgBY,QAChBA,IAAIE,MAAM,KAAKZ,4BACfD,gBAAgBW,IAAG,GACrB;YACA,OAAOA,IAAIE,MAAM;QACnB;QAEA,yEAAyE;QACzE,IAAIP,KAAK;YACPR,kBAAkBa;QACpB;QACA,kCAAkC;QAClC,8BAA8B;QAC9B,+CAA+C;QAC/C,IACE,CACEJ,CAAAA,iBACAI,wBAAAA,eAAAA,IAAKG,OAAO,qBAAZH,aAAcI,QAAQ,CACpB,4FACF,GAEF;YACA,oDAAoD;YACpD,MAAMC,OAAOb,YAAYc,kBAAkB;YAC3C,IAAID,MAAM;gBACRA,KAAKE,eAAe,CAACP;gBACrBK,KAAKG,SAAS,CAAC;oBACbC,MAAMlB,eAAemB,KAAK;oBAC1BP,SAASH,IAAIG,OAAO;gBACtB;YACF;YAEA,IAAIN,aAAa;gBACfA,YAAYG,KAAKW,KAAK,CAAC,KAAO;YAChC,OAAO;gBACL,kEAAkE;gBAClE,mCAAmC;gBACnC,mEAAmE;gBACnE,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;oBACzC,MAAM,EAAEC,cAAc,EAAE,GACtBC,QAAQ;oBACVD,eAAef;gBACjB;gBACA,IAAIY,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;oBACzCG,QAAQC,KAAK,CAAClB;gBAChB;YACF;QACF;QAEAF,eAAeG,IAAI,CAACD;QACpB,+EAA+E;QAC/E,OAAOd,WAAWc,IAAIG,OAAO,GAAGH,IAAImB,KAAK,GAAInB,CAAAA,IAAIE,MAAM,IAAI,EAAC,GAAIkB,QAAQ;IAC1E;AACF"}

View File

@@ -0,0 +1,28 @@
import { PAGE_SEGMENT_KEY } from "../../shared/lib/constants";
export function addSearchParamsIfPageSegment(segment, searchParams) {
const isPageSegment = segment === PAGE_SEGMENT_KEY;
if (isPageSegment) {
const stringifiedQuery = JSON.stringify(searchParams);
return stringifiedQuery !== "{}" ? segment + "?" + stringifiedQuery : segment;
}
return segment;
}
export function createFlightRouterStateFromLoaderTree([segment, parallelRoutes, { layout }], getDynamicParamFromSegment, searchParams, rootLayoutIncluded = false) {
const dynamicParam = getDynamicParamFromSegment(segment);
const treeSegment = dynamicParam ? dynamicParam.treeSegment : segment;
const segmentTree = [
addSearchParamsIfPageSegment(treeSegment, searchParams),
{}
];
if (!rootLayoutIncluded && typeof layout !== "undefined") {
rootLayoutIncluded = true;
segmentTree[4] = true;
}
segmentTree[1] = Object.keys(parallelRoutes).reduce((existingValue, currentValue)=>{
existingValue[currentValue] = createFlightRouterStateFromLoaderTree(parallelRoutes[currentValue], getDynamicParamFromSegment, searchParams, rootLayoutIncluded);
return existingValue;
}, {});
return segmentTree;
}
//# sourceMappingURL=create-flight-router-state-from-loader-tree.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/create-flight-router-state-from-loader-tree.ts"],"names":["PAGE_SEGMENT_KEY","addSearchParamsIfPageSegment","segment","searchParams","isPageSegment","stringifiedQuery","JSON","stringify","createFlightRouterStateFromLoaderTree","parallelRoutes","layout","getDynamicParamFromSegment","rootLayoutIncluded","dynamicParam","treeSegment","segmentTree","Object","keys","reduce","existingValue","currentValue"],"mappings":"AAGA,SAASA,gBAAgB,QAAQ,6BAA4B;AAE7D,OAAO,SAASC,6BACdC,OAAgB,EAChBC,YAAiB;IAEjB,MAAMC,gBAAgBF,YAAYF;IAElC,IAAII,eAAe;QACjB,MAAMC,mBAAmBC,KAAKC,SAAS,CAACJ;QACxC,OAAOE,qBAAqB,OACxBH,UAAU,MAAMG,mBAChBH;IACN;IAEA,OAAOA;AACT;AAEA,OAAO,SAASM,sCACd,CAACN,SAASO,gBAAgB,EAAEC,MAAM,EAAE,CAAa,EACjDC,0BAAsD,EACtDR,YAAiB,EACjBS,qBAAqB,KAAK;IAE1B,MAAMC,eAAeF,2BAA2BT;IAChD,MAAMY,cAAcD,eAAeA,aAAaC,WAAW,GAAGZ;IAE9D,MAAMa,cAAiC;QACrCd,6BAA6Ba,aAAaX;QAC1C,CAAC;KACF;IAED,IAAI,CAACS,sBAAsB,OAAOF,WAAW,aAAa;QACxDE,qBAAqB;QACrBG,WAAW,CAAC,EAAE,GAAG;IACnB;IAEAA,WAAW,CAAC,EAAE,GAAGC,OAAOC,IAAI,CAACR,gBAAgBS,MAAM,CACjD,CAACC,eAAeC;QACdD,aAAa,CAACC,aAAa,GAAGZ,sCAC5BC,cAAc,CAACW,aAAa,EAC5BT,4BACAR,cACAS;QAEF,OAAOO;IACT,GACA,CAAC;IAGH,OAAOJ;AACT"}

View File

@@ -0,0 +1,28 @@
import React, { use } from "react";
import { useFlightResponse } from "./use-flight-response";
/**
* Create a component that renders the Flight stream.
* This is only used for renderToHTML, the Flight response does not need additional wrappers.
*/ export function createServerComponentRenderer(ComponentToRender, ComponentMod, { transformStream, clientReferenceManifest, serverContexts, rscChunks }, serverComponentsErrorHandler, nonce) {
let RSCStream;
const createRSCStream = (props)=>{
if (!RSCStream) {
RSCStream = ComponentMod.renderToReadableStream(/*#__PURE__*/ React.createElement(ComponentToRender, props), clientReferenceManifest.clientModules, {
context: serverContexts,
onError: serverComponentsErrorHandler
});
}
return RSCStream;
};
const flightResponseRef = {
current: null
};
const writable = transformStream.writable;
return function ServerComponentWrapper(props) {
const reqStream = createRSCStream(props);
const response = useFlightResponse(writable, reqStream, clientReferenceManifest, rscChunks, flightResponseRef, nonce);
return use(response);
};
}
//# sourceMappingURL=create-server-components-renderer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/create-server-components-renderer.tsx"],"names":["React","use","useFlightResponse","createServerComponentRenderer","ComponentToRender","ComponentMod","transformStream","clientReferenceManifest","serverContexts","rscChunks","serverComponentsErrorHandler","nonce","RSCStream","createRSCStream","props","renderToReadableStream","clientModules","context","onError","flightResponseRef","current","writable","ServerComponentWrapper","reqStream","response"],"mappings":"AAGA,OAAOA,SAASC,GAAG,QAAQ,QAAO;AAElC,SAASC,iBAAiB,QAAQ,wBAAuB;AAEzD;;;CAGC,GACD,OAAO,SAASC,8BACdC,iBAAwC,EACxCC,YAMC,EACD,EACEC,eAAe,EACfC,uBAAuB,EACvBC,cAAc,EACdC,SAAS,EAQV,EACDC,4BAAmE,EACnEC,KAAc;IAEd,IAAIC;IACJ,MAAMC,kBAAkB,CAACC;QACvB,IAAI,CAACF,WAAW;YACdA,YAAYP,aAAaU,sBAAsB,eAC7C,oBAACX,mBAAuBU,QACxBP,wBAAwBS,aAAa,EACrC;gBACEC,SAAST;gBACTU,SAASR;YACX;QAEJ;QACA,OAAOE;IACT;IAEA,MAAMO,oBAAuC;QAAEC,SAAS;IAAK;IAE7D,MAAMC,WAAWf,gBAAgBe,QAAQ;IACzC,OAAO,SAASC,uBAAuBR,KAAY;QACjD,MAAMS,YAAYV,gBAAgBC;QAClC,MAAMU,WAAWtB,kBACfmB,UACAE,WACAhB,yBACAE,WACAU,mBACAR;QAEF,OAAOV,IAAIuB;IACb;AACF"}

View File

@@ -0,0 +1,16 @@
const { renderToReadableStream, decodeReply, decodeAction } = require("react-server-dom-webpack/server.edge");
import AppRouter from "../../client/components/app-router";
import LayoutRouter from "../../client/components/layout-router";
import RenderFromTemplateContext from "../../client/components/render-from-template-context";
import { staticGenerationAsyncStorage } from "../../client/components/static-generation-async-storage.external";
import { requestAsyncStorage } from "../../client/components/request-async-storage.external";
import { actionAsyncStorage } from "../../client/components/action-async-storage.external";
import { staticGenerationBailout } from "../../client/components/static-generation-bailout";
import StaticGenerationSearchParamsBailoutProvider from "../../client/components/static-generation-searchparams-bailout-provider";
import { createSearchParamsBailoutProxy } from "../../client/components/searchparams-bailout-proxy";
import * as serverHooks from "../../client/components/hooks-server-context";
import { preloadStyle, preloadFont, preconnect } from "../../server/app-render/rsc/preloads";
const { NotFoundBoundary } = require("next/dist/client/components/not-found-boundary");
export { AppRouter, LayoutRouter, RenderFromTemplateContext, staticGenerationAsyncStorage, requestAsyncStorage, actionAsyncStorage, staticGenerationBailout, createSearchParamsBailoutProxy, serverHooks, renderToReadableStream, decodeReply, decodeAction, preloadStyle, preloadFont, preconnect, StaticGenerationSearchParamsBailoutProvider, NotFoundBoundary, };
//# sourceMappingURL=entry-base.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/entry-base.ts"],"names":["renderToReadableStream","decodeReply","decodeAction","require","AppRouter","LayoutRouter","RenderFromTemplateContext","staticGenerationAsyncStorage","requestAsyncStorage","actionAsyncStorage","staticGenerationBailout","StaticGenerationSearchParamsBailoutProvider","createSearchParamsBailoutProxy","serverHooks","preloadStyle","preloadFont","preconnect","NotFoundBoundary"],"mappings":"AAAA,MAAM,EACJA,sBAAsB,EACtBC,WAAW,EACXC,YAAY,EAEb,GAAGC,QAAQ;AAEZ,OAAOC,eAAe,qCAAoC;AAC1D,OAAOC,kBAAkB,wCAAuC;AAChE,OAAOC,+BAA+B,uDAAsD;AAC5F,SAASC,4BAA4B,QAAQ,mEAAkE;AAC/G,SAASC,mBAAmB,QAAQ,yDAAwD;AAC5F,SAASC,kBAAkB,QAAQ,wDAAuD;AAC1F,SAASC,uBAAuB,QAAQ,oDAAmD;AAC3F,OAAOC,iDAAiD,0EAAyE;AACjI,SAASC,8BAA8B,QAAQ,qDAAoD;AACnG,YAAYC,iBAAiB,+CAA8C;AAE3E,SACEC,YAAY,EACZC,WAAW,EACXC,UAAU,QACL,uCAAsC;AAE7C,MAAM,EAAEC,gBAAgB,EAAE,GACxBd,QAAQ;AAEV,SACEC,SAAS,EACTC,YAAY,EACZC,yBAAyB,EACzBC,4BAA4B,EAC5BC,mBAAmB,EACnBC,kBAAkB,EAClBC,uBAAuB,EACvBE,8BAA8B,EAC9BC,WAAW,EACXb,sBAAsB,EACtBC,WAAW,EACXC,YAAY,EACZY,YAAY,EACZC,WAAW,EACXC,UAAU,EACVL,2CAA2C,EAC3CM,gBAAgB,KACjB"}

View File

@@ -0,0 +1,13 @@
import { RSC_CONTENT_TYPE_HEADER } from "../../client/components/app-router-headers";
import RenderResult from "../render-result";
/**
* Flight Response is always set to RSC_CONTENT_TYPE_HEADER to ensure it does not get interpreted as HTML.
*/ export class FlightRenderResult extends RenderResult {
constructor(response){
super(response, {
contentType: RSC_CONTENT_TYPE_HEADER
});
}
}
//# sourceMappingURL=flight-render-result.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/flight-render-result.ts"],"names":["RSC_CONTENT_TYPE_HEADER","RenderResult","FlightRenderResult","constructor","response","contentType"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,6CAA4C;AACpF,OAAOC,kBAAkB,mBAAkB;AAE3C;;CAEC,GACD,OAAO,MAAMC,2BAA2BD;IACtCE,YAAYC,QAA6C,CAAE;QACzD,KAAK,CAACA,UAAU;YAAEC,aAAaL;QAAwB;IACzD;AACF"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/flight-response-ref.tsx"],"names":[],"mappings":"AAAA,WAEC"}

View File

@@ -0,0 +1,22 @@
/**
* Get external stylesheet link hrefs based on server CSS manifest.
*/ export function getCssInlinedLinkTags(clientReferenceManifest, filePath, injectedCSS, collectNewCSSImports) {
const filePathWithoutExt = filePath.replace(/\.[^.]+$/, "");
const chunks = new Set();
const entryCSSFiles = clientReferenceManifest.entryCSSFiles[filePathWithoutExt];
if (entryCSSFiles) {
for (const file of entryCSSFiles){
if (!injectedCSS.has(file)) {
if (collectNewCSSImports) {
injectedCSS.add(file);
}
chunks.add(file);
}
}
}
return [
...chunks
];
}
//# sourceMappingURL=get-css-inlined-link-tags.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/get-css-inlined-link-tags.tsx"],"names":["getCssInlinedLinkTags","clientReferenceManifest","filePath","injectedCSS","collectNewCSSImports","filePathWithoutExt","replace","chunks","Set","entryCSSFiles","file","has","add"],"mappings":"AAEA;;CAEC,GACD,OAAO,SAASA,sBACdC,uBAAgD,EAChDC,QAAgB,EAChBC,WAAwB,EACxBC,oBAA8B;IAE9B,MAAMC,qBAAqBH,SAASI,OAAO,CAAC,YAAY;IACxD,MAAMC,SAAS,IAAIC;IAEnB,MAAMC,gBACJR,wBAAwBQ,aAAa,CAACJ,mBAAmB;IAE3D,IAAII,eAAe;QACjB,KAAK,MAAMC,QAAQD,cAAe;YAChC,IAAI,CAACN,YAAYQ,GAAG,CAACD,OAAO;gBAC1B,IAAIN,sBAAsB;oBACxBD,YAAYS,GAAG,CAACF;gBAClB;gBACAH,OAAOK,GAAG,CAACF;YACb;QACF;IACF;IAEA,OAAO;WAAIH;KAAO;AACpB"}

View File

@@ -0,0 +1,35 @@
/**
* Get hrefs for fonts to preload
* Returns null if there are no fonts at all.
* Returns string[] if there are fonts to preload (font paths)
* Returns empty string[] if there are fonts but none to preload and no other fonts have been preloaded
* Returns null if there are fonts but none to preload and at least some were previously preloaded
*/ export function getPreloadableFonts(nextFontManifest, filePath, injectedFontPreloadTags) {
if (!nextFontManifest || !filePath) {
return null;
}
const filepathWithoutExtension = filePath.replace(/\.[^.]+$/, "");
const fontFiles = new Set();
let foundFontUsage = false;
const preloadedFontFiles = nextFontManifest.app[filepathWithoutExtension];
if (preloadedFontFiles) {
foundFontUsage = true;
for (const fontFile of preloadedFontFiles){
if (!injectedFontPreloadTags.has(fontFile)) {
fontFiles.add(fontFile);
injectedFontPreloadTags.add(fontFile);
}
}
}
if (fontFiles.size) {
return [
...fontFiles
].sort();
} else if (foundFontUsage && injectedFontPreloadTags.size === 0) {
return [];
} else {
return null;
}
}
//# sourceMappingURL=get-preloadable-fonts.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/get-preloadable-fonts.tsx"],"names":["getPreloadableFonts","nextFontManifest","filePath","injectedFontPreloadTags","filepathWithoutExtension","replace","fontFiles","Set","foundFontUsage","preloadedFontFiles","app","fontFile","has","add","size","sort"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,SAASA,oBACdC,gBAA8C,EAC9CC,QAA4B,EAC5BC,uBAAoC;IAEpC,IAAI,CAACF,oBAAoB,CAACC,UAAU;QAClC,OAAO;IACT;IACA,MAAME,2BAA2BF,SAASG,OAAO,CAAC,YAAY;IAC9D,MAAMC,YAAY,IAAIC;IACtB,IAAIC,iBAAiB;IAErB,MAAMC,qBAAqBR,iBAAiBS,GAAG,CAACN,yBAAyB;IACzE,IAAIK,oBAAoB;QACtBD,iBAAiB;QACjB,KAAK,MAAMG,YAAYF,mBAAoB;YACzC,IAAI,CAACN,wBAAwBS,GAAG,CAACD,WAAW;gBAC1CL,UAAUO,GAAG,CAACF;gBACdR,wBAAwBU,GAAG,CAACF;YAC9B;QACF;IACF;IAEA,IAAIL,UAAUQ,IAAI,EAAE;QAClB,OAAO;eAAIR;SAAU,CAACS,IAAI;IAC5B,OAAO,IAAIP,kBAAkBL,wBAAwBW,IAAI,KAAK,GAAG;QAC/D,OAAO,EAAE;IACX,OAAO;QACL,OAAO;IACT;AACF"}

View File

@@ -0,0 +1,30 @@
import { ESCAPE_REGEX } from "../htmlescape";
export function getScriptNonceFromHeader(cspHeaderValue) {
var _directive_split_slice_map_find;
const directives = cspHeaderValue// Directives are split by ';'.
.split(";").map((directive)=>directive.trim());
// First try to find the directive for the 'script-src', otherwise try to
// fallback to the 'default-src'.
const directive = directives.find((dir)=>dir.startsWith("script-src")) || directives.find((dir)=>dir.startsWith("default-src"));
// If no directive could be found, then we're done.
if (!directive) {
return;
}
// Extract the nonce from the directive
const nonce = (_directive_split_slice_map_find = directive.split(" ")// Remove the 'strict-src'/'default-src' string, this can't be the nonce.
.slice(1).map((source)=>source.trim())// Find the first source with the 'nonce-' prefix.
.find((source)=>source.startsWith("'nonce-") && source.length > 8 && source.endsWith("'"))) == null ? void 0 : _directive_split_slice_map_find.slice(7, -1);
// If we could't find the nonce, then we're done.
if (!nonce) {
return;
}
// Don't accept the nonce value if it contains HTML escape characters.
// Technically, the spec requires a base64'd value, but this is just an
// extra layer.
if (ESCAPE_REGEX.test(nonce)) {
throw new Error("Nonce value from Content-Security-Policy contained HTML escape characters.\nLearn more: https://nextjs.org/docs/messages/nonce-contained-invalid-characters");
}
return nonce;
}
//# sourceMappingURL=get-script-nonce-from-header.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/get-script-nonce-from-header.tsx"],"names":["ESCAPE_REGEX","getScriptNonceFromHeader","cspHeaderValue","directive","directives","split","map","trim","find","dir","startsWith","nonce","slice","source","length","endsWith","test","Error"],"mappings":"AAAA,SAASA,YAAY,QAAQ,gBAAe;AAE5C,OAAO,SAASC,yBACdC,cAAsB;QAmBRC;IAjBd,MAAMC,aAAaF,cACjB,+BAA+B;KAC9BG,KAAK,CAAC,KACNC,GAAG,CAAC,CAACH,YAAcA,UAAUI,IAAI;IAEpC,yEAAyE;IACzE,iCAAiC;IACjC,MAAMJ,YACJC,WAAWI,IAAI,CAAC,CAACC,MAAQA,IAAIC,UAAU,CAAC,kBACxCN,WAAWI,IAAI,CAAC,CAACC,MAAQA,IAAIC,UAAU,CAAC;IAE1C,mDAAmD;IACnD,IAAI,CAACP,WAAW;QACd;IACF;IAEA,uCAAuC;IACvC,MAAMQ,SAAQR,kCAAAA,UACXE,KAAK,CAAC,IACP,yEAAyE;KACxEO,KAAK,CAAC,GACNN,GAAG,CAAC,CAACO,SAAWA,OAAON,IAAI,GAC5B,kDAAkD;KACjDC,IAAI,CACH,CAACK,SACCA,OAAOH,UAAU,CAAC,cAClBG,OAAOC,MAAM,GAAG,KAChBD,OAAOE,QAAQ,CAAC,0BAVRZ,gCAaVS,KAAK,CAAC,GAAG,CAAC;IAEd,iDAAiD;IACjD,IAAI,CAACD,OAAO;QACV;IACF;IAEA,sEAAsE;IACtE,uEAAuE;IACvE,eAAe;IACf,IAAIX,aAAagB,IAAI,CAACL,QAAQ;QAC5B,MAAM,IAAIM,MACR;IAEJ;IAEA,OAAON;AACT"}

View File

@@ -0,0 +1,32 @@
import { INTERCEPTION_ROUTE_MARKERS } from "../future/helpers/interception-routes";
/**
* Parse dynamic route segment to type of parameter
*/ export function getSegmentParam(segment) {
const interceptionMarker = INTERCEPTION_ROUTE_MARKERS.find((marker)=>segment.startsWith(marker));
// if an interception marker is part of the path segment, we need to jump ahead
// to the relevant portion for param parsing
if (interceptionMarker) {
segment = segment.slice(interceptionMarker.length);
}
if (segment.startsWith("[[...") && segment.endsWith("]]")) {
return {
type: "optional-catchall",
param: segment.slice(5, -2)
};
}
if (segment.startsWith("[...") && segment.endsWith("]")) {
return {
type: "catchall",
param: segment.slice(4, -1)
};
}
if (segment.startsWith("[") && segment.endsWith("]")) {
return {
type: "dynamic",
param: segment.slice(1, -1)
};
}
return null;
}
//# sourceMappingURL=get-segment-param.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/get-segment-param.tsx"],"names":["INTERCEPTION_ROUTE_MARKERS","getSegmentParam","segment","interceptionMarker","find","marker","startsWith","slice","length","endsWith","type","param"],"mappings":"AAAA,SAASA,0BAA0B,QAAQ,wCAAuC;AAGlF;;CAEC,GACD,OAAO,SAASC,gBAAgBC,OAAe;IAI7C,MAAMC,qBAAqBH,2BAA2BI,IAAI,CAAC,CAACC,SAC1DH,QAAQI,UAAU,CAACD;IAGrB,+EAA+E;IAC/E,4CAA4C;IAC5C,IAAIF,oBAAoB;QACtBD,UAAUA,QAAQK,KAAK,CAACJ,mBAAmBK,MAAM;IACnD;IAEA,IAAIN,QAAQI,UAAU,CAAC,YAAYJ,QAAQO,QAAQ,CAAC,OAAO;QACzD,OAAO;YACLC,MAAM;YACNC,OAAOT,QAAQK,KAAK,CAAC,GAAG,CAAC;QAC3B;IACF;IAEA,IAAIL,QAAQI,UAAU,CAAC,WAAWJ,QAAQO,QAAQ,CAAC,MAAM;QACvD,OAAO;YACLC,MAAM;YACNC,OAAOT,QAAQK,KAAK,CAAC,GAAG,CAAC;QAC3B;IACF;IAEA,IAAIL,QAAQI,UAAU,CAAC,QAAQJ,QAAQO,QAAQ,CAAC,MAAM;QACpD,OAAO;YACLC,MAAM;YACNC,OAAOT,QAAQK,KAAK,CAAC,GAAG,CAAC;QAC3B;IACF;IAEA,OAAO;AACT"}

View File

@@ -0,0 +1,16 @@
export const dynamicParamTypes = {
catchall: "c",
"optional-catchall": "oc",
dynamic: "d"
};
/**
* Shorten the dynamic param in order to make it smaller when transmitted to the browser.
*/ export function getShortDynamicParamType(type) {
const short = dynamicParamTypes[type];
if (!short) {
throw new Error("Unknown dynamic param type");
}
return short;
}
//# sourceMappingURL=get-short-dynamic-param-type.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/get-short-dynamic-param-type.tsx"],"names":["dynamicParamTypes","catchall","dynamic","getShortDynamicParamType","type","short","Error"],"mappings":"AAEA,OAAO,MAAMA,oBAGT;IACFC,UAAU;IACV,qBAAqB;IACrBC,SAAS;AACX,EAAC;AAED;;CAEC,GACD,OAAO,SAASC,yBACdC,IAAuB;IAEvB,MAAMC,QAAQL,iBAAiB,CAACI,KAAK;IACrC,IAAI,CAACC,OAAO;QACV,MAAM,IAAIC,MAAM;IAClB;IACA,OAAOD;AACT"}

View File

@@ -0,0 +1,7 @@
/**
* Interop between "export default" and "module.exports".
*/ export function interopDefault(mod) {
return mod.default || mod;
}
//# sourceMappingURL=interop-default.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/interop-default.ts"],"names":["interopDefault","mod","default"],"mappings":"AAAA;;CAEC,GACD,OAAO,SAASA,eAAeC,GAAQ;IACrC,OAAOA,IAAIC,OAAO,IAAID;AACxB"}

View File

@@ -0,0 +1,24 @@
import { flightRouterStateSchema } from "./types";
export function parseAndValidateFlightRouterState(stateHeader) {
if (typeof stateHeader === "undefined") {
return undefined;
}
if (Array.isArray(stateHeader)) {
throw new Error("Multiple router state headers were sent. This is not allowed.");
}
// We limit the size of the router state header to ~40kb. This is to prevent
// a malicious user from sending a very large header and slowing down the
// resolving of the router state.
// This is around 2,000 nested or parallel route segment states:
// '{"children":["",{}]}'.length === 20.
if (stateHeader.length > 20 * 2000) {
throw new Error("The router state header was too large.");
}
try {
return flightRouterStateSchema.parse(JSON.parse(decodeURIComponent(stateHeader)));
} catch {
throw new Error("The router state header was sent but could not be parsed.");
}
}
//# sourceMappingURL=parse-and-validate-flight-router-state.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/parse-and-validate-flight-router-state.tsx"],"names":["flightRouterStateSchema","parseAndValidateFlightRouterState","stateHeader","undefined","Array","isArray","Error","length","parse","JSON","decodeURIComponent"],"mappings":"AACA,SAASA,uBAAuB,QAAQ,UAAS;AAEjD,OAAO,SAASC,kCACdC,WAA0C;IAE1C,IAAI,OAAOA,gBAAgB,aAAa;QACtC,OAAOC;IACT;IACA,IAAIC,MAAMC,OAAO,CAACH,cAAc;QAC9B,MAAM,IAAII,MACR;IAEJ;IAEA,4EAA4E;IAC5E,yEAAyE;IACzE,iCAAiC;IACjC,gEAAgE;IAChE,wCAAwC;IACxC,IAAIJ,YAAYK,MAAM,GAAG,KAAK,MAAM;QAClC,MAAM,IAAID,MAAM;IAClB;IAEA,IAAI;QACF,OAAON,wBAAwBQ,KAAK,CAClCC,KAAKD,KAAK,CAACE,mBAAmBR;IAElC,EAAE,OAAM;QACN,MAAM,IAAII,MAAM;IAClB;AACF"}

View File

@@ -0,0 +1,30 @@
export function preloadComponent(Component, props) {
const prev = console.error;
// Hide invalid hook call warning when calling component
console.error = function(msg) {
if (msg.startsWith("Warning: Invalid hook call.")) {
// ignore
} else {
// @ts-expect-error argument is defined
prev.apply(console, arguments);
}
};
try {
let result = Component(props);
if (result && typeof result.then === "function") {
// Catch promise rejections to prevent unhandledRejection errors
result.then(()=>{}, ()=>{});
}
return function() {
// We know what this component will render already.
return result;
};
} catch (x) {
// something suspended or errored, try again later
} finally{
console.error = prev;
}
return Component;
}
//# sourceMappingURL=preload-component.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/preload-component.ts"],"names":["preloadComponent","Component","props","prev","console","error","msg","startsWith","apply","arguments","result","then","x"],"mappings":"AAAA,OAAO,SAASA,iBAAiBC,SAAc,EAAEC,KAAU;IACzD,MAAMC,OAAOC,QAAQC,KAAK;IAC1B,wDAAwD;IACxDD,QAAQC,KAAK,GAAG,SAAUC,GAAG;QAC3B,IAAIA,IAAIC,UAAU,CAAC,gCAAgC;QACjD,SAAS;QACX,OAAO;YACL,uCAAuC;YACvCJ,KAAKK,KAAK,CAACJ,SAASK;QACtB;IACF;IACA,IAAI;QACF,IAAIC,SAAST,UAAUC;QACvB,IAAIQ,UAAU,OAAOA,OAAOC,IAAI,KAAK,YAAY;YAC/C,gEAAgE;YAChED,OAAOC,IAAI,CACT,KAAO,GACP,KAAO;QAEX;QACA,OAAO;YACL,mDAAmD;YACnD,OAAOD;QACT;IACF,EAAE,OAAOE,GAAG;IACV,kDAAkD;IACpD,SAAU;QACRR,QAAQC,KAAK,GAAGF;IAClB;IACA,OAAOF;AACT"}

View File

@@ -0,0 +1,12 @@
import { streamToString } from "../stream-utils/node-web-streams-helper";
import { AppRenderSpan } from "../lib/trace/constants";
import { getTracer } from "../lib/trace/tracer";
export async function renderToString({ ReactDOMServer, element }) {
return getTracer().trace(AppRenderSpan.renderToString, async ()=>{
const renderStream = await ReactDOMServer.renderToReadableStream(element);
await renderStream.allReady;
return streamToString(renderStream);
});
}
//# sourceMappingURL=render-to-string.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/render-to-string.tsx"],"names":["streamToString","AppRenderSpan","getTracer","renderToString","ReactDOMServer","element","trace","renderStream","renderToReadableStream","allReady"],"mappings":"AAAA,SAASA,cAAc,QAAQ,0CAAyC;AACxE,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SAASC,SAAS,QAAQ,sBAAqB;AAE/C,OAAO,eAAeC,eAAe,EACnCC,cAAc,EACdC,OAAO,EAIR;IACC,OAAOH,YAAYI,KAAK,CAACL,cAAcE,cAAc,EAAE;QACrD,MAAMI,eAAe,MAAMH,eAAeI,sBAAsB,CAACH;QACjE,MAAME,aAAaE,QAAQ;QAC3B,OAAOT,eAAeO;IACxB;AACF"}

View File

@@ -0,0 +1,52 @@
import ReactDOM from "react-dom";
export function getRequiredScripts(buildManifest, assetPrefix, SRIManifest, qs, nonce) {
let preinitScripts;
let preinitScriptCommands = [];
let bootstrapScript = "";
const files = buildManifest.rootMainFiles;
if (files.length === 0) {
throw new Error("Invariant: missing bootstrap script. This is a bug in Next.js");
}
if (SRIManifest) {
bootstrapScript = {
src: `${assetPrefix}/_next/` + files[0] + qs,
integrity: SRIManifest[files[0]]
};
for(let i = 1; i < files.length; i++){
const src = `${assetPrefix}/_next/` + files[i] + qs;
const integrity = SRIManifest[files[i]];
preinitScriptCommands.push(src, integrity);
}
preinitScripts = ()=>{
// preinitScriptCommands is a double indexed array of src/integrity pairs
for(let i = 0; i < preinitScriptCommands.length; i += 2){
ReactDOM.preinit(preinitScriptCommands[i], {
as: "script",
integrity: preinitScriptCommands[i + 1],
nonce
});
}
};
} else {
bootstrapScript = `${assetPrefix}/_next/` + files[0] + qs;
for(let i = 1; i < files.length; i++){
const src = `${assetPrefix}/_next/` + files[i] + qs;
preinitScriptCommands.push(src);
}
preinitScripts = ()=>{
// preinitScriptCommands is a singled indexed array of src values
for(let i = 0; i < preinitScriptCommands.length; i++){
ReactDOM.preinit(preinitScriptCommands[i], {
as: "script",
nonce
});
}
};
}
return [
preinitScripts,
bootstrapScript
];
}
//# sourceMappingURL=required-scripts.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/required-scripts.tsx"],"names":["ReactDOM","getRequiredScripts","buildManifest","assetPrefix","SRIManifest","qs","nonce","preinitScripts","preinitScriptCommands","bootstrapScript","files","rootMainFiles","length","Error","src","integrity","i","push","preinit","as"],"mappings":"AAEA,OAAOA,cAAc,YAAW;AAEhC,OAAO,SAASC,mBACdC,aAA4B,EAC5BC,WAAmB,EACnBC,WAA+C,EAC/CC,EAAU,EACVC,KAAyB;IAEzB,IAAIC;IACJ,IAAIC,wBAAkC,EAAE;IACxC,IAAIC,kBAA+D;IACnE,MAAMC,QAAQR,cAAcS,aAAa;IACzC,IAAID,MAAME,MAAM,KAAK,GAAG;QACtB,MAAM,IAAIC,MACR;IAEJ;IACA,IAAIT,aAAa;QACfK,kBAAkB;YAChBK,KAAK,CAAC,EAAEX,YAAY,OAAO,CAAC,GAAGO,KAAK,CAAC,EAAE,GAAGL;YAC1CU,WAAWX,WAAW,CAACM,KAAK,CAAC,EAAE,CAAC;QAClC;QACA,IAAK,IAAIM,IAAI,GAAGA,IAAIN,MAAME,MAAM,EAAEI,IAAK;YACrC,MAAMF,MAAM,CAAC,EAAEX,YAAY,OAAO,CAAC,GAAGO,KAAK,CAACM,EAAE,GAAGX;YACjD,MAAMU,YAAYX,WAAW,CAACM,KAAK,CAACM,EAAE,CAAC;YACvCR,sBAAsBS,IAAI,CAACH,KAAKC;QAClC;QACAR,iBAAiB;YACf,yEAAyE;YACzE,IAAK,IAAIS,IAAI,GAAGA,IAAIR,sBAAsBI,MAAM,EAAEI,KAAK,EAAG;gBACxDhB,SAASkB,OAAO,CAACV,qBAAqB,CAACQ,EAAE,EAAE;oBACzCG,IAAI;oBACJJ,WAAWP,qBAAqB,CAACQ,IAAI,EAAE;oBACvCV;gBACF;YACF;QACF;IACF,OAAO;QACLG,kBAAkB,CAAC,EAAEN,YAAY,OAAO,CAAC,GAAGO,KAAK,CAAC,EAAE,GAAGL;QACvD,IAAK,IAAIW,IAAI,GAAGA,IAAIN,MAAME,MAAM,EAAEI,IAAK;YACrC,MAAMF,MAAM,CAAC,EAAEX,YAAY,OAAO,CAAC,GAAGO,KAAK,CAACM,EAAE,GAAGX;YACjDG,sBAAsBS,IAAI,CAACH;QAC7B;QACAP,iBAAiB;YACf,iEAAiE;YACjE,IAAK,IAAIS,IAAI,GAAGA,IAAIR,sBAAsBI,MAAM,EAAEI,IAAK;gBACrDhB,SAASkB,OAAO,CAACV,qBAAqB,CAACQ,EAAE,EAAE;oBACzCG,IAAI;oBACJb;gBACF;YACF;QACF;IACF;IAEA,OAAO;QAACC;QAAgBE;KAAgB;AAC1C"}

View File

@@ -0,0 +1,27 @@
/*
Files in the rsc directory are meant to be packaged as part of the RSC graph using next-app-loader.
*/ import ReactDOM from "react-dom";
export function preloadStyle(href) {
ReactDOM.preload(href, {
as: "style"
});
}
export function preloadFont(href, type) {
ReactDOM.preload(href, {
as: "font",
type
});
}
export function preconnect(href, crossOrigin) {
if (typeof crossOrigin === "string") {
ReactDOM.preconnect(href, {
crossOrigin
});
} else {
ReactDOM.preconnect(href);
}
}
//# sourceMappingURL=preloads.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/app-render/rsc/preloads.ts"],"names":["ReactDOM","preloadStyle","href","preload","as","preloadFont","type","preconnect","crossOrigin"],"mappings":"AAAA;;;;AAIA,GAEA,OAAOA,cAAc,YAAW;AAEhC,OAAO,SAASC,aAAaC,IAAY;IACvCF,SAASG,OAAO,CAACD,MAAM;QAAEE,IAAI;IAAQ;AACvC;AAEA,OAAO,SAASC,YAAYH,IAAY,EAAEI,IAAY;IAClDN,SAAiBG,OAAO,CAACD,MAAM;QAAEE,IAAI;QAAQE;IAAK;AACtD;AAEA,OAAO,SAASC,WAAWL,IAAY,EAAEM,WAAoB;IAC3D,IAAI,OAAOA,gBAAgB,UAAU;QACjCR,SAAiBO,UAAU,CAACL,MAAM;YAAEM;QAAY;IACpD,OAAO;QACHR,SAAiBO,UAAU,CAACL;IAChC;AACF"}

View File

@@ -0,0 +1,24 @@
// Provider for the `useServerInsertedHTML` API to register callbacks to insert
// elements into the HTML stream.
import React from "react";
import { ServerInsertedHTMLContext } from "../../shared/lib/server-inserted-html.shared-runtime";
export function createServerInsertedHTML() {
const serverInsertedHTMLCallbacks = [];
const addInsertedHtml = (handler)=>{
serverInsertedHTMLCallbacks.push(handler);
};
return {
ServerInsertedHTMLProvider ({ children }) {
return /*#__PURE__*/ React.createElement(ServerInsertedHTMLContext.Provider, {
value: addInsertedHtml
}, children);
},
renderServerInsertedHTML () {
return serverInsertedHTMLCallbacks.map((callback, index)=>/*#__PURE__*/ React.createElement(React.Fragment, {
key: "__next_server_inserted__" + index
}, callback()));
}
};
}
//# sourceMappingURL=server-inserted-html.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/server-inserted-html.tsx"],"names":["React","ServerInsertedHTMLContext","createServerInsertedHTML","serverInsertedHTMLCallbacks","addInsertedHtml","handler","push","ServerInsertedHTMLProvider","children","Provider","value","renderServerInsertedHTML","map","callback","index","Fragment","key"],"mappings":"AAAA,+EAA+E;AAC/E,iCAAiC;AAEjC,OAAOA,WAAW,QAAO;AACzB,SAASC,yBAAyB,QAAQ,uDAAsD;AAEhG,OAAO,SAASC;IACd,MAAMC,8BAAyD,EAAE;IACjE,MAAMC,kBAAkB,CAACC;QACvBF,4BAA4BG,IAAI,CAACD;IACnC;IAEA,OAAO;QACLE,4BAA2B,EAAEC,QAAQ,EAA6B;YAChE,qBACE,oBAACP,0BAA0BQ,QAAQ;gBAACC,OAAON;eACxCI;QAGP;QACAG;YACE,OAAOR,4BAA4BS,GAAG,CAAC,CAACC,UAAUC,sBAChD,oBAACd,MAAMe,QAAQ;oBAACC,KAAK,6BAA6BF;mBAC/CD;QAGP;IACF;AACF"}

48
node_modules/next/dist/esm/server/app-render/types.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
import zod from "zod";
const dynamicParamTypesSchema = zod.enum([
"c",
"oc",
"d"
]);
const segmentSchema = zod.union([
zod.string(),
zod.tuple([
zod.string(),
zod.string(),
dynamicParamTypesSchema
])
]);
export const flightRouterStateSchema = zod.lazy(()=>{
const parallelRoutesSchema = zod.record(flightRouterStateSchema);
const urlSchema = zod.string().nullable().optional();
const refreshSchema = zod.literal("refetch").nullable().optional();
const isRootLayoutSchema = zod.boolean().optional();
// Due to the lack of optional tuple types in Zod, we need to use union here.
// https://github.com/colinhacks/zod/issues/1465
return zod.union([
zod.tuple([
segmentSchema,
parallelRoutesSchema,
urlSchema,
refreshSchema,
isRootLayoutSchema
]),
zod.tuple([
segmentSchema,
parallelRoutesSchema,
urlSchema,
refreshSchema
]),
zod.tuple([
segmentSchema,
parallelRoutesSchema,
urlSchema
]),
zod.tuple([
segmentSchema,
parallelRoutesSchema
])
]);
});
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/types.ts"],"names":["zod","dynamicParamTypesSchema","enum","segmentSchema","union","string","tuple","flightRouterStateSchema","lazy","parallelRoutesSchema","record","urlSchema","nullable","optional","refreshSchema","literal","isRootLayoutSchema","boolean"],"mappings":"AAMA,OAAOA,SAAS,MAAK;AAIrB,MAAMC,0BAA0BD,IAAIE,IAAI,CAAC;IAAC;IAAK;IAAM;CAAI;AAQzD,MAAMC,gBAAgBH,IAAII,KAAK,CAAC;IAC9BJ,IAAIK,MAAM;IACVL,IAAIM,KAAK,CAAC;QAACN,IAAIK,MAAM;QAAIL,IAAIK,MAAM;QAAIJ;KAAwB;CAChE;AAMD,OAAO,MAAMM,0BAA0DP,IAAIQ,IAAI,CAC7E;IACE,MAAMC,uBAAuBT,IAAIU,MAAM,CAACH;IACxC,MAAMI,YAAYX,IAAIK,MAAM,GAAGO,QAAQ,GAAGC,QAAQ;IAClD,MAAMC,gBAAgBd,IAAIe,OAAO,CAAC,WAAWH,QAAQ,GAAGC,QAAQ;IAChE,MAAMG,qBAAqBhB,IAAIiB,OAAO,GAAGJ,QAAQ;IAEjD,6EAA6E;IAC7E,gDAAgD;IAChD,OAAOb,IAAII,KAAK,CAAC;QACfJ,IAAIM,KAAK,CAAC;YACRH;YACAM;YACAE;YACAG;YACAE;SACD;QACDhB,IAAIM,KAAK,CAAC;YACRH;YACAM;YACAE;YACAG;SACD;QACDd,IAAIM,KAAK,CAAC;YAACH;YAAeM;YAAsBE;SAAU;QAC1DX,IAAIM,KAAK,CAAC;YAACH;YAAeM;SAAqB;KAChD;AACH,GACD"}

View File

@@ -0,0 +1,59 @@
import { encodeText, decodeText } from "../stream-utils/encode-decode";
import { htmlEscapeJsonString } from "../htmlescape";
const isEdgeRuntime = process.env.NEXT_RUNTIME === "edge";
/**
* Render Flight stream.
* This is only used for renderToHTML, the Flight response does not need additional wrappers.
*/ export function useFlightResponse(writable, req, clientReferenceManifest, rscChunks, flightResponseRef, nonce) {
if (flightResponseRef.current !== null) {
return flightResponseRef.current;
}
// react-server-dom-webpack/client.edge must not be hoisted for require cache clearing to work correctly
const { createFromReadableStream } = require(`react-server-dom-webpack/client.edge`);
const [renderStream, forwardStream] = req.tee();
const res = createFromReadableStream(renderStream, {
moduleMap: isEdgeRuntime ? clientReferenceManifest.edgeSSRModuleMapping : clientReferenceManifest.ssrModuleMapping
});
flightResponseRef.current = res;
let bootstrapped = false;
// We only attach CSS chunks to the inlined data.
const forwardReader = forwardStream.getReader();
const writer = writable.getWriter();
const startScriptTag = nonce ? `<script nonce=${JSON.stringify(nonce)}>` : "<script>";
const textDecoder = new TextDecoder();
function read() {
forwardReader.read().then(({ done, value })=>{
if (value) {
rscChunks.push(value);
}
if (!bootstrapped) {
bootstrapped = true;
writer.write(encodeText(`${startScriptTag}(self.__next_f=self.__next_f||[]).push(${htmlEscapeJsonString(JSON.stringify([
0
]))})</script>`));
}
if (done) {
// Add a setTimeout here because the error component is too small, the first forwardReader.read() read will return the full chunk
// and then it immediately set flightResponseRef.current as null.
// react renders the component twice, the second render will run into the state with useFlightResponse where flightResponseRef.current is null,
// so it tries to render the flight payload again
setTimeout(()=>{
flightResponseRef.current = null;
});
writer.close();
} else {
const responsePartial = decodeText(value, textDecoder);
const scripts = `${startScriptTag}self.__next_f.push(${htmlEscapeJsonString(JSON.stringify([
1,
responsePartial
]))})</script>`;
writer.write(encodeText(scripts));
read();
}
});
}
read();
return res;
}
//# sourceMappingURL=use-flight-response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/use-flight-response.tsx"],"names":["encodeText","decodeText","htmlEscapeJsonString","isEdgeRuntime","process","env","NEXT_RUNTIME","useFlightResponse","writable","req","clientReferenceManifest","rscChunks","flightResponseRef","nonce","current","createFromReadableStream","require","renderStream","forwardStream","tee","res","moduleMap","edgeSSRModuleMapping","ssrModuleMapping","bootstrapped","forwardReader","getReader","writer","getWriter","startScriptTag","JSON","stringify","textDecoder","TextDecoder","read","then","done","value","push","write","setTimeout","close","responsePartial","scripts"],"mappings":"AAEA,SAASA,UAAU,EAAEC,UAAU,QAAQ,gCAA+B;AACtE,SAASC,oBAAoB,QAAQ,gBAAe;AAEpD,MAAMC,gBAAgBC,QAAQC,GAAG,CAACC,YAAY,KAAK;AAEnD;;;CAGC,GACD,OAAO,SAASC,kBACdC,QAAoC,EACpCC,GAA+B,EAC/BC,uBAAgD,EAChDC,SAAuB,EACvBC,iBAAoC,EACpCC,KAAc;IAEd,IAAID,kBAAkBE,OAAO,KAAK,MAAM;QACtC,OAAOF,kBAAkBE,OAAO;IAClC;IACA,wGAAwG;IACxG,MAAM,EACJC,wBAAwB,EACzB,GAAGC,QAAQ,CAAC,oCAAoC,CAAC;IAElD,MAAM,CAACC,cAAcC,cAAc,GAAGT,IAAIU,GAAG;IAC7C,MAAMC,MAAML,yBAAyBE,cAAc;QACjDI,WAAWlB,gBACPO,wBAAwBY,oBAAoB,GAC5CZ,wBAAwBa,gBAAgB;IAC9C;IACAX,kBAAkBE,OAAO,GAAGM;IAE5B,IAAII,eAAe;IACnB,iDAAiD;IACjD,MAAMC,gBAAgBP,cAAcQ,SAAS;IAC7C,MAAMC,SAASnB,SAASoB,SAAS;IACjC,MAAMC,iBAAiBhB,QACnB,CAAC,cAAc,EAAEiB,KAAKC,SAAS,CAAClB,OAAO,CAAC,CAAC,GACzC;IACJ,MAAMmB,cAAc,IAAIC;IAExB,SAASC;QACPT,cAAcS,IAAI,GAAGC,IAAI,CAAC,CAAC,EAAEC,IAAI,EAAEC,KAAK,EAAE;YACxC,IAAIA,OAAO;gBACT1B,UAAU2B,IAAI,CAACD;YACjB;YAEA,IAAI,CAACb,cAAc;gBACjBA,eAAe;gBACfG,OAAOY,KAAK,CACVvC,WACE,CAAC,EAAE6B,eAAe,uCAAuC,EAAE3B,qBACzD4B,KAAKC,SAAS,CAAC;oBAAC;iBAAE,GAClB,UAAU,CAAC;YAGnB;YACA,IAAIK,MAAM;gBACR,iIAAiI;gBACjI,iEAAiE;gBACjE,+IAA+I;gBAC/I,iDAAiD;gBACjDI,WAAW;oBACT5B,kBAAkBE,OAAO,GAAG;gBAC9B;gBACAa,OAAOc,KAAK;YACd,OAAO;gBACL,MAAMC,kBAAkBzC,WAAWoC,OAAOL;gBAC1C,MAAMW,UAAU,CAAC,EAAEd,eAAe,mBAAmB,EAAE3B,qBACrD4B,KAAKC,SAAS,CAAC;oBAAC;oBAAGW;iBAAgB,GACnC,UAAU,CAAC;gBAEbf,OAAOY,KAAK,CAACvC,WAAW2C;gBACxBT;YACF;QACF;IACF;IACAA;IAEA,OAAOd;AACT"}

View File

@@ -0,0 +1,19 @@
const DUMMY_ORIGIN = "http://n";
const INVALID_URL_MESSAGE = "Invalid request URL";
export function validateURL(url) {
if (!url) {
throw new Error(INVALID_URL_MESSAGE);
}
try {
const parsed = new URL(url, DUMMY_ORIGIN);
// Avoid origin change by extra slashes in pathname
if (parsed.origin !== DUMMY_ORIGIN) {
throw new Error(INVALID_URL_MESSAGE);
}
return url;
} catch {
throw new Error(INVALID_URL_MESSAGE);
}
}
//# sourceMappingURL=validate-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/app-render/validate-url.tsx"],"names":["DUMMY_ORIGIN","INVALID_URL_MESSAGE","validateURL","url","Error","parsed","URL","origin"],"mappings":"AAAA,MAAMA,eAAe;AACrB,MAAMC,sBAAsB;AAE5B,OAAO,SAASC,YAAYC,GAAuB;IACjD,IAAI,CAACA,KAAK;QACR,MAAM,IAAIC,MAAMH;IAClB;IACA,IAAI;QACF,MAAMI,SAAS,IAAIC,IAAIH,KAAKH;QAC5B,mDAAmD;QACnD,IAAIK,OAAOE,MAAM,KAAKP,cAAc;YAClC,MAAM,IAAII,MAAMH;QAClB;QACA,OAAOE;IACT,EAAE,OAAM;QACN,MAAM,IAAIC,MAAMH;IAClB;AACF"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/async-storage/async-storage-wrapper.ts"],"names":[],"mappings":"AAAA,WAoBC"}

View File

@@ -0,0 +1,42 @@
import { COOKIE_NAME_PRERENDER_BYPASS, checkIsOnDemandRevalidate } from "../api-utils";
export class DraftModeProvider {
constructor(previewProps, req, cookies, mutableCookies){
var _cookies_get;
// The logic for draftMode() is very similar to tryGetPreviewData()
// but Draft Mode does not have any data associated with it.
const isOnDemandRevalidate = previewProps && checkIsOnDemandRevalidate(req, previewProps).isOnDemandRevalidate;
const cookieValue = (_cookies_get = cookies.get(COOKIE_NAME_PRERENDER_BYPASS)) == null ? void 0 : _cookies_get.value;
this.isEnabled = Boolean(!isOnDemandRevalidate && cookieValue && previewProps && cookieValue === previewProps.previewModeId);
this._previewModeId = previewProps == null ? void 0 : previewProps.previewModeId;
this._mutableCookies = mutableCookies;
}
enable() {
if (!this._previewModeId) {
throw new Error("Invariant: previewProps missing previewModeId this should never happen");
}
this._mutableCookies.set({
name: COOKIE_NAME_PRERENDER_BYPASS,
value: this._previewModeId,
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/"
});
}
disable() {
// To delete a cookie, set `expires` to a date in the past:
// https://tools.ietf.org/html/rfc6265#section-4.1.1
// `Max-Age: 0` is not valid, thus ignored, and the cookie is persisted.
this._mutableCookies.set({
name: COOKIE_NAME_PRERENDER_BYPASS,
value: "",
httpOnly: true,
sameSite: process.env.NODE_ENV !== "development" ? "none" : "lax",
secure: process.env.NODE_ENV !== "development",
path: "/",
expires: new Date(0)
});
}
}
//# sourceMappingURL=draft-mode-provider.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/async-storage/draft-mode-provider.ts"],"names":["COOKIE_NAME_PRERENDER_BYPASS","checkIsOnDemandRevalidate","DraftModeProvider","constructor","previewProps","req","cookies","mutableCookies","isOnDemandRevalidate","cookieValue","get","value","isEnabled","Boolean","previewModeId","_previewModeId","_mutableCookies","enable","Error","set","name","httpOnly","sameSite","process","env","NODE_ENV","secure","path","disable","expires","Date"],"mappings":"AAMA,SACEA,4BAA4B,EAC5BC,yBAAyB,QAEpB,eAAc;AAErB,OAAO,MAAMC;IAaXC,YACEC,YAA2C,EAC3CC,GAA6D,EAC7DC,OAA+B,EAC/BC,cAA+B,CAC/B;YAOoBD;QANpB,mEAAmE;QACnE,4DAA4D;QAC5D,MAAME,uBACJJ,gBACAH,0BAA0BI,KAAKD,cAAcI,oBAAoB;QAEnE,MAAMC,eAAcH,eAAAA,QAAQI,GAAG,CAACV,kDAAZM,aAA2CK,KAAK;QAEpE,IAAI,CAACC,SAAS,GAAGC,QACf,CAACL,wBACCC,eACAL,gBACAK,gBAAgBL,aAAaU,aAAa;QAG9C,IAAI,CAACC,cAAc,GAAGX,gCAAAA,aAAcU,aAAa;QACjD,IAAI,CAACE,eAAe,GAAGT;IACzB;IAEAU,SAAS;QACP,IAAI,CAAC,IAAI,CAACF,cAAc,EAAE;YACxB,MAAM,IAAIG,MACR;QAEJ;QAEA,IAAI,CAACF,eAAe,CAACG,GAAG,CAAC;YACvBC,MAAMpB;YACNW,OAAO,IAAI,CAACI,cAAc;YAC1BM,UAAU;YACVC,UAAUC,QAAQC,GAAG,CAACC,QAAQ,KAAK,gBAAgB,SAAS;YAC5DC,QAAQH,QAAQC,GAAG,CAACC,QAAQ,KAAK;YACjCE,MAAM;QACR;IACF;IAEAC,UAAU;QACR,2DAA2D;QAC3D,oDAAoD;QACpD,wEAAwE;QACxE,IAAI,CAACZ,eAAe,CAACG,GAAG,CAAC;YACvBC,MAAMpB;YACNW,OAAO;YACPU,UAAU;YACVC,UAAUC,QAAQC,GAAG,CAACC,QAAQ,KAAK,gBAAgB,SAAS;YAC5DC,QAAQH,QAAQC,GAAG,CAACC,QAAQ,KAAK;YACjCE,MAAM;YACNE,SAAS,IAAIC,KAAK;QACpB;IACF;AACF"}

View File

@@ -0,0 +1,76 @@
import { FLIGHT_PARAMETERS } from "../../client/components/app-router-headers";
import { HeadersAdapter } from "../web/spec-extension/adapters/headers";
import { MutableRequestCookiesAdapter, RequestCookiesAdapter } from "../web/spec-extension/adapters/request-cookies";
import { RequestCookies } from "../web/spec-extension/cookies";
import { DraftModeProvider } from "./draft-mode-provider";
function getHeaders(headers) {
const cleaned = HeadersAdapter.from(headers);
for (const param of FLIGHT_PARAMETERS){
cleaned.delete(param.toString().toLowerCase());
}
return HeadersAdapter.seal(cleaned);
}
function getCookies(headers) {
const cookies = new RequestCookies(HeadersAdapter.from(headers));
return RequestCookiesAdapter.seal(cookies);
}
function getMutableCookies(headers, onUpdateCookies) {
const cookies = new RequestCookies(HeadersAdapter.from(headers));
return MutableRequestCookiesAdapter.wrap(cookies, onUpdateCookies);
}
export const RequestAsyncStorageWrapper = {
/**
* Wrap the callback with the given store so it can access the underlying
* store using hooks.
*
* @param storage underlying storage object returned by the module
* @param context context to seed the store
* @param callback function to call within the scope of the context
* @returns the result returned by the callback
*/ wrap (storage, { req, res, renderOpts }, callback) {
let previewProps = undefined;
if (renderOpts && "previewProps" in renderOpts) {
// TODO: investigate why previewProps isn't on RenderOpts
previewProps = renderOpts.previewProps;
}
function defaultOnUpdateCookies(cookies) {
if (res) {
res.setHeader("Set-Cookie", cookies);
}
}
const cache = {};
const store = {
get headers () {
if (!cache.headers) {
// Seal the headers object that'll freeze out any methods that could
// mutate the underlying data.
cache.headers = getHeaders(req.headers);
}
return cache.headers;
},
get cookies () {
if (!cache.cookies) {
// Seal the cookies object that'll freeze out any methods that could
// mutate the underlying data.
cache.cookies = getCookies(req.headers);
}
return cache.cookies;
},
get mutableCookies () {
if (!cache.mutableCookies) {
cache.mutableCookies = getMutableCookies(req.headers, (renderOpts == null ? void 0 : renderOpts.onUpdateCookies) || (res ? defaultOnUpdateCookies : undefined));
}
return cache.mutableCookies;
},
get draftMode () {
if (!cache.draftMode) {
cache.draftMode = new DraftModeProvider(previewProps, req, this.cookies, this.mutableCookies);
}
return cache.draftMode;
}
};
return storage.run(store, callback, store);
}
};
//# sourceMappingURL=request-async-storage-wrapper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/async-storage/request-async-storage-wrapper.ts"],"names":["FLIGHT_PARAMETERS","HeadersAdapter","MutableRequestCookiesAdapter","RequestCookiesAdapter","RequestCookies","DraftModeProvider","getHeaders","headers","cleaned","from","param","delete","toString","toLowerCase","seal","getCookies","cookies","getMutableCookies","onUpdateCookies","wrap","RequestAsyncStorageWrapper","storage","req","res","renderOpts","callback","previewProps","undefined","defaultOnUpdateCookies","setHeader","cache","store","mutableCookies","draftMode","run"],"mappings":"AAQA,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SACEC,cAAc,QAET,yCAAwC;AAC/C,SACEC,4BAA4B,EAC5BC,qBAAqB,QAEhB,iDAAgD;AACvD,SAASC,cAAc,QAAyB,gCAA+B;AAE/E,SAASC,iBAAiB,QAAQ,wBAAuB;AAEzD,SAASC,WAAWC,OAAsC;IACxD,MAAMC,UAAUP,eAAeQ,IAAI,CAACF;IACpC,KAAK,MAAMG,SAASV,kBAAmB;QACrCQ,QAAQG,MAAM,CAACD,MAAME,QAAQ,GAAGC,WAAW;IAC7C;IAEA,OAAOZ,eAAea,IAAI,CAACN;AAC7B;AAEA,SAASO,WACPR,OAAsC;IAEtC,MAAMS,UAAU,IAAIZ,eAAeH,eAAeQ,IAAI,CAACF;IACvD,OAAOJ,sBAAsBW,IAAI,CAACE;AACpC;AAEA,SAASC,kBACPV,OAAsC,EACtCW,eAA6C;IAE7C,MAAMF,UAAU,IAAIZ,eAAeH,eAAeQ,IAAI,CAACF;IACvD,OAAOL,6BAA6BiB,IAAI,CAACH,SAASE;AACpD;AAQA,OAAO,MAAME,6BAGT;IACF;;;;;;;;GAQC,GACDD,MACEE,OAAwC,EACxC,EAAEC,GAAG,EAAEC,GAAG,EAAEC,UAAU,EAAkB,EACxCC,QAAyC;QAEzC,IAAIC,eAA8CC;QAElD,IAAIH,cAAc,kBAAkBA,YAAY;YAC9C,yDAAyD;YACzDE,eAAe,AAACF,WAAmBE,YAAY;QACjD;QAEA,SAASE,uBAAuBZ,OAAiB;YAC/C,IAAIO,KAAK;gBACPA,IAAIM,SAAS,CAAC,cAAcb;YAC9B;QACF;QAEA,MAAMc,QAKF,CAAC;QAEL,MAAMC,QAAsB;YAC1B,IAAIxB,WAAU;gBACZ,IAAI,CAACuB,MAAMvB,OAAO,EAAE;oBAClB,oEAAoE;oBACpE,8BAA8B;oBAC9BuB,MAAMvB,OAAO,GAAGD,WAAWgB,IAAIf,OAAO;gBACxC;gBAEA,OAAOuB,MAAMvB,OAAO;YACtB;YACA,IAAIS,WAAU;gBACZ,IAAI,CAACc,MAAMd,OAAO,EAAE;oBAClB,oEAAoE;oBACpE,8BAA8B;oBAC9Bc,MAAMd,OAAO,GAAGD,WAAWO,IAAIf,OAAO;gBACxC;gBAEA,OAAOuB,MAAMd,OAAO;YACtB;YACA,IAAIgB,kBAAiB;gBACnB,IAAI,CAACF,MAAME,cAAc,EAAE;oBACzBF,MAAME,cAAc,GAAGf,kBACrBK,IAAIf,OAAO,EACXiB,CAAAA,8BAAAA,WAAYN,eAAe,KACxBK,CAAAA,MAAMK,yBAAyBD,SAAQ;gBAE9C;gBACA,OAAOG,MAAME,cAAc;YAC7B;YACA,IAAIC,aAAY;gBACd,IAAI,CAACH,MAAMG,SAAS,EAAE;oBACpBH,MAAMG,SAAS,GAAG,IAAI5B,kBACpBqB,cACAJ,KACA,IAAI,CAACN,OAAO,EACZ,IAAI,CAACgB,cAAc;gBAEvB;gBAEA,OAAOF,MAAMG,SAAS;YACxB;QACF;QAEA,OAAOZ,QAAQa,GAAG,CAACH,OAAON,UAAUM;IACtC;AACF,EAAC"}

View File

@@ -0,0 +1,39 @@
export const StaticGenerationAsyncStorageWrapper = {
wrap (storage, { urlPathname, renderOpts }, callback) {
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* 3.) If the request is in draft mode, we must generate dynamic HTML.
*
* 4.) If the request is a server action, we must generate dynamic HTML.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/ const isStaticGeneration = !renderOpts.supportsDynamicHTML && !renderOpts.isDraftMode && !renderOpts.isServerAction;
const store = {
isStaticGeneration,
urlPathname,
pagePath: renderOpts.originalPathname,
incrementalCache: // we fallback to a global incremental cache for edge-runtime locally
// so that it can access the fs cache without mocks
renderOpts.incrementalCache || globalThis.__incrementalCache,
isRevalidate: renderOpts.isRevalidate,
isPrerendering: renderOpts.nextExport,
fetchCache: renderOpts.fetchCache,
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
isDraftMode: renderOpts.isDraftMode
};
// TODO: remove this when we resolve accessing the store outside the execution context
renderOpts.store = store;
return storage.run(store, callback, store);
}
};
//# sourceMappingURL=static-generation-async-storage-wrapper.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/async-storage/static-generation-async-storage-wrapper.ts"],"names":["StaticGenerationAsyncStorageWrapper","wrap","storage","urlPathname","renderOpts","callback","isStaticGeneration","supportsDynamicHTML","isDraftMode","isServerAction","store","pagePath","originalPathname","incrementalCache","globalThis","__incrementalCache","isRevalidate","isPrerendering","nextExport","fetchCache","isOnDemandRevalidate","run"],"mappings":"AA+BA,OAAO,MAAMA,sCAGT;IACFC,MACEC,OAAiD,EACjD,EAAEC,WAAW,EAAEC,UAAU,EAA2B,EACpDC,QAAkD;QAElD;;;;;;;;;;;;;;;;KAgBC,GACD,MAAMC,qBACJ,CAACF,WAAWG,mBAAmB,IAC/B,CAACH,WAAWI,WAAW,IACvB,CAACJ,WAAWK,cAAc;QAE5B,MAAMC,QAA+B;YACnCJ;YACAH;YACAQ,UAAUP,WAAWQ,gBAAgB;YACrCC,kBACE,qEAAqE;YACrE,mDAAmD;YACnDT,WAAWS,gBAAgB,IAAI,AAACC,WAAmBC,kBAAkB;YACvEC,cAAcZ,WAAWY,YAAY;YACrCC,gBAAgBb,WAAWc,UAAU;YACrCC,YAAYf,WAAWe,UAAU;YACjCC,sBAAsBhB,WAAWgB,oBAAoB;YAErDZ,aAAaJ,WAAWI,WAAW;QACrC;QAEA,sFAAsF;QACtFJ,WAAWM,KAAK,GAAGA;QAEnB,OAAOR,QAAQmB,GAAG,CAACX,OAAOL,UAAUK;IACtC;AACF,EAAC"}

32
node_modules/next/dist/esm/server/base-http/index.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import { PERMANENT_REDIRECT_STATUS } from "../../shared/lib/constants";
import { getCookieParser } from "../api-utils/get-cookie-parser";
export class BaseNextRequest {
constructor(method, url, body){
this.method = method;
this.url = url;
this.body = body;
}
// Utils implemented using the abstract methods above
get cookies() {
if (this._cookies) return this._cookies;
return this._cookies = getCookieParser(this.headers)();
}
}
export class BaseNextResponse {
constructor(destination){
this.destination = destination;
}
// Utils implemented using the abstract methods above
redirect(destination, statusCode) {
this.setHeader("Location", destination);
this.statusCode = statusCode;
// Since IE11 doesn't support the 308 header add backwards
// compatibility using refresh header
if (statusCode === PERMANENT_REDIRECT_STATUS) {
this.setHeader("Refresh", `0;url=${destination}`);
}
return this;
}
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/base-http/index.ts"],"names":["PERMANENT_REDIRECT_STATUS","getCookieParser","BaseNextRequest","constructor","method","url","body","cookies","_cookies","headers","BaseNextResponse","destination","redirect","statusCode","setHeader"],"mappings":"AAGA,SAASA,yBAAyB,QAAQ,6BAA4B;AAEtE,SAASC,eAAe,QAAQ,iCAAgC;AAQhE,OAAO,MAAeC;IAIpBC,YAAmBC,QAAuBC,KAAoBC,KAAY;sBAAvDF;mBAAuBC;oBAAoBC;IAAa;IAI3E,qDAAqD;IAErD,IAAWC,UAAU;QACnB,IAAI,IAAI,CAACC,QAAQ,EAAE,OAAO,IAAI,CAACA,QAAQ;QACvC,OAAQ,IAAI,CAACA,QAAQ,GAAGP,gBAAgB,IAAI,CAACQ,OAAO;IACtD;AACF;AAEA,OAAO,MAAeC;IAKpBP,YAAmBQ,YAA0B;2BAA1BA;IAA2B;IAmC9C,qDAAqD;IAErDC,SAASD,WAAmB,EAAEE,UAAkB,EAAE;QAChD,IAAI,CAACC,SAAS,CAAC,YAAYH;QAC3B,IAAI,CAACE,UAAU,GAAGA;QAElB,0DAA0D;QAC1D,qCAAqC;QACrC,IAAIA,eAAeb,2BAA2B;YAC5C,IAAI,CAACc,SAAS,CAAC,WAAW,CAAC,MAAM,EAAEH,YAAY,CAAC;QAClD;QACA,OAAO,IAAI;IACb;AACF"}

99
node_modules/next/dist/esm/server/base-http/node.js generated vendored Normal file
View File

@@ -0,0 +1,99 @@
import { SYMBOL_CLEARED_COOKIES } from "../api-utils";
import { parseBody } from "../api-utils/node";
import { NEXT_REQUEST_META } from "../request-meta";
import { BaseNextRequest, BaseNextResponse } from "./index";
let _NEXT_REQUEST_META = NEXT_REQUEST_META;
export class NodeNextRequest extends BaseNextRequest {
get originalRequest() {
// Need to mimic these changes to the original req object for places where we use it:
// render.tsx, api/ssg requests
this._req[NEXT_REQUEST_META] = this[NEXT_REQUEST_META];
this._req.url = this.url;
this._req.cookies = this.cookies;
return this._req;
}
set originalRequest(value) {
this._req = value;
}
constructor(_req){
super(_req.method.toUpperCase(), _req.url, _req);
this._req = _req;
this.headers = this._req.headers;
this[_NEXT_REQUEST_META] = this._req[NEXT_REQUEST_META] || {};
}
async parseBody(limit) {
return parseBody(this._req, limit);
}
}
export class NodeNextResponse extends BaseNextResponse {
get originalResponse() {
if (SYMBOL_CLEARED_COOKIES in this) {
this._res[SYMBOL_CLEARED_COOKIES] = this[SYMBOL_CLEARED_COOKIES];
}
return this._res;
}
constructor(_res){
super(_res);
this._res = _res;
this.textBody = undefined;
}
get sent() {
return this._res.finished || this._res.headersSent;
}
get statusCode() {
return this._res.statusCode;
}
set statusCode(value) {
this._res.statusCode = value;
}
get statusMessage() {
return this._res.statusMessage;
}
set statusMessage(value) {
this._res.statusMessage = value;
}
setHeader(name, value) {
this._res.setHeader(name, value);
return this;
}
removeHeader(name) {
this._res.removeHeader(name);
return this;
}
getHeaderValues(name) {
const values = this._res.getHeader(name);
if (values === undefined) return undefined;
return (Array.isArray(values) ? values : [
values
]).map((value)=>value.toString());
}
hasHeader(name) {
return this._res.hasHeader(name);
}
getHeader(name) {
const values = this.getHeaderValues(name);
return Array.isArray(values) ? values.join(",") : undefined;
}
getHeaders() {
return this._res.getHeaders();
}
appendHeader(name, value) {
const currentValues = this.getHeaderValues(name) ?? [];
if (!currentValues.includes(value)) {
this._res.setHeader(name, [
...currentValues,
value
]);
}
return this;
}
body(value) {
this.textBody = value;
return this;
}
send() {
this._res.end(this.textBody);
}
}
//# sourceMappingURL=node.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/base-http/node.ts"],"names":["SYMBOL_CLEARED_COOKIES","parseBody","NEXT_REQUEST_META","BaseNextRequest","BaseNextResponse","NodeNextRequest","originalRequest","_req","url","cookies","value","constructor","method","toUpperCase","headers","limit","NodeNextResponse","originalResponse","_res","textBody","undefined","sent","finished","headersSent","statusCode","statusMessage","setHeader","name","removeHeader","getHeaderValues","values","getHeader","Array","isArray","map","toString","hasHeader","join","getHeaders","appendHeader","currentValues","includes","body","send","end"],"mappings":"AAIA,SAAgCA,sBAAsB,QAAQ,eAAc;AAC5E,SAASC,SAAS,QAAQ,oBAAmB;AAC7C,SAASC,iBAAiB,QAAqB,kBAAiB;AAEhE,SAASC,eAAe,EAAEC,gBAAgB,QAAQ,UAAS;IAWxDF,qBAAAA;AAHH,OAAO,MAAMG,wBAAwBF;IAKnC,IAAIG,kBAAkB;QACpB,qFAAqF;QACrF,+BAA+B;QAC/B,IAAI,CAACC,IAAI,CAACL,kBAAkB,GAAG,IAAI,CAACA,kBAAkB;QACtD,IAAI,CAACK,IAAI,CAACC,GAAG,GAAG,IAAI,CAACA,GAAG;QACxB,IAAI,CAACD,IAAI,CAACE,OAAO,GAAG,IAAI,CAACA,OAAO;QAChC,OAAO,IAAI,CAACF,IAAI;IAClB;IAEA,IAAID,gBAAgBI,KAAU,EAAE;QAC9B,IAAI,CAACH,IAAI,GAAGG;IACd;IAEAC,YAAoBJ,KAAW;QAC7B,KAAK,CAACA,KAAKK,MAAM,CAAEC,WAAW,IAAIN,KAAKC,GAAG,EAAGD;oBAD3BA;aAjBbO,UAAU,IAAI,CAACP,IAAI,CAACO,OAAO;YAElC,CAACZ,mBAAkB,GAAgB,IAAI,CAACK,IAAI,CAACL,kBAAkB,IAAI,CAAC;IAiBpE;IAEA,MAAMD,UAAUc,KAAgB,EAAgB;QAC9C,OAAOd,UAAU,IAAI,CAACM,IAAI,EAAEQ;IAC9B;AACF;AAEA,OAAO,MAAMC,yBAAyBZ;IAKpC,IAAIa,mBAAmB;QACrB,IAAIjB,0BAA0B,IAAI,EAAE;YAClC,IAAI,CAACkB,IAAI,CAAClB,uBAAuB,GAAG,IAAI,CAACA,uBAAuB;QAClE;QAEA,OAAO,IAAI,CAACkB,IAAI;IAClB;IAEAP,YACUO,KACR;QACA,KAAK,CAACA;oBAFEA;aAbFC,WAA+BC;IAgBvC;IAEA,IAAIC,OAAO;QACT,OAAO,IAAI,CAACH,IAAI,CAACI,QAAQ,IAAI,IAAI,CAACJ,IAAI,CAACK,WAAW;IACpD;IAEA,IAAIC,aAAa;QACf,OAAO,IAAI,CAACN,IAAI,CAACM,UAAU;IAC7B;IAEA,IAAIA,WAAWd,KAAa,EAAE;QAC5B,IAAI,CAACQ,IAAI,CAACM,UAAU,GAAGd;IACzB;IAEA,IAAIe,gBAAgB;QAClB,OAAO,IAAI,CAACP,IAAI,CAACO,aAAa;IAChC;IAEA,IAAIA,cAAcf,KAAa,EAAE;QAC/B,IAAI,CAACQ,IAAI,CAACO,aAAa,GAAGf;IAC5B;IAEAgB,UAAUC,IAAY,EAAEjB,KAAwB,EAAQ;QACtD,IAAI,CAACQ,IAAI,CAACQ,SAAS,CAACC,MAAMjB;QAC1B,OAAO,IAAI;IACb;IAEAkB,aAAaD,IAAY,EAAQ;QAC/B,IAAI,CAACT,IAAI,CAACU,YAAY,CAACD;QACvB,OAAO,IAAI;IACb;IAEAE,gBAAgBF,IAAY,EAAwB;QAClD,MAAMG,SAAS,IAAI,CAACZ,IAAI,CAACa,SAAS,CAACJ;QAEnC,IAAIG,WAAWV,WAAW,OAAOA;QAEjC,OAAO,AAACY,CAAAA,MAAMC,OAAO,CAACH,UAAUA,SAAS;YAACA;SAAO,AAAD,EAAGI,GAAG,CAAC,CAACxB,QACtDA,MAAMyB,QAAQ;IAElB;IAEAC,UAAUT,IAAY,EAAW;QAC/B,OAAO,IAAI,CAACT,IAAI,CAACkB,SAAS,CAACT;IAC7B;IAEAI,UAAUJ,IAAY,EAAsB;QAC1C,MAAMG,SAAS,IAAI,CAACD,eAAe,CAACF;QACpC,OAAOK,MAAMC,OAAO,CAACH,UAAUA,OAAOO,IAAI,CAAC,OAAOjB;IACpD;IAEAkB,aAAkC;QAChC,OAAO,IAAI,CAACpB,IAAI,CAACoB,UAAU;IAC7B;IAEAC,aAAaZ,IAAY,EAAEjB,KAAa,EAAQ;QAC9C,MAAM8B,gBAAgB,IAAI,CAACX,eAAe,CAACF,SAAS,EAAE;QAEtD,IAAI,CAACa,cAAcC,QAAQ,CAAC/B,QAAQ;YAClC,IAAI,CAACQ,IAAI,CAACQ,SAAS,CAACC,MAAM;mBAAIa;gBAAe9B;aAAM;QACrD;QAEA,OAAO,IAAI;IACb;IAEAgC,KAAKhC,KAAa,EAAE;QAClB,IAAI,CAACS,QAAQ,GAAGT;QAChB,OAAO,IAAI;IACb;IAEAiC,OAAO;QACL,IAAI,CAACzB,IAAI,CAAC0B,GAAG,CAAC,IAAI,CAACzB,QAAQ;IAC7B;AACF"}

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

@@ -0,0 +1,83 @@
import { toNodeOutgoingHttpHeaders } from "../web/utils";
import { BaseNextRequest, BaseNextResponse } from "./index";
export class WebNextRequest extends BaseNextRequest {
constructor(request){
const url = new URL(request.url);
super(request.method, url.href.slice(url.origin.length), request.clone().body);
this.request = request;
this.headers = {};
for (const [name, value] of request.headers.entries()){
this.headers[name] = value;
}
}
async parseBody(_limit) {
throw new Error("parseBody is not implemented in the web runtime");
}
}
export class WebNextResponse extends BaseNextResponse {
get sent() {
return this._sent;
}
constructor(transformStream = new TransformStream()){
super(transformStream.writable);
this.transformStream = transformStream;
this.headers = new Headers();
this.textBody = undefined;
this._sent = false;
this.sendPromise = new Promise((resolve)=>{
this.sendResolve = resolve;
});
this.response = this.sendPromise.then(()=>{
return new Response(this.textBody ?? this.transformStream.readable, {
headers: this.headers,
status: this.statusCode,
statusText: this.statusMessage
});
});
}
setHeader(name, value) {
this.headers.delete(name);
for (const val of Array.isArray(value) ? value : [
value
]){
this.headers.append(name, val);
}
return this;
}
removeHeader(name) {
this.headers.delete(name);
return this;
}
getHeaderValues(name) {
var _this_getHeader;
// https://developer.mozilla.org/docs/Web/API/Headers/get#example
return (_this_getHeader = this.getHeader(name)) == null ? void 0 : _this_getHeader.split(",").map((v)=>v.trimStart());
}
getHeader(name) {
return this.headers.get(name) ?? undefined;
}
getHeaders() {
return toNodeOutgoingHttpHeaders(this.headers);
}
hasHeader(name) {
return this.headers.has(name);
}
appendHeader(name, value) {
this.headers.append(name, value);
return this;
}
body(value) {
this.textBody = value;
return this;
}
send() {
var _this_sendResolve, _this;
(_this_sendResolve = (_this = this).sendResolve) == null ? void 0 : _this_sendResolve.call(_this);
this._sent = true;
}
toResponse() {
return this.response;
}
}
//# sourceMappingURL=web.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/base-http/web.ts"],"names":["toNodeOutgoingHttpHeaders","BaseNextRequest","BaseNextResponse","WebNextRequest","constructor","request","url","URL","method","href","slice","origin","length","clone","body","headers","name","value","entries","parseBody","_limit","Error","WebNextResponse","sent","_sent","transformStream","TransformStream","writable","Headers","textBody","undefined","sendPromise","Promise","resolve","sendResolve","response","then","Response","readable","status","statusCode","statusText","statusMessage","setHeader","delete","val","Array","isArray","append","removeHeader","getHeaderValues","getHeader","split","map","v","trimStart","get","getHeaders","hasHeader","has","appendHeader","send","toResponse"],"mappings":"AACA,SAASA,yBAAyB,QAAQ,eAAc;AAExD,SAASC,eAAe,EAAEC,gBAAgB,QAAQ,UAAS;AAE3D,OAAO,MAAMC,uBAAuBF;IAIlCG,YAAYC,OAAgB,CAAE;QAC5B,MAAMC,MAAM,IAAIC,IAAIF,QAAQC,GAAG;QAE/B,KAAK,CACHD,QAAQG,MAAM,EACdF,IAAIG,IAAI,CAACC,KAAK,CAACJ,IAAIK,MAAM,CAACC,MAAM,GAChCP,QAAQQ,KAAK,GAAGC,IAAI;QAEtB,IAAI,CAACT,OAAO,GAAGA;QAEf,IAAI,CAACU,OAAO,GAAG,CAAC;QAChB,KAAK,MAAM,CAACC,MAAMC,MAAM,IAAIZ,QAAQU,OAAO,CAACG,OAAO,GAAI;YACrD,IAAI,CAACH,OAAO,CAACC,KAAK,GAAGC;QACvB;IACF;IAEA,MAAME,UAAUC,MAAuB,EAAgB;QACrD,MAAM,IAAIC,MAAM;IAClB;AACF;AAEA,OAAO,MAAMC,wBAAwBpB;IAoBnC,IAAIqB,OAAO;QACT,OAAO,IAAI,CAACC,KAAK;IACnB;IAEApB,YAAmBqB,kBAAkB,IAAIC,iBAAiB,CAAE;QAC1D,KAAK,CAACD,gBAAgBE,QAAQ;+BADbF;aAvBXV,UAAU,IAAIa;aACdC,WAA+BC;aAC/BN,QAAQ;aAERO,cAAc,IAAIC,QAAc,CAACC;YACvC,IAAI,CAACC,WAAW,GAAGD;QACrB;aAEQE,WAAW,IAAI,CAACJ,WAAW,CAACK,IAAI,CAAC;YACvC,OAAO,IAAIC,SAAS,IAAI,CAACR,QAAQ,IAAI,IAAI,CAACJ,eAAe,CAACa,QAAQ,EAAE;gBAClEvB,SAAS,IAAI,CAACA,OAAO;gBACrBwB,QAAQ,IAAI,CAACC,UAAU;gBACvBC,YAAY,IAAI,CAACC,aAAa;YAChC;QACF;IAWA;IAEAC,UAAU3B,IAAY,EAAEC,KAAwB,EAAQ;QACtD,IAAI,CAACF,OAAO,CAAC6B,MAAM,CAAC5B;QACpB,KAAK,MAAM6B,OAAOC,MAAMC,OAAO,CAAC9B,SAASA,QAAQ;YAACA;SAAM,CAAE;YACxD,IAAI,CAACF,OAAO,CAACiC,MAAM,CAAChC,MAAM6B;QAC5B;QACA,OAAO,IAAI;IACb;IAEAI,aAAajC,IAAY,EAAQ;QAC/B,IAAI,CAACD,OAAO,CAAC6B,MAAM,CAAC5B;QACpB,OAAO,IAAI;IACb;IAEAkC,gBAAgBlC,IAAY,EAAwB;YAE3C;QADP,iEAAiE;QACjE,QAAO,kBAAA,IAAI,CAACmC,SAAS,CAACnC,0BAAf,gBACHoC,KAAK,CAAC,KACPC,GAAG,CAAC,CAACC,IAAMA,EAAEC,SAAS;IAC3B;IAEAJ,UAAUnC,IAAY,EAAsB;QAC1C,OAAO,IAAI,CAACD,OAAO,CAACyC,GAAG,CAACxC,SAASc;IACnC;IAEA2B,aAAkC;QAChC,OAAOzD,0BAA0B,IAAI,CAACe,OAAO;IAC/C;IAEA2C,UAAU1C,IAAY,EAAW;QAC/B,OAAO,IAAI,CAACD,OAAO,CAAC4C,GAAG,CAAC3C;IAC1B;IAEA4C,aAAa5C,IAAY,EAAEC,KAAa,EAAQ;QAC9C,IAAI,CAACF,OAAO,CAACiC,MAAM,CAAChC,MAAMC;QAC1B,OAAO,IAAI;IACb;IAEAH,KAAKG,KAAa,EAAE;QAClB,IAAI,CAACY,QAAQ,GAAGZ;QAChB,OAAO,IAAI;IACb;IAEA4C,OAAO;YACL,mBAAA;SAAA,oBAAA,CAAA,QAAA,IAAI,EAAC3B,WAAW,qBAAhB,uBAAA;QACA,IAAI,CAACV,KAAK,GAAG;IACf;IAEAsC,aAAa;QACX,OAAO,IAAI,CAAC3B,QAAQ;IACtB;AACF"}

1846
node_modules/next/dist/esm/server/base-server.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/next/dist/esm/server/base-server.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

69
node_modules/next/dist/esm/server/body-streams.js generated vendored Normal file
View File

@@ -0,0 +1,69 @@
import { PassThrough } from "stream";
export function requestToBodyStream(context, KUint8Array, stream) {
return new context.ReadableStream({
start (controller) {
stream.on("data", (chunk)=>controller.enqueue(new KUint8Array([
...new Uint8Array(chunk)
])));
stream.on("end", ()=>controller.close());
stream.on("error", (err)=>controller.error(err));
}
});
}
function replaceRequestBody(base, stream) {
for(const key in stream){
let v = stream[key];
if (typeof v === "function") {
v = v.bind(base);
}
base[key] = v;
}
return base;
}
export function getCloneableBody(readable) {
let buffered = null;
const endPromise = new Promise((resolve, reject)=>{
readable.on("end", resolve);
readable.on("error", reject);
}).catch((error)=>{
return {
error
};
});
return {
/**
* Replaces the original request body if necessary.
* This is done because once we read the body from the original request,
* we can't read it again.
*/ async finalize () {
if (buffered) {
const res = await endPromise;
if (res && typeof res === "object" && res.error) {
throw res.error;
}
replaceRequestBody(readable, buffered);
buffered = readable;
}
},
/**
* Clones the body stream
* to pass into a middleware
*/ cloneBodyStream () {
const input = buffered ?? readable;
const p1 = new PassThrough();
const p2 = new PassThrough();
input.on("data", (chunk)=>{
p1.push(chunk);
p2.push(chunk);
});
input.on("end", ()=>{
p1.push(null);
p2.push(null);
});
buffered = p2;
return p1;
}
};
}
//# sourceMappingURL=body-streams.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/server/body-streams.ts"],"names":["PassThrough","requestToBodyStream","context","KUint8Array","stream","ReadableStream","start","controller","on","chunk","enqueue","Uint8Array","close","err","error","replaceRequestBody","base","key","v","bind","getCloneableBody","readable","buffered","endPromise","Promise","resolve","reject","catch","finalize","res","cloneBodyStream","input","p1","p2","push"],"mappings":"AACA,SAASA,WAAW,QAAkB,SAAQ;AAE9C,OAAO,SAASC,oBACdC,OAAkD,EAClDC,WAA8B,EAC9BC,MAAgB;IAEhB,OAAO,IAAIF,QAAQG,cAAc,CAAC;QAChCC,OAAMC,UAAU;YACdH,OAAOI,EAAE,CAAC,QAAQ,CAACC,QACjBF,WAAWG,OAAO,CAAC,IAAIP,YAAY;uBAAI,IAAIQ,WAAWF;iBAAO;YAE/DL,OAAOI,EAAE,CAAC,OAAO,IAAMD,WAAWK,KAAK;YACvCR,OAAOI,EAAE,CAAC,SAAS,CAACK,MAAQN,WAAWO,KAAK,CAACD;QAC/C;IACF;AACF;AAEA,SAASE,mBACPC,IAAO,EACPZ,MAAgB;IAEhB,IAAK,MAAMa,OAAOb,OAAQ;QACxB,IAAIc,IAAId,MAAM,CAACa,IAAsB;QACrC,IAAI,OAAOC,MAAM,YAAY;YAC3BA,IAAIA,EAAEC,IAAI,CAACH;QACb;QACAA,IAAI,CAACC,IAAe,GAAGC;IACzB;IAEA,OAAOF;AACT;AAOA,OAAO,SAASI,iBACdC,QAAW;IAEX,IAAIC,WAA4B;IAEhC,MAAMC,aAAa,IAAIC,QACrB,CAACC,SAASC;QACRL,SAASb,EAAE,CAAC,OAAOiB;QACnBJ,SAASb,EAAE,CAAC,SAASkB;IACvB,GACAC,KAAK,CAAC,CAACb;QACP,OAAO;YAAEA;QAAM;IACjB;IAEA,OAAO;QACL;;;;KAIC,GACD,MAAMc;YACJ,IAAIN,UAAU;gBACZ,MAAMO,MAAM,MAAMN;gBAElB,IAAIM,OAAO,OAAOA,QAAQ,YAAYA,IAAIf,KAAK,EAAE;oBAC/C,MAAMe,IAAIf,KAAK;gBACjB;gBACAC,mBAAmBM,UAAUC;gBAC7BA,WAAWD;YACb;QACF;QACA;;;KAGC,GACDS;YACE,MAAMC,QAAQT,YAAYD;YAC1B,MAAMW,KAAK,IAAIhC;YACf,MAAMiC,KAAK,IAAIjC;YACf+B,MAAMvB,EAAE,CAAC,QAAQ,CAACC;gBAChBuB,GAAGE,IAAI,CAACzB;gBACRwB,GAAGC,IAAI,CAACzB;YACV;YACAsB,MAAMvB,EAAE,CAAC,OAAO;gBACdwB,GAAGE,IAAI,CAAC;gBACRD,GAAGC,IAAI,CAAC;YACV;YACAZ,WAAWW;YACX,OAAOD;QACT;IACF;AACF"}

865
node_modules/next/dist/esm/server/config-schema.js generated vendored Normal file
View File

@@ -0,0 +1,865 @@
import { VALID_LOADERS } from "../shared/lib/image-config";
const configSchema = {
type: "object",
additionalProperties: false,
properties: {
amp: {
additionalProperties: false,
properties: {
canonicalBase: {
nullable: true,
type: "string"
}
},
type: "object"
},
analyticsId: {
type: "string"
},
assetPrefix: {
nullable: true,
type: "string"
},
basePath: {
type: "string"
},
cleanDistDir: {
type: "boolean"
},
compiler: {
additionalProperties: false,
properties: {
emotion: {
oneOf: [
{
type: "boolean"
},
{
type: "object",
additionalProperties: false,
properties: {
sourceMap: {
type: "boolean"
},
autoLabel: {
type: "string",
enum: [
"always",
"dev-only",
"never"
]
},
labelFormat: {
type: "string",
minLength: 1
},
importMap: {
type: "object"
}
}
}
]
},
reactRemoveProperties: {
oneOf: [
{
type: "boolean"
},
{
type: "object",
additionalProperties: false,
properties: {
properties: {
type: "array",
items: {
type: "string"
}
}
}
}
]
},
relay: {
type: "object"
},
removeConsole: {
oneOf: [
{
type: "boolean"
},
{
type: "object",
additionalProperties: false,
properties: {
exclude: {
type: "array",
items: {
type: "string",
minLength: 1
}
}
}
}
]
},
styledComponents: {
oneOf: [
{
type: "boolean"
},
{
type: "object",
additionalProperties: false,
properties: {
displayName: {
type: "boolean"
},
topLevelImportPaths: {
oneOf: [
{
type: "boolean"
},
{
type: "array",
items: {
type: "string",
minLength: 1
}
}
]
},
ssr: {
type: "boolean"
},
fileName: {
type: "boolean"
},
meaninglessFileNames: {
oneOf: [
{
type: "boolean"
},
{
type: "array",
items: {
type: "string",
minLength: 1
}
}
]
},
minify: {
type: "boolean"
},
transpileTemplateLiterals: {
type: "boolean"
},
namespace: {
type: "string",
minLength: 1
},
pure: {
type: "boolean"
},
cssProp: {
type: "boolean"
}
}
}
]
}
},
type: "object"
},
compress: {
type: "boolean"
},
configOrigin: {
type: "string"
},
crossOrigin: {
oneOf: [
false,
{
enum: [
"anonymous",
"use-credentials"
],
type: "string"
}
]
},
devIndicators: {
additionalProperties: false,
properties: {
buildActivity: {
type: "boolean"
},
buildActivityPosition: {
// automatic typing does not like enum
enum: [
"bottom-left",
"bottom-right",
"top-left",
"top-right"
],
type: "string"
}
},
type: "object"
},
distDir: {
minLength: 1,
type: "string",
nullable: true
},
env: {
type: "object"
},
eslint: {
additionalProperties: false,
properties: {
dirs: {
items: {
minLength: 1,
type: "string"
},
type: "array"
},
ignoreDuringBuilds: {
type: "boolean"
}
},
type: "object"
},
excludeDefaultMomentLocales: {
type: "boolean"
},
experimental: {
additionalProperties: false,
properties: {
appDocumentPreloading: {
type: "boolean"
},
adjustFontFallbacks: {
type: "boolean"
},
adjustFontFallbacksWithSizeAdjust: {
type: "boolean"
},
allowedRevalidateHeaderKeys: {
type: "array"
},
amp: {
additionalProperties: false,
properties: {
optimizer: {
type: "object"
},
skipValidation: {
type: "boolean"
},
validator: {
type: "string"
}
},
type: "object"
},
clientRouterFilter: {
type: "boolean"
},
clientRouterFilterRedirects: {
type: "boolean"
},
clientRouterFilterAllowedRate: {
type: "number"
},
cpus: {
type: "number"
},
memoryBasedWorkersCount: {
type: "boolean"
},
craCompat: {
type: "boolean"
},
caseSensitiveRoutes: {
type: "boolean"
},
useDeploymentId: {
type: "boolean"
},
useDeploymentIdServerActions: {
type: "boolean"
},
deploymentId: {
type: "string"
},
disableOptimizedLoading: {
type: "boolean"
},
disablePostcssPresetEnv: {
type: "boolean"
},
esmExternals: {
oneOf: [
{
type: "boolean"
},
{
const: "loose"
}
]
},
serverActions: {
type: "boolean"
},
serverActionsBodySizeLimit: {
oneOf: [
{
type: "number"
},
{
type: "string"
}
]
},
extensionAlias: {
type: "object"
},
externalDir: {
type: "boolean"
},
externalMiddlewareRewritesResolve: {
type: "boolean"
},
fallbackNodePolyfills: {
type: "boolean"
},
fetchCacheKeyPrefix: {
type: "string"
},
forceSwcTransforms: {
type: "boolean"
},
fullySpecified: {
type: "boolean"
},
gzipSize: {
type: "boolean"
},
incrementalCacheHandlerPath: {
type: "string"
},
isrFlushToDisk: {
type: "boolean"
},
isrMemoryCacheSize: {
type: "number"
},
largePageDataBytes: {
type: "number"
},
manualClientBasePath: {
type: "boolean"
},
middlewarePrefetch: {
// automatic typing doesn't like enum
enum: [
"strict",
"flexible"
],
type: "string"
},
nextScriptWorkers: {
type: "boolean"
},
optimizeCss: {
oneOf: [
{
type: "boolean"
},
{
type: "object"
}
]
},
optimisticClientCache: {
type: "boolean"
},
outputFileTracingRoot: {
nullable: true,
type: "string"
},
outputFileTracingExcludes: {
type: "object"
},
outputFileTracingIgnores: {
type: "array"
},
outputFileTracingIncludes: {
type: "object"
},
ppr: {
type: "boolean"
},
proxyTimeout: {
minimum: 0,
type: "number"
},
serverComponentsExternalPackages: {
items: {
type: "string"
},
type: "array"
},
scrollRestoration: {
type: "boolean"
},
sharedPool: {
type: "boolean"
},
sri: {
properties: {
algorithm: {
enum: [
"sha256",
"sha384",
"sha512"
],
type: "string"
}
},
type: "object"
},
strictNextHead: {
type: "boolean"
},
swcMinify: {
type: "boolean"
},
swcPlugins: {
type: "array"
},
swcTraceProfiling: {
type: "boolean"
},
urlImports: {
items: {
type: "string"
},
type: "array"
},
workerThreads: {
type: "boolean"
},
webVitalsAttribution: {
type: "array",
items: {
type: "string",
enum: [
"CLS",
"FCP",
"FID",
"INP",
"LCP",
"TTFB"
]
}
},
mdxRs: {
type: "boolean"
},
typedRoutes: {
type: "boolean"
},
webpackBuildWorker: {
type: "boolean"
},
turbo: {
type: "object",
additionalProperties: false,
properties: {
loaders: {
type: "object"
},
rules: {
type: "object"
},
resolveAlias: {
type: "object"
}
}
},
optimizePackageImports: {
type: "array"
},
optimizeServerReact: {
type: "boolean"
},
instrumentationHook: {
type: "boolean"
},
turbotrace: {
type: "object",
properties: {
logLevel: {
type: "string",
enum: [
"bug",
"fatal",
"error",
"warning",
"hint",
"note",
"suggestions",
"info"
]
},
logAll: {
type: "boolean"
},
logDetail: {
type: "boolean"
},
contextDirectory: {
type: "string"
},
processCwd: {
type: "string"
},
memoryLimit: {
type: "integer"
}
}
},
logging: {
type: "object",
properties: {
level: {
type: "string"
},
fullUrl: {
type: "boolean"
}
}
},
serverMinification: {
type: "boolean"
},
serverSourceMaps: {
type: "boolean"
}
},
type: "object"
},
exportPathMap: {
isFunction: true,
errorMessage: "must be a function that returns a Promise"
},
generateBuildId: {
isFunction: true,
errorMessage: "must be a function that returns a Promise"
},
generateEtags: {
type: "boolean"
},
headers: {
isFunction: true,
errorMessage: "must be a function that returns a Promise"
},
httpAgentOptions: {
additionalProperties: false,
properties: {
keepAlive: {
type: "boolean"
}
},
type: "object"
},
i18n: {
additionalProperties: false,
nullable: true,
properties: {
defaultLocale: {
minLength: 1,
type: "string"
},
domains: {
items: {
additionalProperties: false,
properties: {
defaultLocale: {
minLength: 1,
type: "string"
},
domain: {
minLength: 1,
type: "string"
},
http: {
type: "boolean"
},
locales: {
items: {
minLength: 1,
type: "string"
},
type: "array"
}
},
type: "object"
},
type: "array"
},
localeDetection: {
type: "boolean"
},
locales: {
items: {
minLength: 1,
type: "string"
},
type: "array"
}
},
type: "object"
},
images: {
additionalProperties: false,
nullable: true,
properties: {
remotePatterns: {
nullable: true,
items: {
additionalProperties: false,
properties: {
hostname: {
type: "string"
},
pathname: {
type: "string"
},
port: {
maxLength: 5,
type: "string"
},
protocol: {
// automatic typing doesn't like enum
enum: [
"http",
"https"
],
type: "string"
}
},
required: [
"hostname"
],
type: "object"
},
maxItems: 50,
type: "array"
},
unoptimized: {
type: "boolean"
},
contentSecurityPolicy: {
type: "string",
nullable: true
},
contentDispositionType: {
enum: [
"inline",
"attachment"
],
type: "string",
nullable: true
},
dangerouslyAllowSVG: {
type: "boolean",
nullable: true
},
deviceSizes: {
items: {
type: "integer",
minimum: 1,
maximum: 10000
},
maxItems: 25,
type: "array",
nullable: true
},
disableStaticImages: {
type: "boolean",
nullable: true
},
domains: {
items: {
type: "string"
},
maxItems: 50,
type: "array",
nullable: true
},
formats: {
items: {
enum: [
"image/avif",
"image/webp"
],
type: "string"
},
maxItems: 4,
type: "array",
nullable: true
},
imageSizes: {
items: {
type: "integer",
minimum: 1,
maximum: 10000
},
minItems: 0,
maxItems: 25,
type: "array",
nullable: true
},
loader: {
// automatic typing does not like enum
enum: VALID_LOADERS,
type: "string",
nullable: true
},
loaderFile: {
type: "string",
nullable: true
},
minimumCacheTTL: {
type: "integer",
minimum: 0,
nullable: true
},
path: {
type: "string",
nullable: true
}
},
type: "object"
},
modularizeImports: {
type: "object"
},
onDemandEntries: {
additionalProperties: false,
properties: {
maxInactiveAge: {
type: "number"
},
pagesBufferLength: {
type: "number"
}
},
type: "object"
},
optimizeFonts: {
type: "boolean"
},
output: {
// automatic typing doesn't like enum
enum: [
"standalone",
"export"
],
type: "string"
},
outputFileTracing: {
type: "boolean"
},
pageExtensions: {
minItems: 1,
type: "array"
},
poweredByHeader: {
type: "boolean"
},
productionBrowserSourceMaps: {
type: "boolean"
},
publicRuntimeConfig: {
type: "object"
},
reactProductionProfiling: {
type: "boolean"
},
reactStrictMode: {
type: "boolean",
nullable: true
},
redirects: {
isFunction: true,
errorMessage: "must be a function that returns a Promise"
},
rewrites: {
isFunction: true,
errorMessage: "must be a function that returns a Promise"
},
sassOptions: {
type: "object"
},
serverRuntimeConfig: {
type: "object"
},
skipMiddlewareUrlNormalize: {
type: "boolean"
},
skipTrailingSlashRedirect: {
type: "boolean"
},
staticPageGenerationTimeout: {
type: "number"
},
swcMinify: {
type: "boolean"
},
target: {
type: "string"
},
trailingSlash: {
type: "boolean"
},
transpilePackages: {
items: {
type: "string"
},
type: "array"
},
typescript: {
additionalProperties: false,
properties: {
ignoreBuildErrors: {
type: "boolean"
},
tsconfigPath: {
minLength: 1,
type: "string"
}
},
type: "object"
},
useFileSystemPublicRoutes: {
type: "boolean"
},
webpack: {
isFunction: true,
errorMessage: "must be a function that returns a webpack configuration object"
}
}
};
// module.exports is used to get around an export bug with TypeScript
// and the Ajv automatic typing
module.exports = {
configSchema
};
//# sourceMappingURL=config-schema.js.map

File diff suppressed because one or more lines are too long

133
node_modules/next/dist/esm/server/config-shared.js generated vendored Normal file
View File

@@ -0,0 +1,133 @@
import os from "os";
import { imageConfigDefault } from "../shared/lib/image-config";
export const defaultConfig = {
env: {},
webpack: null,
eslint: {
ignoreDuringBuilds: false
},
typescript: {
ignoreBuildErrors: false,
tsconfigPath: "tsconfig.json"
},
distDir: ".next",
cleanDistDir: true,
assetPrefix: "",
configOrigin: "default",
useFileSystemPublicRoutes: true,
generateBuildId: ()=>null,
generateEtags: true,
pageExtensions: [
"tsx",
"ts",
"jsx",
"js"
],
poweredByHeader: true,
compress: true,
analyticsId: process.env.VERCEL_ANALYTICS_ID || "",
images: imageConfigDefault,
devIndicators: {
buildActivity: true,
buildActivityPosition: "bottom-right"
},
onDemandEntries: {
maxInactiveAge: 60 * 1000,
pagesBufferLength: 5
},
amp: {
canonicalBase: ""
},
basePath: "",
sassOptions: {},
trailingSlash: false,
i18n: null,
productionBrowserSourceMaps: false,
optimizeFonts: true,
excludeDefaultMomentLocales: true,
serverRuntimeConfig: {},
publicRuntimeConfig: {},
reactProductionProfiling: false,
reactStrictMode: null,
httpAgentOptions: {
keepAlive: true
},
outputFileTracing: true,
staticPageGenerationTimeout: 60,
swcMinify: true,
output: !!process.env.NEXT_PRIVATE_STANDALONE ? "standalone" : undefined,
modularizeImports: undefined,
experimental: {
serverMinification: true,
serverSourceMaps: false,
caseSensitiveRoutes: false,
useDeploymentId: false,
deploymentId: undefined,
useDeploymentIdServerActions: false,
appDocumentPreloading: undefined,
clientRouterFilter: true,
clientRouterFilterRedirects: false,
fetchCacheKeyPrefix: "",
middlewarePrefetch: "flexible",
optimisticClientCache: true,
manualClientBasePath: false,
cpus: Math.max(1, (Number(process.env.CIRCLE_NODE_TOTAL) || (os.cpus() || {
length: 1
}).length) - 1),
memoryBasedWorkersCount: false,
sharedPool: true,
isrFlushToDisk: true,
workerThreads: false,
proxyTimeout: undefined,
optimizeCss: false,
nextScriptWorkers: false,
scrollRestoration: false,
externalDir: false,
disableOptimizedLoading: false,
gzipSize: true,
craCompat: false,
esmExternals: true,
// default to 50MB limit
isrMemoryCacheSize: 50 * 1024 * 1024,
incrementalCacheHandlerPath: undefined,
fullySpecified: false,
outputFileTracingRoot: process.env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT || "",
swcTraceProfiling: false,
forceSwcTransforms: false,
swcPlugins: undefined,
largePageDataBytes: 128 * 1000,
disablePostcssPresetEnv: undefined,
amp: undefined,
urlImports: undefined,
adjustFontFallbacks: false,
adjustFontFallbacksWithSizeAdjust: false,
turbo: undefined,
turbotrace: undefined,
typedRoutes: false,
instrumentationHook: false
}
};
export async function normalizeConfig(phase, config) {
if (typeof config === "function") {
config = config(phase, {
defaultConfig
});
}
// Support `new Promise` and `async () =>` as return values of the config export
return await config;
}
export function validateConfig(userConfig) {
if (process.env.NEXT_MINIMAL) {
return {
errors: []
};
} else {
const configValidator = require("next/dist/next-config-validate.js");
configValidator(userConfig);
return {
errors: configValidator.errors
};
}
}
//# sourceMappingURL=config-shared.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/server/config-shared.ts"],"names":["os","imageConfigDefault","defaultConfig","env","webpack","eslint","ignoreDuringBuilds","typescript","ignoreBuildErrors","tsconfigPath","distDir","cleanDistDir","assetPrefix","configOrigin","useFileSystemPublicRoutes","generateBuildId","generateEtags","pageExtensions","poweredByHeader","compress","analyticsId","process","VERCEL_ANALYTICS_ID","images","devIndicators","buildActivity","buildActivityPosition","onDemandEntries","maxInactiveAge","pagesBufferLength","amp","canonicalBase","basePath","sassOptions","trailingSlash","i18n","productionBrowserSourceMaps","optimizeFonts","excludeDefaultMomentLocales","serverRuntimeConfig","publicRuntimeConfig","reactProductionProfiling","reactStrictMode","httpAgentOptions","keepAlive","outputFileTracing","staticPageGenerationTimeout","swcMinify","output","NEXT_PRIVATE_STANDALONE","undefined","modularizeImports","experimental","serverMinification","serverSourceMaps","caseSensitiveRoutes","useDeploymentId","deploymentId","useDeploymentIdServerActions","appDocumentPreloading","clientRouterFilter","clientRouterFilterRedirects","fetchCacheKeyPrefix","middlewarePrefetch","optimisticClientCache","manualClientBasePath","cpus","Math","max","Number","CIRCLE_NODE_TOTAL","length","memoryBasedWorkersCount","sharedPool","isrFlushToDisk","workerThreads","proxyTimeout","optimizeCss","nextScriptWorkers","scrollRestoration","externalDir","disableOptimizedLoading","gzipSize","craCompat","esmExternals","isrMemoryCacheSize","incrementalCacheHandlerPath","fullySpecified","outputFileTracingRoot","NEXT_PRIVATE_OUTPUT_TRACE_ROOT","swcTraceProfiling","forceSwcTransforms","swcPlugins","largePageDataBytes","disablePostcssPresetEnv","urlImports","adjustFontFallbacks","adjustFontFallbacksWithSizeAdjust","turbo","turbotrace","typedRoutes","instrumentationHook","normalizeConfig","phase","config","validateConfig","userConfig","NEXT_MINIMAL","errors","configValidator","require"],"mappings":"AAAA,OAAOA,QAAQ,KAAI;AAGnB,SAGEC,kBAAkB,QACb,6BAA4B;AAwpBnC,OAAO,MAAMC,gBAA4B;IACvCC,KAAK,CAAC;IACNC,SAAS;IACTC,QAAQ;QACNC,oBAAoB;IACtB;IACAC,YAAY;QACVC,mBAAmB;QACnBC,cAAc;IAChB;IACAC,SAAS;IACTC,cAAc;IACdC,aAAa;IACbC,cAAc;IACdC,2BAA2B;IAC3BC,iBAAiB,IAAM;IACvBC,eAAe;IACfC,gBAAgB;QAAC;QAAO;QAAM;QAAO;KAAK;IAC1CC,iBAAiB;IACjBC,UAAU;IACVC,aAAaC,QAAQlB,GAAG,CAACmB,mBAAmB,IAAI;IAChDC,QAAQtB;IACRuB,eAAe;QACbC,eAAe;QACfC,uBAAuB;IACzB;IACAC,iBAAiB;QACfC,gBAAgB,KAAK;QACrBC,mBAAmB;IACrB;IACAC,KAAK;QACHC,eAAe;IACjB;IACAC,UAAU;IACVC,aAAa,CAAC;IACdC,eAAe;IACfC,MAAM;IACNC,6BAA6B;IAC7BC,eAAe;IACfC,6BAA6B;IAC7BC,qBAAqB,CAAC;IACtBC,qBAAqB,CAAC;IACtBC,0BAA0B;IAC1BC,iBAAiB;IACjBC,kBAAkB;QAChBC,WAAW;IACb;IACAC,mBAAmB;IACnBC,6BAA6B;IAC7BC,WAAW;IACXC,QAAQ,CAAC,CAAC3B,QAAQlB,GAAG,CAAC8C,uBAAuB,GAAG,eAAeC;IAC/DC,mBAAmBD;IACnBE,cAAc;QACZC,oBAAoB;QACpBC,kBAAkB;QAClBC,qBAAqB;QACrBC,iBAAiB;QACjBC,cAAcP;QACdQ,8BAA8B;QAC9BC,uBAAuBT;QACvBU,oBAAoB;QACpBC,6BAA6B;QAC7BC,qBAAqB;QACrBC,oBAAoB;QACpBC,uBAAuB;QACvBC,sBAAsB;QACtBC,MAAMC,KAAKC,GAAG,CACZ,GACA,AAACC,CAAAA,OAAOhD,QAAQlB,GAAG,CAACmE,iBAAiB,KACnC,AAACtE,CAAAA,GAAGkE,IAAI,MAAM;YAAEK,QAAQ;QAAE,CAAA,EAAGA,MAAM,AAAD,IAAK;QAE3CC,yBAAyB;QACzBC,YAAY;QACZC,gBAAgB;QAChBC,eAAe;QACfC,cAAc1B;QACd2B,aAAa;QACbC,mBAAmB;QACnBC,mBAAmB;QACnBC,aAAa;QACbC,yBAAyB;QACzBC,UAAU;QACVC,WAAW;QACXC,cAAc;QACd,wBAAwB;QACxBC,oBAAoB,KAAK,OAAO;QAChCC,6BAA6BpC;QAC7BqC,gBAAgB;QAChBC,uBAAuBnE,QAAQlB,GAAG,CAACsF,8BAA8B,IAAI;QACrEC,mBAAmB;QACnBC,oBAAoB;QACpBC,YAAY1C;QACZ2C,oBAAoB,MAAM;QAC1BC,yBAAyB5C;QACzBpB,KAAKoB;QACL6C,YAAY7C;QACZ8C,qBAAqB;QACrBC,mCAAmC;QACnCC,OAAOhD;QACPiD,YAAYjD;QACZkD,aAAa;QACbC,qBAAqB;IACvB;AACF,EAAC;AAED,OAAO,eAAeC,gBAAgBC,KAAa,EAAEC,MAAW;IAC9D,IAAI,OAAOA,WAAW,YAAY;QAChCA,SAASA,OAAOD,OAAO;YAAErG;QAAc;IACzC;IACA,gFAAgF;IAChF,OAAO,MAAMsG;AACf;AAEA,OAAO,SAASC,eAAeC,UAAsB;IAGnD,IAAIrF,QAAQlB,GAAG,CAACwG,YAAY,EAAE;QAC5B,OAAO;YACLC,QAAQ,EAAE;QACZ;IACF,OAAO;QACL,MAAMC,kBAAkBC,QAAQ;QAChCD,gBAAgBH;QAChB,OAAO;YACLE,QAAQC,gBAAgBD,MAAM;QAChC;IACF;AACF"}

183
node_modules/next/dist/esm/server/config-utils.js generated vendored Normal file
View File

@@ -0,0 +1,183 @@
let installed = false;
export function loadWebpackHook() {
const { init: initWebpack } = require("next/dist/compiled/webpack/webpack");
if (installed) {
return;
}
installed = true;
initWebpack();
// hook the Node.js require so that webpack requires are
// routed to the bundled and now initialized webpack version
require("../server/require-hook").addHookAliases([
[
"webpack",
"next/dist/compiled/webpack/webpack-lib"
],
[
"webpack/package",
"next/dist/compiled/webpack/package"
],
[
"webpack/package.json",
"next/dist/compiled/webpack/package"
],
[
"webpack/lib/webpack",
"next/dist/compiled/webpack/webpack-lib"
],
[
"webpack/lib/webpack.js",
"next/dist/compiled/webpack/webpack-lib"
],
[
"webpack/lib/node/NodeEnvironmentPlugin",
"next/dist/compiled/webpack/NodeEnvironmentPlugin"
],
[
"webpack/lib/node/NodeEnvironmentPlugin.js",
"next/dist/compiled/webpack/NodeEnvironmentPlugin"
],
[
"webpack/lib/BasicEvaluatedExpression",
"next/dist/compiled/webpack/BasicEvaluatedExpression"
],
[
"webpack/lib/BasicEvaluatedExpression.js",
"next/dist/compiled/webpack/BasicEvaluatedExpression"
],
[
"webpack/lib/node/NodeTargetPlugin",
"next/dist/compiled/webpack/NodeTargetPlugin"
],
[
"webpack/lib/node/NodeTargetPlugin.js",
"next/dist/compiled/webpack/NodeTargetPlugin"
],
[
"webpack/lib/node/NodeTemplatePlugin",
"next/dist/compiled/webpack/NodeTemplatePlugin"
],
[
"webpack/lib/node/NodeTemplatePlugin.js",
"next/dist/compiled/webpack/NodeTemplatePlugin"
],
[
"webpack/lib/LibraryTemplatePlugin",
"next/dist/compiled/webpack/LibraryTemplatePlugin"
],
[
"webpack/lib/LibraryTemplatePlugin.js",
"next/dist/compiled/webpack/LibraryTemplatePlugin"
],
[
"webpack/lib/SingleEntryPlugin",
"next/dist/compiled/webpack/SingleEntryPlugin"
],
[
"webpack/lib/SingleEntryPlugin.js",
"next/dist/compiled/webpack/SingleEntryPlugin"
],
[
"webpack/lib/optimize/LimitChunkCountPlugin",
"next/dist/compiled/webpack/LimitChunkCountPlugin"
],
[
"webpack/lib/optimize/LimitChunkCountPlugin.js",
"next/dist/compiled/webpack/LimitChunkCountPlugin"
],
[
"webpack/lib/webworker/WebWorkerTemplatePlugin",
"next/dist/compiled/webpack/WebWorkerTemplatePlugin"
],
[
"webpack/lib/webworker/WebWorkerTemplatePlugin.js",
"next/dist/compiled/webpack/WebWorkerTemplatePlugin"
],
[
"webpack/lib/ExternalsPlugin",
"next/dist/compiled/webpack/ExternalsPlugin"
],
[
"webpack/lib/ExternalsPlugin.js",
"next/dist/compiled/webpack/ExternalsPlugin"
],
[
"webpack/lib/web/FetchCompileWasmTemplatePlugin",
"next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin"
],
[
"webpack/lib/web/FetchCompileWasmTemplatePlugin.js",
"next/dist/compiled/webpack/FetchCompileWasmTemplatePlugin"
],
[
"webpack/lib/web/FetchCompileWasmPlugin",
"next/dist/compiled/webpack/FetchCompileWasmPlugin"
],
[
"webpack/lib/web/FetchCompileWasmPlugin.js",
"next/dist/compiled/webpack/FetchCompileWasmPlugin"
],
[
"webpack/lib/web/FetchCompileAsyncWasmPlugin",
"next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin"
],
[
"webpack/lib/web/FetchCompileAsyncWasmPlugin.js",
"next/dist/compiled/webpack/FetchCompileAsyncWasmPlugin"
],
[
"webpack/lib/ModuleFilenameHelpers",
"next/dist/compiled/webpack/ModuleFilenameHelpers"
],
[
"webpack/lib/ModuleFilenameHelpers.js",
"next/dist/compiled/webpack/ModuleFilenameHelpers"
],
[
"webpack/lib/GraphHelpers",
"next/dist/compiled/webpack/GraphHelpers"
],
[
"webpack/lib/GraphHelpers.js",
"next/dist/compiled/webpack/GraphHelpers"
],
[
"webpack/lib/NormalModule",
"next/dist/compiled/webpack/NormalModule"
],
[
"webpack-sources",
"next/dist/compiled/webpack/sources"
],
[
"webpack-sources/lib",
"next/dist/compiled/webpack/sources"
],
[
"webpack-sources/lib/index",
"next/dist/compiled/webpack/sources"
],
[
"webpack-sources/lib/index.js",
"next/dist/compiled/webpack/sources"
],
[
"@babel/runtime",
"next/dist/compiled/@babel/runtime/package.json"
],
[
"@babel/runtime/package.json",
"next/dist/compiled/@babel/runtime/package.json"
],
[
"undici",
"next/dist/compiled/undici"
]
].map(// Use dynamic require.resolve to avoid statically analyzable since they're only for build time
([request, replacement])=>[
request,
require.resolve(replacement)
]));
}
//# sourceMappingURL=config-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/server/config-utils.ts"],"names":["installed","loadWebpackHook","init","initWebpack","require","addHookAliases","map","request","replacement","resolve"],"mappings":"AAAA,IAAIA,YAAqB;AAEzB,OAAO,SAASC;IACd,MAAM,EAAEC,MAAMC,WAAW,EAAE,GAAGC,QAAQ;IACtC,IAAIJ,WAAW;QACb;IACF;IACAA,YAAY;IACZG;IAEA,wDAAwD;IACxD,4DAA4D;IAC5DC,QAAQ,0BAA0BC,cAAc,CAC9C;QACE;YAAC;YAAW;SAAyC;QACrD;YAAC;YAAmB;SAAqC;QACzD;YAAC;YAAwB;SAAqC;QAC9D;YAAC;YAAuB;SAAyC;QACjE;YAAC;YAA0B;SAAyC;QACpE;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YACE;YACA;SACD;QACD;YAAC;YAA4B;SAA0C;QACvE;YACE;YACA;SACD;QACD;YAAC;YAA4B;SAA0C;QACvE;YAAC;YAAmB;SAAqC;QACzD;YAAC;YAAuB;SAAqC;QAC7D;YAAC;YAA6B;SAAqC;QACnE;YAAC;YAAgC;SAAqC;QACtE;YAAC;YAAkB;SAAiD;QACpE;YACE;YACA;SACD;QACD;YAAC;YAAU;SAA4B;KACxC,CAACC,GAAG,CACH,+FAA+F;IAC/F,CAAC,CAACC,SAASC,YAAY,GAAK;YAACD;YAASH,QAAQK,OAAO,CAACD;SAAa;AAGzE"}

647
node_modules/next/dist/esm/server/config.js generated vendored Normal file
View File

@@ -0,0 +1,647 @@
import { existsSync } from "fs";
import { basename, extname, join, relative, isAbsolute, resolve } from "path";
import { pathToFileURL } from "url";
import findUp from "next/dist/compiled/find-up";
import * as Log from "../build/output/log";
import { CONFIG_FILES, PHASE_DEVELOPMENT_SERVER } from "../shared/lib/constants";
import { defaultConfig, normalizeConfig, validateConfig } from "./config-shared";
import { loadWebpackHook } from "./config-utils";
import { imageConfigDefault } from "../shared/lib/image-config";
import { loadEnvConfig, updateInitialEnv } from "@next/env";
import { flushAndExit } from "../telemetry/flush-and-exit";
import { findRootDir } from "../lib/find-root";
import { setHttpClientAndAgentOptions } from "./setup-http-agent-env";
import { pathHasPrefix } from "../shared/lib/router/utils/path-has-prefix";
export { DomainLocale, NextConfig, normalizeConfig } from "./config-shared";
export function warnOptionHasBeenDeprecated(config, nestedPropertyKey, reason, silent) {
if (!silent) {
let current = config;
let found = true;
const nestedPropertyKeys = nestedPropertyKey.split(".");
for (const key of nestedPropertyKeys){
if (current[key] !== undefined) {
current = current[key];
} else {
found = false;
break;
}
}
if (found) {
Log.warn(reason);
}
}
}
export function warnOptionHasBeenMovedOutOfExperimental(config, oldKey, newKey, configFileName, silent) {
if (config.experimental && oldKey in config.experimental) {
if (!silent) {
Log.warn(`\`${oldKey}\` has been moved out of \`experimental\`` + (newKey.includes(".") ? ` and into \`${newKey}\`` : "") + `. Please update your ${configFileName} file accordingly.`);
}
let current = config;
const newKeys = newKey.split(".");
while(newKeys.length > 1){
const key = newKeys.shift();
current[key] = current[key] || {};
current = current[key];
}
current[newKeys.shift()] = config.experimental[oldKey];
}
return config;
}
function assignDefaults(dir, userConfig, silent) {
var _result_experimental, _result_experimental1, _result_experimental2, _result_experimental3, _result_experimental4, _result_experimental5, _result_devIndicators, _result_experimental6;
const configFileName = userConfig.configFileName;
if (typeof userConfig.exportTrailingSlash !== "undefined") {
if (!silent) {
Log.warn(`The "exportTrailingSlash" option has been renamed to "trailingSlash". Please update your ${configFileName}.`);
}
if (typeof userConfig.trailingSlash === "undefined") {
userConfig.trailingSlash = userConfig.exportTrailingSlash;
}
delete userConfig.exportTrailingSlash;
}
const config = Object.keys(userConfig).reduce((currentConfig, key)=>{
const value = userConfig[key];
if (value === undefined || value === null) {
return currentConfig;
}
if (key === "distDir") {
if (typeof value !== "string") {
throw new Error(`Specified distDir is not a string, found type "${typeof value}"`);
}
const userDistDir = value.trim();
// don't allow public as the distDir as this is a reserved folder for
// public files
if (userDistDir === "public") {
throw new Error(`The 'public' directory is reserved in Next.js and can not be set as the 'distDir'. https://nextjs.org/docs/messages/can-not-output-to-public`);
}
// make sure distDir isn't an empty string as it can result in the provided
// directory being deleted in development mode
if (userDistDir.length === 0) {
throw new Error(`Invalid distDir provided, distDir can not be an empty string. Please remove this config or set it to undefined`);
}
}
if (key === "pageExtensions") {
if (!Array.isArray(value)) {
throw new Error(`Specified pageExtensions is not an array of strings, found "${value}". Please update this config or remove it.`);
}
if (!value.length) {
throw new Error(`Specified pageExtensions is an empty array. Please update it with the relevant extensions or remove it.`);
}
value.forEach((ext)=>{
if (typeof ext !== "string") {
throw new Error(`Specified pageExtensions is not an array of strings, found "${ext}" of type "${typeof ext}". Please update this config or remove it.`);
}
});
}
if (!!value && value.constructor === Object) {
currentConfig[key] = {
...defaultConfig[key],
...Object.keys(value).reduce((c, k)=>{
const v = value[k];
if (v !== undefined && v !== null) {
c[k] = v;
}
return c;
}, {})
};
} else {
currentConfig[key] = value;
}
return currentConfig;
}, {});
const result = {
...defaultConfig,
...config
};
if (result.output === "export") {
if (result.i18n) {
throw new Error('Specified "i18n" cannot be used with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-i18n');
}
if (result.rewrites) {
throw new Error('Specified "rewrites" cannot be used with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-custom-routes');
}
if (result.redirects) {
throw new Error('Specified "redirects" cannot be used with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-custom-routes');
}
if (result.headers) {
throw new Error('Specified "headers" cannot be used with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-custom-routes');
}
}
if (typeof result.assetPrefix !== "string") {
throw new Error(`Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://nextjs.org/docs/messages/invalid-assetprefix`);
}
if (typeof result.basePath !== "string") {
throw new Error(`Specified basePath is not a string, found type "${typeof result.basePath}"`);
}
// TODO: remove after next minor (current v13.1.1)
if (Array.isArray((_result_experimental = result.experimental) == null ? void 0 : _result_experimental.outputFileTracingIgnores)) {
if (!result.experimental) {
result.experimental = {};
}
if (!result.experimental.outputFileTracingExcludes) {
result.experimental.outputFileTracingExcludes = {};
}
if (!result.experimental.outputFileTracingExcludes["**/*"]) {
result.experimental.outputFileTracingExcludes["**/*"] = [];
}
result.experimental.outputFileTracingExcludes["**/*"].push(...result.experimental.outputFileTracingIgnores || []);
Log.warn(`\`outputFileTracingIgnores\` has been moved to \`experimental.outputFileTracingExcludes\`. Please update your ${configFileName} file accordingly.`);
}
if (result.basePath !== "") {
if (result.basePath === "/") {
throw new Error(`Specified basePath /. basePath has to be either an empty string or a path prefix"`);
}
if (!result.basePath.startsWith("/")) {
throw new Error(`Specified basePath has to start with a /, found "${result.basePath}"`);
}
if (result.basePath !== "/") {
var _result_amp;
if (result.basePath.endsWith("/")) {
throw new Error(`Specified basePath should not end with /, found "${result.basePath}"`);
}
if (result.assetPrefix === "") {
result.assetPrefix = result.basePath;
}
if (((_result_amp = result.amp) == null ? void 0 : _result_amp.canonicalBase) === "") {
result.amp.canonicalBase = result.basePath;
}
}
}
if (result == null ? void 0 : result.images) {
const images = result.images;
if (typeof images !== "object") {
throw new Error(`Specified images should be an object received ${typeof images}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`);
}
if (images.domains) {
var _config_assetPrefix;
if (!Array.isArray(images.domains)) {
throw new Error(`Specified images.domains should be an Array received ${typeof images.domains}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`);
}
// static images are automatically prefixed with assetPrefix
// so we need to ensure _next/image allows downloading from
// this resource
if ((_config_assetPrefix = config.assetPrefix) == null ? void 0 : _config_assetPrefix.startsWith("http")) {
images.domains.push(new URL(config.assetPrefix).hostname);
}
}
if (!images.loader) {
images.loader = "default";
}
if (images.loader !== "default" && images.loader !== "custom" && images.path === imageConfigDefault.path) {
throw new Error(`Specified images.loader property (${images.loader}) also requires images.path property to be assigned to a URL prefix.\nSee more info here: https://nextjs.org/docs/api-reference/next/legacy/image#loader-configuration`);
}
if (images.path === imageConfigDefault.path && result.basePath && !pathHasPrefix(images.path, result.basePath)) {
images.path = `${result.basePath}${images.path}`;
}
// Append trailing slash for non-default loaders and when trailingSlash is set
if (images.path && !images.path.endsWith("/") && (images.loader !== "default" || result.trailingSlash)) {
images.path += "/";
}
if (images.loaderFile) {
if (images.loader !== "default" && images.loader !== "custom") {
throw new Error(`Specified images.loader property (${images.loader}) cannot be used with images.loaderFile property. Please set images.loader to "custom".`);
}
const absolutePath = join(dir, images.loaderFile);
if (!existsSync(absolutePath)) {
throw new Error(`Specified images.loaderFile does not exist at "${absolutePath}".`);
}
images.loaderFile = absolutePath;
}
}
// TODO: remove this in next major or minor version after 13.5
warnOptionHasBeenDeprecated(result, "experimental.appDir", "App router is available by default now, `experimental.appDir` option can be safely removed.", silent);
warnOptionHasBeenMovedOutOfExperimental(result, "relay", "compiler.relay", configFileName, silent);
warnOptionHasBeenMovedOutOfExperimental(result, "styledComponents", "compiler.styledComponents", configFileName, silent);
warnOptionHasBeenMovedOutOfExperimental(result, "emotion", "compiler.emotion", configFileName, silent);
warnOptionHasBeenMovedOutOfExperimental(result, "reactRemoveProperties", "compiler.reactRemoveProperties", configFileName, silent);
warnOptionHasBeenMovedOutOfExperimental(result, "removeConsole", "compiler.removeConsole", configFileName, silent);
if (typeof ((_result_experimental1 = result.experimental) == null ? void 0 : _result_experimental1.swcMinifyDebugOptions) !== "undefined") {
if (!silent) {
Log.warn("SWC minify debug option is not supported anymore, please remove it from your config.");
}
}
if (result.experimental.outputStandalone) {
if (!silent) {
Log.warn(`experimental.outputStandalone has been renamed to "output: 'standalone'", please move the config.`);
}
result.output = "standalone";
}
if (typeof ((_result_experimental2 = result.experimental) == null ? void 0 : _result_experimental2.serverActionsBodySizeLimit) !== "undefined") {
const value = parseInt(result.experimental.serverActionsBodySizeLimit.toString());
if (isNaN(value) || value < 1) {
throw new Error("Server Actions Size Limit must be a valid number or filesize format lager than 1MB: https://nextjs.org/docs/app/api-reference/server-actions#size-limitation");
}
}
warnOptionHasBeenMovedOutOfExperimental(result, "transpilePackages", "transpilePackages", configFileName, silent);
warnOptionHasBeenMovedOutOfExperimental(result, "skipMiddlewareUrlNormalize", "skipMiddlewareUrlNormalize", configFileName, silent);
warnOptionHasBeenMovedOutOfExperimental(result, "skipTrailingSlashRedirect", "skipTrailingSlashRedirect", configFileName, silent);
if (((_result_experimental3 = result.experimental) == null ? void 0 : _result_experimental3.outputFileTracingRoot) && !isAbsolute(result.experimental.outputFileTracingRoot)) {
result.experimental.outputFileTracingRoot = resolve(result.experimental.outputFileTracingRoot);
if (!silent) {
Log.warn(`experimental.outputFileTracingRoot should be absolute, using: ${result.experimental.outputFileTracingRoot}`);
}
}
// only leverage deploymentId
if (((_result_experimental4 = result.experimental) == null ? void 0 : _result_experimental4.useDeploymentId) && process.env.NEXT_DEPLOYMENT_ID) {
if (!result.experimental) {
result.experimental = {};
}
result.experimental.deploymentId = process.env.NEXT_DEPLOYMENT_ID;
}
// use the closest lockfile as tracing root
if (!((_result_experimental5 = result.experimental) == null ? void 0 : _result_experimental5.outputFileTracingRoot)) {
let rootDir = findRootDir(dir);
if (rootDir) {
if (!result.experimental) {
result.experimental = {};
}
if (!defaultConfig.experimental) {
defaultConfig.experimental = {};
}
result.experimental.outputFileTracingRoot = rootDir;
defaultConfig.experimental.outputFileTracingRoot = result.experimental.outputFileTracingRoot;
}
}
if (result.output === "standalone" && !result.outputFileTracing) {
if (!silent) {
Log.warn(`"output: 'standalone'" requires outputFileTracing not be disabled please enable it to leverage the standalone build`);
}
result.output = undefined;
}
setHttpClientAndAgentOptions(result || defaultConfig);
if (result.i18n) {
const { i18n } = result;
const i18nType = typeof i18n;
if (i18nType !== "object") {
throw new Error(`Specified i18n should be an object received ${i18nType}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
if (!Array.isArray(i18n.locales)) {
throw new Error(`Specified i18n.locales should be an Array received ${typeof i18n.locales}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
if (i18n.locales.length > 100 && !silent) {
Log.warn(`Received ${i18n.locales.length} i18n.locales items which exceeds the recommended max of 100.\nSee more info here: https://nextjs.org/docs/advanced-features/i18n-routing#how-does-this-work-with-static-generation`);
}
const defaultLocaleType = typeof i18n.defaultLocale;
if (!i18n.defaultLocale || defaultLocaleType !== "string") {
throw new Error(`Specified i18n.defaultLocale should be a string.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
if (typeof i18n.domains !== "undefined" && !Array.isArray(i18n.domains)) {
throw new Error(`Specified i18n.domains must be an array of domain objects e.g. [ { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] } ] received ${typeof i18n.domains}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
if (i18n.domains) {
const invalidDomainItems = i18n.domains.filter((item)=>{
var _i18n_domains;
if (!item || typeof item !== "object") return true;
if (!item.defaultLocale) return true;
if (!item.domain || typeof item.domain !== "string") return true;
if (item.domain.includes(":")) {
console.warn(`i18n domain: "${item.domain}" is invalid it should be a valid domain without protocol (https://) or port (:3000) e.g. example.vercel.sh`);
return true;
}
const defaultLocaleDuplicate = (_i18n_domains = i18n.domains) == null ? void 0 : _i18n_domains.find((altItem)=>altItem.defaultLocale === item.defaultLocale && altItem.domain !== item.domain);
if (!silent && defaultLocaleDuplicate) {
console.warn(`Both ${item.domain} and ${defaultLocaleDuplicate.domain} configured the defaultLocale ${item.defaultLocale} but only one can. Change one item's default locale to continue`);
return true;
}
let hasInvalidLocale = false;
if (Array.isArray(item.locales)) {
for (const locale of item.locales){
if (typeof locale !== "string") hasInvalidLocale = true;
for (const domainItem of i18n.domains || []){
if (domainItem === item) continue;
if (domainItem.locales && domainItem.locales.includes(locale)) {
console.warn(`Both ${item.domain} and ${domainItem.domain} configured the locale (${locale}) but only one can. Remove it from one i18n.domains config to continue`);
hasInvalidLocale = true;
break;
}
}
}
}
return hasInvalidLocale;
});
if (invalidDomainItems.length > 0) {
throw new Error(`Invalid i18n.domains values:\n${invalidDomainItems.map((item)=>JSON.stringify(item)).join("\n")}\n\ndomains value must follow format { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] }.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
}
if (!Array.isArray(i18n.locales)) {
throw new Error(`Specified i18n.locales must be an array of locale strings e.g. ["en-US", "nl-NL"] received ${typeof i18n.locales}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
const invalidLocales = i18n.locales.filter((locale)=>typeof locale !== "string");
if (invalidLocales.length > 0) {
throw new Error(`Specified i18n.locales contains invalid values (${invalidLocales.map(String).join(", ")}), locales must be valid locale tags provided as strings e.g. "en-US".\n` + `See here for list of valid language sub-tags: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry`);
}
if (!i18n.locales.includes(i18n.defaultLocale)) {
throw new Error(`Specified i18n.defaultLocale should be included in i18n.locales.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
const normalizedLocales = new Set();
const duplicateLocales = new Set();
i18n.locales.forEach((locale)=>{
const localeLower = locale.toLowerCase();
if (normalizedLocales.has(localeLower)) {
duplicateLocales.add(locale);
}
normalizedLocales.add(localeLower);
});
if (duplicateLocales.size > 0) {
throw new Error(`Specified i18n.locales contains the following duplicate locales:\n` + `${[
...duplicateLocales
].join(", ")}\n` + `Each locale should be listed only once.\n` + `See more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
// make sure default Locale is at the front
i18n.locales = [
i18n.defaultLocale,
...i18n.locales.filter((locale)=>locale !== i18n.defaultLocale)
];
const localeDetectionType = typeof i18n.localeDetection;
if (localeDetectionType !== "boolean" && localeDetectionType !== "undefined") {
throw new Error(`Specified i18n.localeDetection should be undefined or a boolean received ${localeDetectionType}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`);
}
}
if ((_result_devIndicators = result.devIndicators) == null ? void 0 : _result_devIndicators.buildActivityPosition) {
const { buildActivityPosition } = result.devIndicators;
const allowedValues = [
"top-left",
"top-right",
"bottom-left",
"bottom-right"
];
if (!allowedValues.includes(buildActivityPosition)) {
throw new Error(`Invalid "devIndicator.buildActivityPosition" provided, expected one of ${allowedValues.join(", ")}, received ${buildActivityPosition}`);
}
}
const userProvidedModularizeImports = result.modularizeImports;
// Unfortunately these packages end up re-exporting 10600 modules, for example: https://unpkg.com/browse/@mui/icons-material@5.11.16/esm/index.js.
// Leveraging modularizeImports tremendously reduces compile times for these.
result.modularizeImports = {
...userProvidedModularizeImports || {},
// This is intentionally added after the user-provided modularizeImports config.
"@mui/icons-material": {
transform: "@mui/icons-material/{{member}}"
},
"date-fns": {
transform: "date-fns/{{member}}"
},
lodash: {
transform: "lodash/{{member}}"
},
"lodash-es": {
transform: "lodash-es/{{member}}"
},
ramda: {
transform: "ramda/es/{{member}}"
},
"react-bootstrap": {
transform: {
useAccordionButton: "modularize-import-loader?name=useAccordionButton&from=named&as=default!react-bootstrap/AccordionButton",
"*": "react-bootstrap/{{member}}"
}
},
antd: {
transform: "antd/lib/{{kebabCase member}}"
},
ahooks: {
transform: {
createUpdateEffect: "modularize-import-loader?name=createUpdateEffect&from=named&as=default!ahooks/es/createUpdateEffect",
"*": "ahooks/es/{{member}}"
}
},
"@ant-design/icons": {
transform: {
IconProvider: "modularize-import-loader?name=IconProvider&from=named&as=default!@ant-design/icons",
createFromIconfontCN: "@ant-design/icons/es/components/IconFont",
getTwoToneColor: "modularize-import-loader?name=getTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor",
setTwoToneColor: "modularize-import-loader?name=setTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor",
"*": "@ant-design/icons/lib/icons/{{member}}"
}
},
"next/server": {
transform: "next/dist/server/web/exports/{{ kebabCase member }}"
}
};
const userProvidedOptimizePackageImports = ((_result_experimental6 = result.experimental) == null ? void 0 : _result_experimental6.optimizePackageImports) || [];
if (!result.experimental) {
result.experimental = {};
}
result.experimental.optimizePackageImports = [
...new Set([
...userProvidedOptimizePackageImports,
"lucide-react",
"@headlessui/react",
"@headlessui-float/react",
"@heroicons/react/20/solid",
"@heroicons/react/24/solid",
"@heroicons/react/24/outline",
"@visx/visx",
"@tremor/react",
"rxjs",
"@mui/material",
"recharts",
"@material-ui/core",
"react-use",
"@material-ui/icons",
"@tabler/icons-react",
"mui-core",
// We don't support wildcard imports for these configs, e.g. `react-icons/*`
// so we need to add them manually.
// In the future, we should consider automatically detecting packages that
// need to be optimized.
"react-icons/ai",
"react-icons/bi",
"react-icons/bs",
"react-icons/cg",
"react-icons/ci",
"react-icons/di",
"react-icons/fa",
"react-icons/fa6",
"react-icons/fc",
"react-icons/fi",
"react-icons/gi",
"react-icons/go",
"react-icons/gr",
"react-icons/hi",
"react-icons/hi2",
"react-icons/im",
"react-icons/io",
"react-icons/io5",
"react-icons/lia",
"react-icons/lib",
"react-icons/lu",
"react-icons/md",
"react-icons/pi",
"react-icons/ri",
"react-icons/rx",
"react-icons/si",
"react-icons/sl",
"react-icons/tb",
"react-icons/tfi",
"react-icons/ti",
"react-icons/vsc",
"react-icons/wi"
])
];
return result;
}
export default async function loadConfig(phase, dir, { customConfig, rawConfig, silent = true, onLoadUserConfig } = {}) {
if (!process.env.__NEXT_PRIVATE_RENDER_WORKER) {
try {
loadWebpackHook();
} catch (err) {
// this can fail in standalone mode as the files
// aren't traced/included
if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
throw err;
}
}
}
if (process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
return JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG);
}
// For the render worker, we directly return the serialized config from the
// parent worker (router worker) to avoid loading it again.
// This is because loading the config might be expensive especiall when people
// have Webpack plugins added.
// Because of this change, unserializable fields like `.webpack` won't be
// existing here but the render worker shouldn't use these as well.
if (process.env.__NEXT_PRIVATE_RENDER_WORKER_CONFIG) {
return JSON.parse(process.env.__NEXT_PRIVATE_RENDER_WORKER_CONFIG);
}
const curLog = silent ? {
warn: ()=>{},
info: ()=>{},
error: ()=>{}
} : Log;
loadEnvConfig(dir, phase === PHASE_DEVELOPMENT_SERVER, curLog);
let configFileName = "next.config.js";
if (customConfig) {
return assignDefaults(dir, {
configOrigin: "server",
configFileName,
...customConfig
}, silent);
}
const path = await findUp(CONFIG_FILES, {
cwd: dir
});
// If config file was found
if (path == null ? void 0 : path.length) {
var _userConfig_amp, _userConfig_experimental_turbo, _userConfig_experimental, _userConfig_experimental_turbo1, _userConfig_experimental1;
configFileName = basename(path);
let userConfigModule;
try {
const envBefore = Object.assign({}, process.env);
// `import()` expects url-encoded strings, so the path must be properly
// escaped and (especially on Windows) absolute paths must pe prefixed
// with the `file://` protocol
if (process.env.__NEXT_TEST_MODE === "jest") {
// dynamic import does not currently work inside of vm which
// jest relies on so we fall back to require for this case
// https://github.com/nodejs/node/issues/35889
userConfigModule = require(path);
} else {
userConfigModule = await import(pathToFileURL(path).href);
}
const newEnv = {};
for (const key of Object.keys(process.env)){
if (envBefore[key] !== process.env[key]) {
newEnv[key] = process.env[key];
}
}
updateInitialEnv(newEnv);
if (rawConfig) {
return userConfigModule;
}
} catch (err) {
curLog.error(`Failed to load ${configFileName}, see more info here https://nextjs.org/docs/messages/next-config-error`);
throw err;
}
const userConfig = await normalizeConfig(phase, userConfigModule.default || userConfigModule);
const validateResult = validateConfig(userConfig);
if (validateResult.errors) {
// Only load @segment/ajv-human-errors when invalid config is detected
const { AggregateAjvError } = require("next/dist/compiled/@segment/ajv-human-errors");
const aggregatedAjvErrors = new AggregateAjvError(validateResult.errors, {
fieldLabels: "js"
});
let shouldExit = false;
const messages = [
`Invalid ${configFileName} options detected: `
];
for (const error of aggregatedAjvErrors){
messages.push(` ${error.message}`);
if (error.message.startsWith("The value at .images.")) {
shouldExit = true;
}
}
messages.push("See more info here: https://nextjs.org/docs/messages/invalid-next-config");
if (shouldExit) {
for (const message of messages){
console.error(message);
}
await flushAndExit(1);
} else {
for (const message of messages){
curLog.warn(message);
}
}
}
if (userConfig.target && userConfig.target !== "server") {
throw new Error(`The "target" property is no longer supported in ${configFileName}.\n` + "See more info here https://nextjs.org/docs/messages/deprecated-target-config");
}
if ((_userConfig_amp = userConfig.amp) == null ? void 0 : _userConfig_amp.canonicalBase) {
const { canonicalBase } = userConfig.amp || {};
userConfig.amp = userConfig.amp || {};
userConfig.amp.canonicalBase = (canonicalBase.endsWith("/") ? canonicalBase.slice(0, -1) : canonicalBase) || "";
}
if (((_userConfig_experimental = userConfig.experimental) == null ? void 0 : (_userConfig_experimental_turbo = _userConfig_experimental.turbo) == null ? void 0 : _userConfig_experimental_turbo.loaders) && !((_userConfig_experimental1 = userConfig.experimental) == null ? void 0 : (_userConfig_experimental_turbo1 = _userConfig_experimental1.turbo) == null ? void 0 : _userConfig_experimental_turbo1.rules)) {
curLog.warn("experimental.turbo.loaders is now deprecated. Please update next.config.js to use experimental.turbo.rules as soon as possible.\n" + "The new option is similar, but the key should be a glob instead of an extension.\n" + 'Example: loaders: { ".mdx": ["mdx-loader"] } -> rules: { "*.mdx": ["mdx-loader"] }" }\n' + "See more info here https://nextjs.org/docs/app/api-reference/next-config-js/turbo");
const rules = {};
for (const [ext, loaders] of Object.entries(userConfig.experimental.turbo.loaders)){
rules["*" + ext] = loaders;
}
userConfig.experimental.turbo.rules = rules;
}
onLoadUserConfig == null ? void 0 : onLoadUserConfig(userConfig);
const completeConfig = assignDefaults(dir, {
configOrigin: relative(dir, path),
configFile: path,
configFileName,
...userConfig
}, silent);
return completeConfig;
} else {
const configBaseName = basename(CONFIG_FILES[0], extname(CONFIG_FILES[0]));
const nonJsPath = findUp.sync([
`${configBaseName}.jsx`,
`${configBaseName}.ts`,
`${configBaseName}.tsx`,
`${configBaseName}.json`
], {
cwd: dir
});
if (nonJsPath == null ? void 0 : nonJsPath.length) {
throw new Error(`Configuring Next.js via '${basename(nonJsPath)}' is not supported. Please replace the file with 'next.config.js' or 'next.config.mjs'.`);
}
}
// always call assignDefaults to ensure settings like
// reactRoot can be updated correctly even with no next.config.js
const completeConfig = assignDefaults(dir, defaultConfig, silent);
completeConfig.configFileName = configFileName;
setHttpClientAndAgentOptions(completeConfig);
return completeConfig;
}
export function getEnabledExperimentalFeatures(userNextConfigExperimental) {
const enabledExperiments = [];
if (!userNextConfigExperimental) return enabledExperiments;
// defaultConfig.experimental is predefined and will never be undefined
// This is only a type guard for the typescript
if (defaultConfig.experimental) {
for (const featureName of Object.keys(userNextConfigExperimental)){
if (userNextConfigExperimental[featureName] !== defaultConfig.experimental[featureName]) {
enabledExperiments.push(featureName);
}
}
}
return enabledExperiments;
}
//# sourceMappingURL=config.js.map

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

File diff suppressed because one or more lines are too long

43
node_modules/next/dist/esm/server/crypto-utils.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
import crypto from "crypto";
// Background:
// https://security.stackexchange.com/questions/184305/why-would-i-ever-use-aes-256-cbc-if-aes-256-gcm-is-more-secure
const CIPHER_ALGORITHM = `aes-256-gcm`, CIPHER_KEY_LENGTH = 32, CIPHER_IV_LENGTH = 16, CIPHER_TAG_LENGTH = 16, CIPHER_SALT_LENGTH = 64;
const PBKDF2_ITERATIONS = 100000 // https://support.1password.com/pbkdf2/
;
export function encryptWithSecret(secret, data) {
const iv = crypto.randomBytes(CIPHER_IV_LENGTH);
const salt = crypto.randomBytes(CIPHER_SALT_LENGTH);
// https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest
const key = crypto.pbkdf2Sync(secret, salt, PBKDF2_ITERATIONS, CIPHER_KEY_LENGTH, `sha512`);
const cipher = crypto.createCipheriv(CIPHER_ALGORITHM, key, iv);
const encrypted = Buffer.concat([
cipher.update(data, `utf8`),
cipher.final()
]);
// https://nodejs.org/api/crypto.html#crypto_cipher_getauthtag
const tag = cipher.getAuthTag();
return Buffer.concat([
// Data as required by:
// Salt for Key: https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest
// IV: https://nodejs.org/api/crypto.html#crypto_class_decipher
// Tag: https://nodejs.org/api/crypto.html#crypto_decipher_setauthtag_buffer
salt,
iv,
tag,
encrypted
]).toString(`hex`);
}
export function decryptWithSecret(secret, encryptedData) {
const buffer = Buffer.from(encryptedData, `hex`);
const salt = buffer.slice(0, CIPHER_SALT_LENGTH);
const iv = buffer.slice(CIPHER_SALT_LENGTH, CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH);
const tag = buffer.slice(CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH, CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH + CIPHER_TAG_LENGTH);
const encrypted = buffer.slice(CIPHER_SALT_LENGTH + CIPHER_IV_LENGTH + CIPHER_TAG_LENGTH);
// https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest
const key = crypto.pbkdf2Sync(secret, salt, PBKDF2_ITERATIONS, CIPHER_KEY_LENGTH, `sha512`);
const decipher = crypto.createDecipheriv(CIPHER_ALGORITHM, key, iv);
decipher.setAuthTag(tag);
return decipher.update(encrypted) + decipher.final(`utf8`);
}
//# sourceMappingURL=crypto-utils.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/server/crypto-utils.ts"],"names":["crypto","CIPHER_ALGORITHM","CIPHER_KEY_LENGTH","CIPHER_IV_LENGTH","CIPHER_TAG_LENGTH","CIPHER_SALT_LENGTH","PBKDF2_ITERATIONS","encryptWithSecret","secret","data","iv","randomBytes","salt","key","pbkdf2Sync","cipher","createCipheriv","encrypted","Buffer","concat","update","final","tag","getAuthTag","toString","decryptWithSecret","encryptedData","buffer","from","slice","decipher","createDecipheriv","setAuthTag"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAE3B,cAAc;AACd,qHAAqH;AAErH,MAAMC,mBAAmB,CAAC,WAAW,CAAC,EACpCC,oBAAoB,IACpBC,mBAAmB,IACnBC,oBAAoB,IACpBC,qBAAqB;AAEvB,MAAMC,oBAAoB,OAAQ,wCAAwC;;AAE1E,OAAO,SAASC,kBAAkBC,MAAc,EAAEC,IAAY;IAC5D,MAAMC,KAAKV,OAAOW,WAAW,CAACR;IAC9B,MAAMS,OAAOZ,OAAOW,WAAW,CAACN;IAEhC,qGAAqG;IACrG,MAAMQ,MAAMb,OAAOc,UAAU,CAC3BN,QACAI,MACAN,mBACAJ,mBACA,CAAC,MAAM,CAAC;IAGV,MAAMa,SAASf,OAAOgB,cAAc,CAACf,kBAAkBY,KAAKH;IAC5D,MAAMO,YAAYC,OAAOC,MAAM,CAAC;QAACJ,OAAOK,MAAM,CAACX,MAAM,CAAC,IAAI,CAAC;QAAGM,OAAOM,KAAK;KAAG;IAE7E,8DAA8D;IAC9D,MAAMC,MAAMP,OAAOQ,UAAU;IAE7B,OAAOL,OAAOC,MAAM,CAAC;QACnB,uBAAuB;QACvB,mHAAmH;QACnH,+DAA+D;QAC/D,4EAA4E;QAC5EP;QACAF;QACAY;QACAL;KACD,EAAEO,QAAQ,CAAC,CAAC,GAAG,CAAC;AACnB;AAEA,OAAO,SAASC,kBACdjB,MAAc,EACdkB,aAAqB;IAErB,MAAMC,SAAST,OAAOU,IAAI,CAACF,eAAe,CAAC,GAAG,CAAC;IAE/C,MAAMd,OAAOe,OAAOE,KAAK,CAAC,GAAGxB;IAC7B,MAAMK,KAAKiB,OAAOE,KAAK,CACrBxB,oBACAA,qBAAqBF;IAEvB,MAAMmB,MAAMK,OAAOE,KAAK,CACtBxB,qBAAqBF,kBACrBE,qBAAqBF,mBAAmBC;IAE1C,MAAMa,YAAYU,OAAOE,KAAK,CAC5BxB,qBAAqBF,mBAAmBC;IAG1C,qGAAqG;IACrG,MAAMS,MAAMb,OAAOc,UAAU,CAC3BN,QACAI,MACAN,mBACAJ,mBACA,CAAC,MAAM,CAAC;IAGV,MAAM4B,WAAW9B,OAAO+B,gBAAgB,CAAC9B,kBAAkBY,KAAKH;IAChEoB,SAASE,UAAU,CAACV;IAEpB,OAAOQ,SAASV,MAAM,CAACH,aAAaa,SAAST,KAAK,CAAC,CAAC,IAAI,CAAC;AAC3D"}

204
node_modules/next/dist/esm/server/dev/hot-middleware.js generated vendored Normal file
View File

@@ -0,0 +1,204 @@
// Based on https://github.com/webpack-contrib/webpack-hot-middleware/blob/9708d781ae0e46179cf8ea1a94719de4679aaf53/middleware.js
// Included License below
// Copyright JS Foundation and other contributors
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import { isMiddlewareFilename } from "../../build/utils";
import { HMR_ACTIONS_SENT_TO_BROWSER } from "./hot-reloader-types";
function isMiddlewareStats(stats) {
for (const key of stats.compilation.entrypoints.keys()){
if (isMiddlewareFilename(key)) {
return true;
}
}
return false;
}
function statsToJson(stats) {
if (!stats) return {};
return stats.toJson({
all: false,
errors: true,
hash: true,
warnings: true
});
}
function getStatsForSyncEvent(clientStats, serverStats) {
if (!clientStats) return serverStats == null ? void 0 : serverStats.stats;
if (!serverStats) return clientStats == null ? void 0 : clientStats.stats;
// Prefer the server compiler stats if it has errors.
// Otherwise we may end up in a state where the client compilation is the latest but without errors.
// This causes the error overlay to not display the build error.
if (serverStats.stats.hasErrors()) {
return serverStats.stats;
}
// Return the latest stats
return serverStats.ts > clientStats.ts ? serverStats.stats : clientStats.stats;
}
class EventStream {
constructor(){
this.clients = new Set();
}
everyClient(fn) {
for (const client of this.clients){
fn(client);
}
}
close() {
this.everyClient((client)=>{
client.close();
});
this.clients.clear();
}
handler(client) {
this.clients.add(client);
client.addEventListener("close", ()=>{
this.clients.delete(client);
});
}
publish(payload) {
this.everyClient((client)=>{
client.send(JSON.stringify(payload));
});
}
}
export class WebpackHotMiddleware {
constructor(compilers, versionInfo){
this.onClientInvalid = ()=>{
var _this_serverLatestStats;
if (this.closed || ((_this_serverLatestStats = this.serverLatestStats) == null ? void 0 : _this_serverLatestStats.stats.hasErrors())) return;
this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILDING
});
};
this.onClientDone = (statsResult)=>{
var _this_serverLatestStats;
this.clientLatestStats = {
ts: Date.now(),
stats: statsResult
};
if (this.closed || ((_this_serverLatestStats = this.serverLatestStats) == null ? void 0 : _this_serverLatestStats.stats.hasErrors())) return;
this.publishStats(statsResult);
};
this.onServerInvalid = ()=>{
var _this_serverLatestStats, _this_clientLatestStats;
if (!((_this_serverLatestStats = this.serverLatestStats) == null ? void 0 : _this_serverLatestStats.stats.hasErrors())) return;
this.serverLatestStats = null;
if ((_this_clientLatestStats = this.clientLatestStats) == null ? void 0 : _this_clientLatestStats.stats) {
this.publishStats(this.clientLatestStats.stats);
}
};
this.onServerDone = (statsResult)=>{
if (this.closed) return;
if (statsResult.hasErrors()) {
this.serverLatestStats = {
ts: Date.now(),
stats: statsResult
};
this.publishStats(statsResult);
}
};
this.onEdgeServerInvalid = ()=>{
var _this_middlewareLatestStats, _this_clientLatestStats;
if (!((_this_middlewareLatestStats = this.middlewareLatestStats) == null ? void 0 : _this_middlewareLatestStats.stats.hasErrors())) return;
this.middlewareLatestStats = null;
if ((_this_clientLatestStats = this.clientLatestStats) == null ? void 0 : _this_clientLatestStats.stats) {
this.publishStats(this.clientLatestStats.stats);
}
};
this.onEdgeServerDone = (statsResult)=>{
if (!isMiddlewareStats(statsResult)) {
this.onServerDone(statsResult);
return;
}
if (statsResult.hasErrors()) {
this.middlewareLatestStats = {
ts: Date.now(),
stats: statsResult
};
this.publishStats(statsResult);
}
};
/**
* To sync we use the most recent stats but also we append middleware
* errors. This is because it is possible that middleware fails to compile
* and we still want to show the client overlay with the error while
* the error page should be rendered just fine.
*/ this.onHMR = (client)=>{
if (this.closed) return;
this.eventStream.handler(client);
const syncStats = getStatsForSyncEvent(this.clientLatestStats, this.serverLatestStats);
if (syncStats) {
var _this_middlewareLatestStats;
const stats = statsToJson(syncStats);
const middlewareStats = statsToJson((_this_middlewareLatestStats = this.middlewareLatestStats) == null ? void 0 : _this_middlewareLatestStats.stats);
this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.SYNC,
hash: stats.hash,
errors: [
...stats.errors || [],
...middlewareStats.errors || []
],
warnings: [
...stats.warnings || [],
...middlewareStats.warnings || []
],
versionInfo: this.versionInfo
});
}
};
this.publishStats = (statsResult)=>{
const stats = statsResult.toJson({
all: false,
hash: true,
warnings: true,
errors: true,
moduleTrace: true
});
this.publish({
action: HMR_ACTIONS_SENT_TO_BROWSER.BUILT,
hash: stats.hash,
warnings: stats.warnings || [],
errors: stats.errors || []
});
};
this.publish = (payload)=>{
if (this.closed) return;
this.eventStream.publish(payload);
};
this.close = ()=>{
if (this.closed) return;
// Can't remove compiler plugins, so we just set a flag and noop if closed
// https://github.com/webpack/tapable/issues/32#issuecomment-350644466
this.closed = true;
this.eventStream.close();
};
this.eventStream = new EventStream();
this.clientLatestStats = null;
this.middlewareLatestStats = null;
this.serverLatestStats = null;
this.closed = false;
this.versionInfo = versionInfo;
compilers[0].hooks.invalid.tap("webpack-hot-middleware", this.onClientInvalid);
compilers[0].hooks.done.tap("webpack-hot-middleware", this.onClientDone);
compilers[1].hooks.invalid.tap("webpack-hot-middleware", this.onServerInvalid);
compilers[1].hooks.done.tap("webpack-hot-middleware", this.onServerDone);
compilers[2].hooks.done.tap("webpack-hot-middleware", this.onEdgeServerDone);
compilers[2].hooks.invalid.tap("webpack-hot-middleware", this.onEdgeServerInvalid);
}
}
//# sourceMappingURL=hot-middleware.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,18 @@
export var HMR_ACTIONS_SENT_TO_BROWSER;
(function(HMR_ACTIONS_SENT_TO_BROWSER) {
HMR_ACTIONS_SENT_TO_BROWSER["ADDED_PAGE"] = "addedPage";
HMR_ACTIONS_SENT_TO_BROWSER["REMOVED_PAGE"] = "removedPage";
HMR_ACTIONS_SENT_TO_BROWSER["RELOAD_PAGE"] = "reloadPage";
HMR_ACTIONS_SENT_TO_BROWSER["SERVER_COMPONENT_CHANGES"] = "serverComponentChanges";
HMR_ACTIONS_SENT_TO_BROWSER["MIDDLEWARE_CHANGES"] = "middlewareChanges";
HMR_ACTIONS_SENT_TO_BROWSER["SERVER_ONLY_CHANGES"] = "serverOnlyChanges";
HMR_ACTIONS_SENT_TO_BROWSER["SYNC"] = "sync";
HMR_ACTIONS_SENT_TO_BROWSER["BUILT"] = "built";
HMR_ACTIONS_SENT_TO_BROWSER["BUILDING"] = "building";
HMR_ACTIONS_SENT_TO_BROWSER["DEV_PAGES_MANIFEST_UPDATE"] = "devPagesManifestUpdate";
HMR_ACTIONS_SENT_TO_BROWSER["TURBOPACK_MESSAGE"] = "turbopack-message";
HMR_ACTIONS_SENT_TO_BROWSER["SERVER_ERROR"] = "serverError";
HMR_ACTIONS_SENT_TO_BROWSER["TURBOPACK_CONNECTED"] = "turbopack-connected";
})(HMR_ACTIONS_SENT_TO_BROWSER || (HMR_ACTIONS_SENT_TO_BROWSER = {}));
//# sourceMappingURL=hot-reloader-types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/hot-reloader-types.ts"],"names":["HMR_ACTIONS_SENT_TO_BROWSER","ADDED_PAGE","REMOVED_PAGE","RELOAD_PAGE","SERVER_COMPONENT_CHANGES","MIDDLEWARE_CHANGES","SERVER_ONLY_CHANGES","SYNC","BUILT","BUILDING","DEV_PAGES_MANIFEST_UPDATE","TURBOPACK_MESSAGE","SERVER_ERROR","TURBOPACK_CONNECTED"],"mappings":"WASO;UAAWA,2BAA2B;IAA3BA,4BAChBC,gBAAa;IADGD,4BAEhBE,kBAAe;IAFCF,4BAGhBG,iBAAc;IAHEH,4BAIhBI,8BAA2B;IAJXJ,4BAKhBK,wBAAqB;IALLL,4BAMhBM,yBAAsB;IANNN,4BAOhBO,UAAO;IAPSP,4BAQhBQ,WAAQ;IARQR,4BAShBS,cAAW;IATKT,4BAUhBU,+BAA4B;IAVZV,4BAWhBW,uBAAoB;IAXJX,4BAYhBY,kBAAe;IAZCZ,4BAahBa,yBAAsB;GAbNb,gCAAAA"}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
import isError from "../../lib/is-error";
import * as Log from "../../build/output/log";
export function logAppDirError(err) {
if (isError(err) && (err == null ? void 0 : err.stack)) {
const cleanedStack = err.stack.split("\n").map((line)=>// Remove 'webpack-internal:' noise from the path
line.replace(/(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, ""));
const filteredStack = cleanedStack// Only display stack frames from the user's code
.filter((line)=>!/next[\\/]dist[\\/]compiled/.test(line) && !/node_modules[\\/]/.test(line) && !/node:internal[\\/]/.test(line));
if (filteredStack.length === 1) {
// This is an error that happened outside of user code, keep full stack
Log.error(`Internal error: ${cleanedStack.join("\n")}`);
} else {
Log.error(filteredStack.join("\n"));
}
if (typeof err.digest !== "undefined") {
console.error(`digest: ${JSON.stringify(err.digest)}`);
}
} else {
Log.error(err);
}
}
//# sourceMappingURL=log-app-dir-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/log-app-dir-error.ts"],"names":["isError","Log","logAppDirError","err","stack","cleanedStack","split","map","line","replace","filteredStack","filter","test","length","error","join","digest","console","JSON","stringify"],"mappings":"AAAA,OAAOA,aAAa,qBAAoB;AACxC,YAAYC,SAAS,yBAAwB;AAE7C,OAAO,SAASC,eAAeC,GAAQ;IACrC,IAAIH,QAAQG,SAAQA,uBAAAA,IAAKC,KAAK,GAAE;QAC9B,MAAMC,eAAeF,IAAIC,KAAK,CAACE,KAAK,CAAC,MAAMC,GAAG,CAAC,CAACC,OAC9C,iDAAiD;YACjDA,KAAKC,OAAO,CAAC,kDAAkD;QAEjE,MAAMC,gBAAgBL,YACpB,iDAAiD;SAChDM,MAAM,CACL,CAACH,OACC,CAAC,6BAA6BI,IAAI,CAACJ,SACnC,CAAC,oBAAoBI,IAAI,CAACJ,SAC1B,CAAC,qBAAqBI,IAAI,CAACJ;QAEjC,IAAIE,cAAcG,MAAM,KAAK,GAAG;YAC9B,uEAAuE;YACvEZ,IAAIa,KAAK,CAAC,CAAC,gBAAgB,EAAET,aAAaU,IAAI,CAAC,MAAM,CAAC;QACxD,OAAO;YACLd,IAAIa,KAAK,CAACJ,cAAcK,IAAI,CAAC;QAC/B;QACA,IAAI,OAAO,AAACZ,IAAYa,MAAM,KAAK,aAAa;YAC9CC,QAAQH,KAAK,CAAC,CAAC,QAAQ,EAAEI,KAAKC,SAAS,CAAC,AAAChB,IAAYa,MAAM,EAAE,CAAC;QAChE;IACF,OAAO;QACLf,IAAIa,KAAK,CAACX;IACZ;AACF"}

View File

@@ -0,0 +1,528 @@
import { Worker } from "next/dist/compiled/jest-worker";
import { join as pathJoin } from "path";
import { ampValidation } from "../../build/output";
import { INSTRUMENTATION_HOOK_FILENAME, PUBLIC_DIR_MIDDLEWARE_CONFLICT } from "../../lib/constants";
import { fileExists } from "../../lib/file-exists";
import { findPagesDir } from "../../lib/find-pages-dir";
import { PHASE_DEVELOPMENT_SERVER, PAGES_MANIFEST, APP_PATHS_MANIFEST } from "../../shared/lib/constants";
import Server, { WrappedBuildError } from "../next-server";
import { normalizePagePath } from "../../shared/lib/page-path/normalize-page-path";
import { pathHasPrefix } from "../../shared/lib/router/utils/path-has-prefix";
import { removePathPrefix } from "../../shared/lib/router/utils/remove-path-prefix";
import { Telemetry } from "../../telemetry/storage";
import { setGlobal } from "../../trace";
import { findPageFile } from "../lib/find-page-file";
import { getNodeOptionsWithoutInspect } from "../lib/utils";
import { withCoalescedInvoke } from "../../lib/coalesced-function";
import { loadDefaultErrorComponents } from "../load-default-error-components";
import { DecodeError, MiddlewareNotFoundError } from "../../shared/lib/utils";
import * as Log from "../../build/output/log";
import isError, { getProperError } from "../../lib/is-error";
import { isMiddlewareFile } from "../../build/utils";
import { formatServerError } from "../../lib/format-server-error";
import { DevRouteMatcherManager } from "../future/route-matcher-managers/dev-route-matcher-manager";
import { DevPagesRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-pages-route-matcher-provider";
import { DevPagesAPIRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-pages-api-route-matcher-provider";
import { DevAppPageRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-app-page-route-matcher-provider";
import { DevAppRouteRouteMatcherProvider } from "../future/route-matcher-providers/dev/dev-app-route-route-matcher-provider";
import { NodeManifestLoader } from "../future/route-matcher-providers/helpers/manifest-loaders/node-manifest-loader";
import { BatchedFileReader } from "../future/route-matcher-providers/dev/helpers/file-reader/batched-file-reader";
import { DefaultFileReader } from "../future/route-matcher-providers/dev/helpers/file-reader/default-file-reader";
import { NextBuildContext } from "../../build/build-context";
import LRUCache from "next/dist/compiled/lru-cache";
import { getMiddlewareRouteMatcher } from "../../shared/lib/router/utils/middleware-route-matcher";
// Load ReactDevOverlay only when needed
let ReactDevOverlayImpl;
const ReactDevOverlay = (props)=>{
if (ReactDevOverlayImpl === undefined) {
ReactDevOverlayImpl = require("next/dist/compiled/@next/react-dev-overlay/dist/client").ReactDevOverlay;
}
return ReactDevOverlayImpl(props);
};
export default class DevServer extends Server {
invokeDevMethod({ method, args }) {
return global._nextDevHandlers[method](this.dir, ...args);
}
getStaticPathsWorker() {
const worker = new Worker(require.resolve("./static-paths-worker"), {
maxRetries: 1,
// For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.
// This helps reusing the memory a lot.
numWorkers: 1,
enableWorkerThreads: this.nextConfig.experimental.workerThreads,
forkOptions: {
env: {
...process.env,
// discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers
// would be started if user launch Next.js in debugging mode. The number of debuggers is linked to
// the number of workers Next.js tries to launch. The only worker users are interested in debugging
// is the main Next.js one
NODE_OPTIONS: getNodeOptionsWithoutInspect()
}
}
});
worker.getStdout().pipe(process.stdout);
worker.getStderr().pipe(process.stderr);
return worker;
}
constructor(options){
var _this_nextConfig_experimental_amp, _this_nextConfig_experimental;
try {
// Increase the number of stack frames on the server
Error.stackTraceLimit = 50;
} catch {}
super({
...options,
dev: true
});
this.originalFetch = global.fetch;
this.renderOpts.dev = true;
this.renderOpts.appDirDevErrorLogger = (err)=>this.logErrorWithOriginalStack(err, "app-dir");
this.renderOpts.ErrorDebug = ReactDevOverlay;
this.devReady = new Promise((resolve)=>{
this.setDevReady = resolve;
});
this.staticPathsCache = new LRUCache({
// 5MB
max: 5 * 1024 * 1024,
length (value) {
return JSON.stringify(value.staticPaths).length;
}
});
this.renderOpts.ampSkipValidation = ((_this_nextConfig_experimental = this.nextConfig.experimental) == null ? void 0 : (_this_nextConfig_experimental_amp = _this_nextConfig_experimental.amp) == null ? void 0 : _this_nextConfig_experimental_amp.skipValidation) ?? false;
this.renderOpts.ampValidator = (html, pathname)=>{
const validatorPath = this.nextConfig.experimental && this.nextConfig.experimental.amp && this.nextConfig.experimental.amp.validator;
const AmpHtmlValidator = require("next/dist/compiled/amphtml-validator");
return AmpHtmlValidator.getInstance(validatorPath).then((validator)=>{
const result = validator.validateString(html);
ampValidation(pathname, result.errors.filter((e)=>e.severity === "ERROR").filter((e)=>this._filterAmpDevelopmentScript(html, e)), result.errors.filter((e)=>e.severity !== "ERROR"));
});
};
const { pagesDir, appDir } = findPagesDir(this.dir);
this.pagesDir = pagesDir;
this.appDir = appDir;
}
getRouteMatchers() {
const { pagesDir, appDir } = findPagesDir(this.dir);
const ensurer = {
ensure: async (match)=>{
await this.ensurePage({
match,
page: match.definition.page,
clientOnly: false
});
}
};
const matchers = new DevRouteMatcherManager(super.getRouteMatchers(), ensurer, this.dir);
const extensions = this.nextConfig.pageExtensions;
const extensionsExpression = new RegExp(`\\.(?:${extensions.join("|")})$`);
// If the pages directory is available, then configure those matchers.
if (pagesDir) {
const fileReader = new BatchedFileReader(new DefaultFileReader({
// Only allow files that have the correct extensions.
pathnameFilter: (pathname)=>extensionsExpression.test(pathname)
}));
matchers.push(new DevPagesRouteMatcherProvider(pagesDir, extensions, fileReader, this.localeNormalizer));
matchers.push(new DevPagesAPIRouteMatcherProvider(pagesDir, extensions, fileReader, this.localeNormalizer));
}
if (appDir) {
// We create a new file reader for the app directory because we don't want
// to include any folders or files starting with an underscore. This will
// prevent the reader from wasting time reading files that we know we
// don't care about.
const fileReader = new BatchedFileReader(new DefaultFileReader({
// Ignore any directory prefixed with an underscore.
ignorePartFilter: (part)=>part.startsWith("_")
}));
matchers.push(new DevAppPageRouteMatcherProvider(appDir, extensions, fileReader));
matchers.push(new DevAppRouteRouteMatcherProvider(appDir, extensions, fileReader));
}
return matchers;
}
getBuildId() {
return "development";
}
async prepareImpl() {
setGlobal("distDir", this.distDir);
setGlobal("phase", PHASE_DEVELOPMENT_SERVER);
const telemetry = new Telemetry({
distDir: this.distDir
});
await super.prepareImpl();
await this.runInstrumentationHookIfAvailable();
await this.matchers.reload();
this.setDevReady();
// This is required by the tracing subsystem.
setGlobal("appDir", this.appDir);
setGlobal("pagesDir", this.pagesDir);
setGlobal("telemetry", telemetry);
process.on("unhandledRejection", (reason)=>{
this.logErrorWithOriginalStack(reason, "unhandledRejection").catch(()=>{});
});
process.on("uncaughtException", (err)=>{
this.logErrorWithOriginalStack(err, "uncaughtException").catch(()=>{});
});
}
async close() {}
async hasPage(pathname) {
let normalizedPath;
try {
normalizedPath = normalizePagePath(pathname);
} catch (err) {
console.error(err);
// if normalizing the page fails it means it isn't valid
// so it doesn't exist so don't throw and return false
// to ensure we return 404 instead of 500
return false;
}
if (isMiddlewareFile(normalizedPath)) {
return findPageFile(this.dir, normalizedPath, this.nextConfig.pageExtensions, false).then(Boolean);
}
let appFile = null;
let pagesFile = null;
if (this.appDir) {
appFile = await findPageFile(this.appDir, normalizedPath + "/page", this.nextConfig.pageExtensions, true);
}
if (this.pagesDir) {
pagesFile = await findPageFile(this.pagesDir, normalizedPath, this.nextConfig.pageExtensions, false);
}
if (appFile && pagesFile) {
return false;
}
return Boolean(appFile || pagesFile);
}
async runMiddleware(params) {
try {
const result = await super.runMiddleware({
...params,
onWarning: (warn)=>{
this.logErrorWithOriginalStack(warn, "warning");
}
});
if ("finished" in result) {
return result;
}
result.waitUntil.catch((error)=>{
this.logErrorWithOriginalStack(error, "unhandledRejection");
});
return result;
} catch (error) {
if (error instanceof DecodeError) {
throw error;
}
/**
* We only log the error when it is not a MiddlewareNotFound error as
* in that case we should be already displaying a compilation error
* which is what makes the module not found.
*/ if (!(error instanceof MiddlewareNotFoundError)) {
this.logErrorWithOriginalStack(error);
}
const err = getProperError(error);
err.middleware = true;
const { request, response, parsedUrl } = params;
/**
* When there is a failure for an internal Next.js request from
* middleware we bypass the error without finishing the request
* so we can serve the required chunks to render the error.
*/ if (request.url.includes("/_next/static") || request.url.includes("/__nextjs_original-stack-frame")) {
return {
finished: false
};
}
response.statusCode = 500;
await this.renderError(err, request, response, parsedUrl.pathname);
return {
finished: true
};
}
}
async runEdgeFunction(params) {
try {
return super.runEdgeFunction({
...params,
onWarning: (warn)=>{
this.logErrorWithOriginalStack(warn, "warning");
}
});
} catch (error) {
if (error instanceof DecodeError) {
throw error;
}
this.logErrorWithOriginalStack(error, "warning");
const err = getProperError(error);
const { req, res, page } = params;
res.statusCode = 500;
await this.renderError(err, req, res, page);
return null;
}
}
async handleRequest(req, res, parsedUrl) {
await this.devReady;
return await super.handleRequest(req, res, parsedUrl);
}
async run(req, res, parsedUrl) {
await this.devReady;
const { basePath } = this.nextConfig;
let originalPathname = null;
// TODO: see if we can remove this in the future
if (basePath && pathHasPrefix(parsedUrl.pathname || "/", basePath)) {
// strip basePath before handling dev bundles
// If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
originalPathname = parsedUrl.pathname;
parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || "/", basePath);
}
const { pathname } = parsedUrl;
if (pathname.startsWith("/_next")) {
if (await fileExists(pathJoin(this.publicDir, "_next"))) {
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT);
}
}
if (originalPathname) {
// restore the path before continuing so that custom-routes can accurately determine
// if they should match against the basePath or not
parsedUrl.pathname = originalPathname;
}
try {
return await super.run(req, res, parsedUrl);
} catch (error) {
const err = getProperError(error);
formatServerError(err);
this.logErrorWithOriginalStack(err).catch(()=>{});
if (!res.sent) {
res.statusCode = 500;
try {
return await this.renderError(err, req, res, pathname, {
__NEXT_PAGE: isError(err) && err.page || pathname || ""
});
} catch (internalErr) {
console.error(internalErr);
res.body("Internal Server Error").send();
}
}
}
}
async logErrorWithOriginalStack(err, type) {
if (this.isRenderWorker) {
await this.invokeDevMethod({
method: "logErrorWithOriginalStack",
args: [
err,
type
]
});
return;
}
throw new Error("Invariant logErrorWithOriginalStack called outside render worker");
}
getPagesManifest() {
return NodeManifestLoader.require(pathJoin(this.serverDistDir, PAGES_MANIFEST)) ?? undefined;
}
getAppPathsManifest() {
if (!this.hasAppDir) return undefined;
return NodeManifestLoader.require(pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)) ?? undefined;
}
getMiddleware() {
var _this_middleware;
// We need to populate the match
// field as it isn't serializable
if (((_this_middleware = this.middleware) == null ? void 0 : _this_middleware.match) === null) {
this.middleware.match = getMiddlewareRouteMatcher(this.middleware.matchers || []);
}
return this.middleware;
}
getNextFontManifest() {
return undefined;
}
async hasMiddleware() {
return this.hasPage(this.actualMiddlewareFile);
}
async ensureMiddleware() {
return this.ensurePage({
page: this.actualMiddlewareFile,
clientOnly: false
});
}
async runInstrumentationHookIfAvailable() {
if (this.actualInstrumentationHookFile && await this.ensurePage({
page: this.actualInstrumentationHookFile,
clientOnly: false
}).then(()=>true).catch(()=>false)) {
NextBuildContext.hasInstrumentationHook = true;
try {
const instrumentationHook = await require(pathJoin(this.distDir, "server", INSTRUMENTATION_HOOK_FILENAME));
await instrumentationHook.register();
} catch (err) {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`;
throw err;
}
}
}
async ensureEdgeFunction({ page, appPaths }) {
return this.ensurePage({
page,
appPaths,
clientOnly: false
});
}
generateRoutes(_dev) {
// In development we expose all compiled files for react-error-overlay's line show feature
// We use unshift so that we're sure the routes is defined before Next's default routes
// routes.unshift({
// match: getPathMatch('/_next/development/:path*'),
// type: 'route',
// name: '_next/development catchall',
// fn: async (req, res, params) => {
// const p = pathJoin(this.distDir, ...(params.path || []))
// await this.serveStatic(req, res, p)
// return {
// finished: true,
// }
// },
// })
}
_filterAmpDevelopmentScript(html, event) {
if (event.code !== "DISALLOWED_SCRIPT_TAG") {
return true;
}
const snippetChunks = html.split("\n");
let snippet;
if (!(snippet = html.split("\n")[event.line - 1]) || !(snippet = snippet.substring(event.col))) {
return true;
}
snippet = snippet + snippetChunks.slice(event.line).join("\n");
snippet = snippet.substring(0, snippet.indexOf("</script>"));
return !snippet.includes("data-amp-development-mode-only");
}
async getStaticPaths({ pathname, requestHeaders, page, isAppPath }) {
// we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode
const __getStaticPaths = async ()=>{
const { configFileName, publicRuntimeConfig, serverRuntimeConfig, httpAgentOptions } = this.nextConfig;
const { locales, defaultLocale } = this.nextConfig.i18n || {};
const staticPathsWorker = this.getStaticPathsWorker();
try {
const pathsResult = await staticPathsWorker.loadStaticPaths({
distDir: this.distDir,
pathname,
config: {
configFileName,
publicRuntimeConfig,
serverRuntimeConfig
},
httpAgentOptions,
locales,
defaultLocale,
page,
isAppPath,
requestHeaders,
incrementalCacheHandlerPath: this.nextConfig.experimental.incrementalCacheHandlerPath,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize
});
return pathsResult;
} finally{
// we don't re-use workers so destroy the used one
staticPathsWorker.end();
}
};
const result = this.staticPathsCache.get(pathname);
const nextInvoke = withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, []).then((res)=>{
const { paths: staticPaths = [], fallback } = res.value;
if (!isAppPath && this.nextConfig.output === "export") {
if (fallback === "blocking") {
throw new Error('getStaticPaths with "fallback: blocking" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
} else if (fallback === true) {
throw new Error('getStaticPaths with "fallback: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export');
}
}
const value = {
staticPaths,
fallbackMode: fallback === "blocking" ? "blocking" : fallback === true ? "static" : fallback
};
this.staticPathsCache.set(pathname, value);
return value;
}).catch((err)=>{
this.staticPathsCache.del(pathname);
if (!result) throw err;
Log.error(`Failed to generate static paths for ${pathname}:`);
console.error(err);
});
if (result) {
return result;
}
return nextInvoke;
}
restorePatchedGlobals() {
global.fetch = this.originalFetch;
}
async ensurePage(opts) {
if (!this.isRenderWorker) {
throw new Error("Invariant ensurePage called outside render worker");
}
await this.invokeDevMethod({
method: "ensurePage",
args: [
opts
]
});
}
async findPageComponents({ page, query, params, isAppPath, appPaths = null, shouldEnsure }) {
await this.devReady;
const compilationErr = await this.getCompilationError(page);
if (compilationErr) {
// Wrap build errors so that they don't get logged again
throw new WrappedBuildError(compilationErr);
}
try {
if (shouldEnsure || this.renderOpts.customServer) {
await this.ensurePage({
page,
appPaths,
clientOnly: false
});
}
this.nextFontManifest = super.getNextFontManifest();
// before we re-evaluate a route module, we want to restore globals that might
// have been patched previously to their original state so that we don't
// patch on top of the previous patch, which would keep the context of the previous
// patched global in memory, creating a memory leak.
this.restorePatchedGlobals();
return await super.findPageComponents({
page,
query,
params,
isAppPath,
shouldEnsure
});
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
return null;
}
}
async getFallbackErrorComponents() {
if (this.isRenderWorker) {
await this.invokeDevMethod({
method: "getFallbackErrorComponents",
args: []
});
return await loadDefaultErrorComponents(this.distDir);
}
throw new Error(`Invariant getFallbackErrorComponents called outside render worker`);
}
async getCompilationError(page) {
if (this.isRenderWorker) {
return await this.invokeDevMethod({
method: "getCompilationError",
args: [
page
]
});
}
throw new Error("Invariant getCompilationError called outside render worker");
}
}
//# sourceMappingURL=next-dev-server.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,613 @@
import origDebug from "next/dist/compiled/debug";
import { EventEmitter } from "events";
import { findPageFile } from "../lib/find-page-file";
import { getStaticInfoIncludingLayouts, runDependingOnPageType } from "../../build/entries";
import { join, posix } from "path";
import { normalizePathSep } from "../../shared/lib/page-path/normalize-path-sep";
import { normalizePagePath } from "../../shared/lib/page-path/normalize-page-path";
import { ensureLeadingSlash } from "../../shared/lib/page-path/ensure-leading-slash";
import { removePagePathTail } from "../../shared/lib/page-path/remove-page-path-tail";
import { reportTrigger } from "../../build/output";
import getRouteFromEntrypoint from "../get-route-from-entrypoint";
import { isInstrumentationHookFile, isInstrumentationHookFilename, isMiddlewareFile, isMiddlewareFilename } from "../../build/utils";
import { PageNotFoundError, stringifyError } from "../../shared/lib/utils";
import { COMPILER_INDEXES, COMPILER_NAMES, RSC_MODULE_TYPES } from "../../shared/lib/constants";
import { isAppPageRouteMatch } from "../future/route-matches/app-page-route-match";
import { HMR_ACTIONS_SENT_TO_BROWSER } from "./hot-reloader-types";
const debug = origDebug("next:on-demand-entry-handler");
/**
* Returns object keys with type inferred from the object key
*/ const keys = Object.keys;
const COMPILER_KEYS = keys(COMPILER_INDEXES);
function treePathToEntrypoint(segmentPath, parentPath) {
const [parallelRouteKey, segment] = segmentPath;
// TODO-APP: modify this path to cover parallelRouteKey convention
const path = (parentPath ? parentPath + "/" : "") + (parallelRouteKey !== "children" && !segment.startsWith("@") ? `@${parallelRouteKey}/` : "") + (segment === "" ? "page" : segment);
// Last segment
if (segmentPath.length === 2) {
return path;
}
const childSegmentPath = segmentPath.slice(2);
return treePathToEntrypoint(childSegmentPath, path);
}
function convertDynamicParamTypeToSyntax(dynamicParamTypeShort, param) {
switch(dynamicParamTypeShort){
case "c":
return `[...${param}]`;
case "oc":
return `[[...${param}]]`;
case "d":
return `[${param}]`;
default:
throw new Error("Unknown dynamic param type");
}
}
/**
* format: {compiler type}@{page type}@{page path}
* e.g. client@pages@/index
* e.g. server@app@app/page
*
* This guarantees the uniqueness for each page, to avoid conflicts between app/ and pages/
*/ export function getEntryKey(compilerType, pageBundleType, page) {
// TODO: handle the /children slot better
// this is a quick hack to handle when children is provided as children/page instead of /page
const pageKey = page.replace(/(@[^/]+)\/children/g, "$1");
return `${compilerType}@${pageBundleType}@${pageKey}`;
}
function getPageBundleType(pageBundlePath) {
// Handle special case for /_error
if (pageBundlePath === "/_error") return "pages";
if (isMiddlewareFilename(pageBundlePath)) return "root";
return pageBundlePath.startsWith("pages/") ? "pages" : pageBundlePath.startsWith("app/") ? "app" : "root";
}
function getEntrypointsFromTree(tree, isFirst, parentPath = []) {
const [segment, parallelRoutes] = tree;
const currentSegment = Array.isArray(segment) ? convertDynamicParamTypeToSyntax(segment[2], segment[0]) : segment;
const isPageSegment = currentSegment.startsWith("__PAGE__");
const currentPath = [
...parentPath,
isPageSegment ? "" : currentSegment
];
if (!isFirst && isPageSegment) {
// TODO get rid of '' at the start of tree
return [
treePathToEntrypoint(currentPath.slice(1))
];
}
return Object.keys(parallelRoutes).reduce((paths, key)=>{
const childTree = parallelRoutes[key];
const childPages = getEntrypointsFromTree(childTree, false, [
...currentPath,
key
]);
return [
...paths,
...childPages
];
}, []);
}
export const ADDED = Symbol("added");
export const BUILDING = Symbol("building");
export const BUILT = Symbol("built");
export var EntryTypes;
(function(EntryTypes) {
EntryTypes[EntryTypes["ENTRY"] = 0] = "ENTRY";
EntryTypes[EntryTypes["CHILD_ENTRY"] = 1] = "CHILD_ENTRY";
})(EntryTypes || (EntryTypes = {}));
const entriesMap = new Map();
// remove /server from end of output for server compiler
const normalizeOutputPath = (dir)=>dir.replace(/[/\\]server$/, "");
export const getEntries = (dir)=>{
dir = normalizeOutputPath(dir);
const entries = entriesMap.get(dir) || {};
entriesMap.set(dir, entries);
return entries;
};
const invalidators = new Map();
export const getInvalidator = (dir)=>{
dir = normalizeOutputPath(dir);
return invalidators.get(dir);
};
const doneCallbacks = new EventEmitter();
const lastClientAccessPages = [
""
];
const lastServerAccessPagesForAppDir = [
""
];
// Make sure only one invalidation happens at a time
// Otherwise, webpack hash gets changed and it'll force the client to reload.
class Invalidator {
constructor(multiCompiler){
this.building = new Set();
this.rebuildAgain = new Set();
this.multiCompiler = multiCompiler;
}
shouldRebuildAll() {
return this.rebuildAgain.size > 0;
}
invalidate(compilerKeys = COMPILER_KEYS) {
for (const key of compilerKeys){
var _this_multiCompiler_compilers_COMPILER_INDEXES_key_watching;
// If there's a current build is processing, we won't abort it by invalidating.
// (If aborted, it'll cause a client side hard reload)
// But let it to invalidate just after the completion.
// So, it can re-build the queued pages at once.
if (this.building.has(key)) {
this.rebuildAgain.add(key);
continue;
}
this.building.add(key);
(_this_multiCompiler_compilers_COMPILER_INDEXES_key_watching = this.multiCompiler.compilers[COMPILER_INDEXES[key]].watching) == null ? void 0 : _this_multiCompiler_compilers_COMPILER_INDEXES_key_watching.invalidate();
}
}
startBuilding(compilerKey) {
this.building.add(compilerKey);
}
doneBuilding(compilerKeys = []) {
const rebuild = [];
for (const key of compilerKeys){
this.building.delete(key);
if (this.rebuildAgain.has(key)) {
rebuild.push(key);
this.rebuildAgain.delete(key);
}
}
this.invalidate(rebuild);
}
willRebuild(compilerKey) {
return this.rebuildAgain.has(compilerKey);
}
}
function disposeInactiveEntries(entries, maxInactiveAge) {
Object.keys(entries).forEach((entryKey)=>{
const entryData = entries[entryKey];
const { lastActiveTime, status, dispose, bundlePath } = entryData;
// TODO-APP: implement disposing of CHILD_ENTRY
if (entryData.type === 1) {
return;
}
// For the root middleware and the instrumentation hook files,
// we don't dispose them periodically as it's needed for every request.
if (isMiddlewareFilename(bundlePath) || isInstrumentationHookFilename(bundlePath)) {
return;
}
if (dispose) // Skip pages already scheduled for disposing
return;
// This means this entry is currently building or just added
// We don't need to dispose those entries.
if (status !== BUILT) return;
// We should not build the last accessed page even we didn't get any pings
// Sometimes, it's possible our XHR ping to wait before completing other requests.
// In that case, we should not dispose the current viewing page
if (lastClientAccessPages.includes(entryKey) || lastServerAccessPagesForAppDir.includes(entryKey)) return;
if (lastActiveTime && Date.now() - lastActiveTime > maxInactiveAge) {
entries[entryKey].dispose = true;
}
});
}
// Normalize both app paths and page paths
function tryToNormalizePagePath(page) {
try {
return normalizePagePath(page);
} catch (err) {
console.error(err);
throw new PageNotFoundError(page);
}
}
/**
* Attempts to find a page file path from the given pages absolute directory,
* a page and allowed extensions. If the page can't be found it will throw an
* error. It defaults the `/_error` page to Next.js internal error page.
*
* @param rootDir Absolute path to the project root.
* @param pagesDir Absolute path to the pages folder with trailing `/pages`.
* @param normalizedPagePath The page normalized (it will be denormalized).
* @param pageExtensions Array of page extensions.
*/ async function findPagePathData(rootDir, page, extensions, pagesDir, appDir) {
const normalizedPagePath = tryToNormalizePagePath(page);
let pagePath = null;
const isInstrumentation = isInstrumentationHookFile(normalizedPagePath);
if (isMiddlewareFile(normalizedPagePath) || isInstrumentation) {
pagePath = await findPageFile(rootDir, normalizedPagePath, extensions, false);
if (!pagePath) {
throw new PageNotFoundError(normalizedPagePath);
}
const pageUrl = ensureLeadingSlash(removePagePathTail(normalizePathSep(pagePath), {
extensions
}));
let bundlePath = normalizedPagePath;
let pageKey = posix.normalize(pageUrl);
if (isInstrumentation) {
bundlePath = bundlePath.replace("/src", "");
pageKey = page.replace("/src", "");
}
return {
absolutePagePath: join(rootDir, pagePath),
bundlePath: bundlePath.slice(1),
page: pageKey
};
}
// Check appDir first falling back to pagesDir
if (appDir) {
pagePath = await findPageFile(appDir, normalizedPagePath, extensions, true);
if (pagePath) {
const pageUrl = ensureLeadingSlash(removePagePathTail(normalizePathSep(pagePath), {
keepIndex: true,
extensions
}));
return {
absolutePagePath: join(appDir, pagePath),
bundlePath: posix.join("app", pageUrl),
page: posix.normalize(pageUrl)
};
}
}
if (!pagePath && pagesDir) {
pagePath = await findPageFile(pagesDir, normalizedPagePath, extensions, false);
}
if (pagePath !== null && pagesDir) {
const pageUrl = ensureLeadingSlash(removePagePathTail(normalizePathSep(pagePath), {
extensions
}));
return {
absolutePagePath: join(pagesDir, pagePath),
bundlePath: posix.join("pages", normalizePagePath(pageUrl)),
page: posix.normalize(pageUrl)
};
}
if (page === "/not-found" && appDir) {
return {
absolutePagePath: require.resolve("next/dist/client/components/not-found-error"),
bundlePath: "app/not-found",
page: "/not-found"
};
}
if (page === "/_error") {
return {
absolutePagePath: require.resolve("next/dist/pages/_error"),
bundlePath: page,
page: normalizePathSep(page)
};
} else {
throw new PageNotFoundError(normalizedPagePath);
}
}
async function findRoutePathData(rootDir, page, extensions, pagesDir, appDir, match) {
if (match) {
// If the match is available, we don't have to discover the data from the
// filesystem.
return {
absolutePagePath: match.definition.filename,
page: match.definition.page,
bundlePath: match.definition.bundlePath
};
}
return findPagePathData(rootDir, page, extensions, pagesDir, appDir);
}
export function onDemandEntryHandler({ hotReloader, maxInactiveAge, multiCompiler, nextConfig, pagesBufferLength, pagesDir, rootDir, appDir }) {
let curInvalidator = getInvalidator(multiCompiler.outputPath);
const curEntries = getEntries(multiCompiler.outputPath);
if (!curInvalidator) {
curInvalidator = new Invalidator(multiCompiler);
invalidators.set(multiCompiler.outputPath, curInvalidator);
}
const startBuilding = (compilation)=>{
const compilationName = compilation.name;
curInvalidator.startBuilding(compilationName);
};
for (const compiler of multiCompiler.compilers){
compiler.hooks.make.tap("NextJsOnDemandEntries", startBuilding);
}
function getPagePathsFromEntrypoints(type, entrypoints, root) {
const pagePaths = [];
for (const entrypoint of entrypoints.values()){
const page = getRouteFromEntrypoint(entrypoint.name, root);
if (page) {
var _entrypoint_name;
const pageBundleType = ((_entrypoint_name = entrypoint.name) == null ? void 0 : _entrypoint_name.startsWith("app/")) ? "app" : "pages";
pagePaths.push(getEntryKey(type, pageBundleType, page));
} else if (root && entrypoint.name === "root" || isMiddlewareFilename(entrypoint.name) || isInstrumentationHookFilename(entrypoint.name)) {
pagePaths.push(getEntryKey(type, "root", `/${entrypoint.name}`));
}
}
return pagePaths;
}
for (const compiler of multiCompiler.compilers){
compiler.hooks.done.tap("NextJsOnDemandEntries", ()=>{
var _getInvalidator;
return (_getInvalidator = getInvalidator(compiler.outputPath)) == null ? void 0 : _getInvalidator.doneBuilding([
compiler.name
]);
});
}
multiCompiler.hooks.done.tap("NextJsOnDemandEntries", (multiStats)=>{
var _getInvalidator;
const [clientStats, serverStats, edgeServerStats] = multiStats.stats;
const root = !!appDir;
const entryNames = [
...getPagePathsFromEntrypoints(COMPILER_NAMES.client, clientStats.compilation.entrypoints, root),
...getPagePathsFromEntrypoints(COMPILER_NAMES.server, serverStats.compilation.entrypoints, root),
...edgeServerStats ? getPagePathsFromEntrypoints(COMPILER_NAMES.edgeServer, edgeServerStats.compilation.entrypoints, root) : []
];
for (const name of entryNames){
const entry = curEntries[name];
if (!entry) {
continue;
}
if (entry.status !== BUILDING) {
continue;
}
entry.status = BUILT;
doneCallbacks.emit(name);
}
(_getInvalidator = getInvalidator(multiCompiler.outputPath)) == null ? void 0 : _getInvalidator.doneBuilding([
...COMPILER_KEYS
]);
});
const pingIntervalTime = Math.max(1000, Math.min(5000, maxInactiveAge));
setInterval(function() {
disposeInactiveEntries(curEntries, maxInactiveAge);
}, pingIntervalTime + 1000).unref();
function handleAppDirPing(tree) {
const pages = getEntrypointsFromTree(tree, true);
for (const page of pages){
for (const compilerType of [
COMPILER_NAMES.client,
COMPILER_NAMES.server,
COMPILER_NAMES.edgeServer
]){
const entryKey = getEntryKey(compilerType, "app", `/${page}`);
const entryInfo = curEntries[entryKey];
// If there's no entry, it may have been invalidated and needs to be re-built.
if (!entryInfo) {
continue;
}
// We don't need to maintain active state of anything other than BUILT entries
if (entryInfo.status !== BUILT) continue;
// If there's an entryInfo
if (!lastServerAccessPagesForAppDir.includes(entryKey)) {
lastServerAccessPagesForAppDir.unshift(entryKey);
// Maintain the buffer max length
// TODO: verify that the current pageKey is not at the end of the array as multiple entrypoints can exist
if (lastServerAccessPagesForAppDir.length > pagesBufferLength) {
lastServerAccessPagesForAppDir.pop();
}
}
entryInfo.lastActiveTime = Date.now();
entryInfo.dispose = false;
}
}
}
function handlePing(pg) {
const page = normalizePathSep(pg);
for (const compilerType of [
COMPILER_NAMES.client,
COMPILER_NAMES.server,
COMPILER_NAMES.edgeServer
]){
const entryKey = getEntryKey(compilerType, "pages", page);
const entryInfo = curEntries[entryKey];
// If there's no entry, it may have been invalidated and needs to be re-built.
if (!entryInfo) {
// if (page !== lastEntry) client pings, but there's no entry for page
if (compilerType === COMPILER_NAMES.client) {
return;
}
continue;
}
// We don't need to maintain active state of anything other than BUILT entries
if (entryInfo.status !== BUILT) continue;
// If there's an entryInfo
if (!lastClientAccessPages.includes(entryKey)) {
lastClientAccessPages.unshift(entryKey);
// Maintain the buffer max length
if (lastClientAccessPages.length > pagesBufferLength) {
lastClientAccessPages.pop();
}
}
entryInfo.lastActiveTime = Date.now();
entryInfo.dispose = false;
}
return;
}
async function ensurePageImpl({ page, clientOnly, appPaths = null, match, isApp }) {
const stalledTime = 60;
const stalledEnsureTimeout = setTimeout(()=>{
debug(`Ensuring ${page} has taken longer than ${stalledTime}s, if this continues to stall this may be a bug`);
}, stalledTime * 1000);
// If the route is actually an app page route, then we should have access
// to the app route match, and therefore, the appPaths from it.
if (!appPaths && match && isAppPageRouteMatch(match)) {
appPaths = match.definition.appPaths;
}
try {
const pagePathData = await findRoutePathData(rootDir, page, nextConfig.pageExtensions, pagesDir, appDir, match);
const isInsideAppDir = !!appDir && pagePathData.absolutePagePath.startsWith(appDir);
if (typeof isApp === "boolean" && isApp !== isInsideAppDir) {
Error.stackTraceLimit = 15;
throw new Error(`Ensure bailed, found path "${pagePathData.page}" does not match ensure type (${isApp ? "app" : "pages"})`);
}
const pageBundleType = getPageBundleType(pagePathData.bundlePath);
const addEntry = (compilerType)=>{
const entryKey = getEntryKey(compilerType, pageBundleType, pagePathData.page);
if (curEntries[entryKey] && // there can be an overlap in the entryKey for the instrumentation hook file and a page named the same
// this is a quick fix to support this scenario by overwriting the instrumentation hook entry, since we only use it one time
// any changes to the instrumentation hook file will require a restart of the dev server anyway
!isInstrumentationHookFilename(curEntries[entryKey].bundlePath)) {
curEntries[entryKey].dispose = false;
curEntries[entryKey].lastActiveTime = Date.now();
if (curEntries[entryKey].status === BUILT) {
return {
entryKey,
newEntry: false,
shouldInvalidate: false
};
}
return {
entryKey,
newEntry: false,
shouldInvalidate: true
};
}
curEntries[entryKey] = {
type: 0,
appPaths,
absolutePagePath: pagePathData.absolutePagePath,
request: pagePathData.absolutePagePath,
bundlePath: pagePathData.bundlePath,
dispose: false,
lastActiveTime: Date.now(),
status: ADDED
};
return {
entryKey: entryKey,
newEntry: true,
shouldInvalidate: true
};
};
const staticInfo = await getStaticInfoIncludingLayouts({
page,
pageFilePath: pagePathData.absolutePagePath,
isInsideAppDir,
pageExtensions: nextConfig.pageExtensions,
isDev: true,
config: nextConfig,
appDir
});
const added = new Map();
const isServerComponent = isInsideAppDir && staticInfo.rsc !== RSC_MODULE_TYPES.client;
runDependingOnPageType({
page: pagePathData.page,
pageRuntime: staticInfo.runtime,
pageType: pageBundleType,
onClient: ()=>{
// Skip adding the client entry for app / Server Components.
if (isServerComponent || isInsideAppDir) {
return;
}
added.set(COMPILER_NAMES.client, addEntry(COMPILER_NAMES.client));
},
onServer: ()=>{
added.set(COMPILER_NAMES.server, addEntry(COMPILER_NAMES.server));
const edgeServerEntry = getEntryKey(COMPILER_NAMES.edgeServer, pageBundleType, pagePathData.page);
if (curEntries[edgeServerEntry] && !isInstrumentationHookFile(pagePathData.page)) {
// Runtime switched from edge to server
delete curEntries[edgeServerEntry];
}
},
onEdgeServer: ()=>{
added.set(COMPILER_NAMES.edgeServer, addEntry(COMPILER_NAMES.edgeServer));
const serverEntry = getEntryKey(COMPILER_NAMES.server, pageBundleType, pagePathData.page);
if (curEntries[serverEntry] && !isInstrumentationHookFile(pagePathData.page)) {
// Runtime switched from server to edge
delete curEntries[serverEntry];
}
}
});
const addedValues = [
...added.values()
];
const entriesThatShouldBeInvalidated = [
...added.entries()
].filter(([, entry])=>entry.shouldInvalidate);
const hasNewEntry = addedValues.some((entry)=>entry.newEntry);
if (hasNewEntry) {
reportTrigger(!clientOnly && hasNewEntry ? `${pagePathData.page}` : pagePathData.page);
}
if (entriesThatShouldBeInvalidated.length > 0) {
const invalidatePromise = Promise.all(entriesThatShouldBeInvalidated.map(([compilerKey, { entryKey }])=>{
return new Promise((resolve, reject)=>{
doneCallbacks.once(entryKey, (err)=>{
if (err) {
return reject(err);
}
// If the invalidation also triggers a rebuild, we need to
// wait for that additional build to prevent race conditions.
const needsRebuild = curInvalidator.willRebuild(compilerKey);
if (needsRebuild) {
doneCallbacks.once(entryKey, (rebuildErr)=>{
if (rebuildErr) {
return reject(rebuildErr);
}
resolve();
});
} else {
resolve();
}
});
});
}));
curInvalidator.invalidate([
...added.keys()
]);
await invalidatePromise;
}
} finally{
clearTimeout(stalledEnsureTimeout);
}
}
// Make sure that we won't have multiple invalidations ongoing concurrently.
const curEnsurePage = new Map();
return {
async ensurePage ({ page, clientOnly, appPaths = null, match, isApp }) {
const ensureKey = JSON.stringify({
page,
clientOnly,
match,
appPaths
});
const pendingEnsure = curEnsurePage.get(ensureKey);
if (pendingEnsure) {
const res = await pendingEnsure;
if (res && res.err) {
throw res.err;
}
}
const promise = ensurePageImpl({
page,
clientOnly,
appPaths,
match,
isApp
}).catch((err)=>{
return {
err
};
}).finally(()=>{
curEnsurePage.delete(ensureKey);
});
curEnsurePage.set(ensureKey, promise);
return promise;
},
onHMR (client, getHmrServerError) {
let bufferedHmrServerError = null;
client.addEventListener("close", ()=>{
bufferedHmrServerError = null;
});
client.addEventListener("message", ({ data })=>{
try {
const error = getHmrServerError();
// New error occurred: buffered error is flushed and new error occurred
if (!bufferedHmrServerError && error) {
hotReloader.send({
action: HMR_ACTIONS_SENT_TO_BROWSER.SERVER_ERROR,
errorJSON: stringifyError(error)
});
bufferedHmrServerError = null;
}
const parsedData = JSON.parse(typeof data !== "string" ? data.toString() : data);
if (parsedData.event === "ping") {
if (parsedData.appDirRoute) {
handleAppDirPing(parsedData.tree);
} else {
handlePing(parsedData.page);
}
}
} catch {}
});
}
};
}
//# sourceMappingURL=on-demand-entry-handler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,57 @@
import * as semver from "next/dist/compiled/semver";
export function parseVersionInfo(o) {
const latest = semver.parse(o.latest);
const canary = semver.parse(o.canary);
const installedParsed = semver.parse(o.installed);
const installed = o.installed;
if (installedParsed && latest && canary) {
if (installedParsed.major < latest.major) {
// Old major version
return {
staleness: "stale-major",
expected: latest.raw,
installed
};
} else if (installedParsed.prerelease[0] === "canary" && semver.lt(installedParsed, canary)) {
// Matching major, but old canary
return {
staleness: "stale-prerelease",
expected: canary.raw,
installed
};
} else if (!installedParsed.prerelease.length && semver.lt(installedParsed, latest)) {
// Stable, but not the latest
if (installedParsed.minor === latest.minor) {
// Same major and minor, but not the latest patch
return {
staleness: "stale-patch",
expected: latest.raw,
installed
};
}
return {
staleness: "stale-minor",
expected: latest.raw,
installed
};
} else if (semver.gt(installedParsed, latest) && installedParsed.version !== canary.version) {
// Newer major version
return {
staleness: "newer-than-npm",
installed
};
} else {
// Latest and greatest
return {
staleness: "fresh",
installed
};
}
}
return {
installed: (installedParsed == null ? void 0 : installedParsed.raw) ?? "0.0.0",
staleness: "unknown"
};
}
//# sourceMappingURL=parse-version-info.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/parse-version-info.ts"],"names":["semver","parseVersionInfo","o","latest","parse","canary","installedParsed","installed","major","staleness","expected","raw","prerelease","lt","length","minor","gt","version"],"mappings":"AAAA,YAAYA,YAAY,4BAA2B;AAenD,OAAO,SAASC,iBAAiBC,CAIhC;IACC,MAAMC,SAASH,OAAOI,KAAK,CAACF,EAAEC,MAAM;IACpC,MAAME,SAASL,OAAOI,KAAK,CAACF,EAAEG,MAAM;IACpC,MAAMC,kBAAkBN,OAAOI,KAAK,CAACF,EAAEK,SAAS;IAChD,MAAMA,YAAYL,EAAEK,SAAS;IAC7B,IAAID,mBAAmBH,UAAUE,QAAQ;QACvC,IAAIC,gBAAgBE,KAAK,GAAGL,OAAOK,KAAK,EAAE;YACxC,oBAAoB;YACpB,OAAO;gBAAEC,WAAW;gBAAeC,UAAUP,OAAOQ,GAAG;gBAAEJ;YAAU;QACrE,OAAO,IACLD,gBAAgBM,UAAU,CAAC,EAAE,KAAK,YAClCZ,OAAOa,EAAE,CAACP,iBAAiBD,SAC3B;YACA,iCAAiC;YACjC,OAAO;gBACLI,WAAW;gBACXC,UAAUL,OAAOM,GAAG;gBACpBJ;YACF;QACF,OAAO,IACL,CAACD,gBAAgBM,UAAU,CAACE,MAAM,IAClCd,OAAOa,EAAE,CAACP,iBAAiBH,SAC3B;YACA,6BAA6B;YAC7B,IAAIG,gBAAgBS,KAAK,KAAKZ,OAAOY,KAAK,EAAE;gBAC1C,iDAAiD;gBACjD,OAAO;oBACLN,WAAW;oBACXC,UAAUP,OAAOQ,GAAG;oBACpBJ;gBACF;YACF;YACA,OAAO;gBAAEE,WAAW;gBAAeC,UAAUP,OAAOQ,GAAG;gBAAEJ;YAAU;QACrE,OAAO,IACLP,OAAOgB,EAAE,CAACV,iBAAiBH,WAC3BG,gBAAgBW,OAAO,KAAKZ,OAAOY,OAAO,EAC1C;YACA,sBAAsB;YACtB,OAAO;gBAAER,WAAW;gBAAkBF;YAAU;QAClD,OAAO;YACL,sBAAsB;YACtB,OAAO;gBAAEE,WAAW;gBAASF;YAAU;QACzC;IACF;IAEA,OAAO;QACLA,WAAWD,CAAAA,mCAAAA,gBAAiBK,GAAG,KAAI;QACnCF,WAAW;IACb;AACF"}

View File

@@ -0,0 +1,66 @@
import "../require-hook";
import "../node-polyfill-fetch";
import "../node-environment";
import { buildAppStaticPaths, buildStaticPaths, collectGenerateParams } from "../../build/utils";
import { loadComponents } from "../load-components";
import { setHttpClientAndAgentOptions } from "../setup-http-agent-env";
import * as serverHooks from "../../client/components/hooks-server-context";
import { staticGenerationAsyncStorage } from "../../client/components/static-generation-async-storage.external";
const { AppRouteRouteModule } = require("../future/route-modules/app-route/module.compiled");
// we call getStaticPaths in a separate process to ensure
// side-effects aren't relied on in dev that will break
// during a production build
export async function loadStaticPaths({ distDir, pathname, config, httpAgentOptions, locales, defaultLocale, isAppPath, page, isrFlushToDisk, fetchCacheKeyPrefix, maxMemoryCacheSize, requestHeaders, incrementalCacheHandlerPath }) {
// update work memory runtime-config
require("../../shared/lib/runtime-config.external").setConfig(config);
setHttpClientAndAgentOptions({
httpAgentOptions
});
const components = await loadComponents({
distDir,
// In `pages/`, the page is the same as the pathname.
page: page || pathname,
isAppPath
});
if (!components.getStaticPaths && !isAppPath) {
// we shouldn't get to this point since the worker should
// only be called for SSG pages with getStaticPaths
throw new Error(`Invariant: failed to load page with getStaticPaths for ${pathname}`);
}
if (isAppPath) {
const { routeModule } = components;
const generateParams = routeModule && AppRouteRouteModule.is(routeModule) ? [
{
config: {
revalidate: routeModule.userland.revalidate,
dynamic: routeModule.userland.dynamic,
dynamicParams: routeModule.userland.dynamicParams
},
generateStaticParams: routeModule.userland.generateStaticParams,
segmentPath: pathname
}
] : await collectGenerateParams(components.ComponentMod.tree);
return await buildAppStaticPaths({
page: pathname,
generateParams,
configFileName: config.configFileName,
distDir,
requestHeaders,
incrementalCacheHandlerPath,
serverHooks,
staticGenerationAsyncStorage,
isrFlushToDisk,
fetchCacheKeyPrefix,
maxMemoryCacheSize
});
}
return await buildStaticPaths({
page: pathname,
getStaticPaths: components.getStaticPaths,
configFileName: config.configFileName,
locales,
defaultLocale
});
}
//# sourceMappingURL=static-paths-worker.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/server/dev/static-paths-worker.ts"],"names":["buildAppStaticPaths","buildStaticPaths","collectGenerateParams","loadComponents","setHttpClientAndAgentOptions","serverHooks","staticGenerationAsyncStorage","AppRouteRouteModule","require","loadStaticPaths","distDir","pathname","config","httpAgentOptions","locales","defaultLocale","isAppPath","page","isrFlushToDisk","fetchCacheKeyPrefix","maxMemoryCacheSize","requestHeaders","incrementalCacheHandlerPath","setConfig","components","getStaticPaths","Error","routeModule","generateParams","is","revalidate","userland","dynamic","dynamicParams","generateStaticParams","segmentPath","ComponentMod","tree","configFileName"],"mappings":"AAEA,OAAO,kBAAiB;AACxB,OAAO,yBAAwB;AAC/B,OAAO,sBAAqB;AAE5B,SACEA,mBAAmB,EACnBC,gBAAgB,EAChBC,qBAAqB,QAEhB,oBAAmB;AAC1B,SAASC,cAAc,QAAQ,qBAAoB;AACnD,SAASC,4BAA4B,QAAQ,0BAAyB;AAEtE,YAAYC,iBAAiB,+CAA8C;AAC3E,SAASC,4BAA4B,QAAQ,mEAAkE;AAE/G,MAAM,EAAEC,mBAAmB,EAAE,GAC3BC,QAAQ;AAIV,yDAAyD;AACzD,uDAAuD;AACvD,4BAA4B;AAC5B,OAAO,eAAeC,gBAAgB,EACpCC,OAAO,EACPC,QAAQ,EACRC,MAAM,EACNC,gBAAgB,EAChBC,OAAO,EACPC,aAAa,EACbC,SAAS,EACTC,IAAI,EACJC,cAAc,EACdC,mBAAmB,EACnBC,kBAAkB,EAClBC,cAAc,EACdC,2BAA2B,EAe5B;IAKC,oCAAoC;IACpCd,QAAQ,4CAA4Ce,SAAS,CAACX;IAC9DR,6BAA6B;QAC3BS;IACF;IAEA,MAAMW,aAAa,MAAMrB,eAAe;QACtCO;QACA,qDAAqD;QACrDO,MAAMA,QAAQN;QACdK;IACF;IAEA,IAAI,CAACQ,WAAWC,cAAc,IAAI,CAACT,WAAW;QAC5C,yDAAyD;QACzD,mDAAmD;QACnD,MAAM,IAAIU,MACR,CAAC,uDAAuD,EAAEf,SAAS,CAAC;IAExE;IAEA,IAAIK,WAAW;QACb,MAAM,EAAEW,WAAW,EAAE,GAAGH;QACxB,MAAMI,iBACJD,eAAepB,oBAAoBsB,EAAE,CAACF,eAClC;YACE;gBACEf,QAAQ;oBACNkB,YAAYH,YAAYI,QAAQ,CAACD,UAAU;oBAC3CE,SAASL,YAAYI,QAAQ,CAACC,OAAO;oBACrCC,eAAeN,YAAYI,QAAQ,CAACE,aAAa;gBACnD;gBACAC,sBAAsBP,YAAYI,QAAQ,CAACG,oBAAoB;gBAC/DC,aAAaxB;YACf;SACD,GACD,MAAMT,sBAAsBsB,WAAWY,YAAY,CAACC,IAAI;QAE9D,OAAO,MAAMrC,oBAAoB;YAC/BiB,MAAMN;YACNiB;YACAU,gBAAgB1B,OAAO0B,cAAc;YACrC5B;YACAW;YACAC;YACAjB;YACAC;YACAY;YACAC;YACAC;QACF;IACF;IAEA,OAAO,MAAMnB,iBAAiB;QAC5BgB,MAAMN;QACNc,gBAAgBD,WAAWC,cAAc;QACzCa,gBAAgB1B,OAAO0B,cAAc;QACrCxB;QACAC;IACF;AACF"}

Some files were not shown because too many files have changed in this diff Show More