feat(wise-hearted-decor): initial luxury event decor website build with 5 pillars, portfolio, and booking funnel
This commit is contained in:
+17
@@ -0,0 +1,17 @@
|
||||
import type { AppDirModules } from '../../build/webpack/loaders/next-app-loader';
|
||||
/**
|
||||
* LoaderTree is generated in next-app-loader.
|
||||
*/
|
||||
export type LoaderTree = [
|
||||
segment: string,
|
||||
parallelRoutes: {
|
||||
[parallelRouterKey: string]: LoaderTree;
|
||||
},
|
||||
modules: AppDirModules
|
||||
];
|
||||
export declare function getLayoutOrPageModule(loaderTree: LoaderTree): Promise<{
|
||||
mod: any;
|
||||
modType: "page" | "layout" | undefined;
|
||||
filePath: string | undefined;
|
||||
}>;
|
||||
export declare function getComponentTypeModule(loaderTree: LoaderTree, moduleType: 'layout' | 'not-found' | 'forbidden' | 'unauthorized'): Promise<any>;
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
getComponentTypeModule: null,
|
||||
getLayoutOrPageModule: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
getComponentTypeModule: function() {
|
||||
return getComponentTypeModule;
|
||||
},
|
||||
getLayoutOrPageModule: function() {
|
||||
return getLayoutOrPageModule;
|
||||
}
|
||||
});
|
||||
const _segment = require("../../shared/lib/segment");
|
||||
async function getLayoutOrPageModule(loaderTree) {
|
||||
const { layout, page, defaultPage } = loaderTree[2];
|
||||
const isLayout = typeof layout !== 'undefined';
|
||||
const isPage = typeof page !== 'undefined';
|
||||
const isDefaultPage = typeof defaultPage !== 'undefined' && loaderTree[0] === _segment.DEFAULT_SEGMENT_KEY;
|
||||
let mod = undefined;
|
||||
let modType = undefined;
|
||||
let filePath = undefined;
|
||||
if (isLayout) {
|
||||
mod = await layout[0]();
|
||||
modType = 'layout';
|
||||
filePath = layout[1];
|
||||
} else if (isPage) {
|
||||
mod = await page[0]();
|
||||
modType = 'page';
|
||||
filePath = page[1];
|
||||
} else if (isDefaultPage) {
|
||||
mod = await defaultPage[0]();
|
||||
modType = 'page';
|
||||
filePath = defaultPage[1];
|
||||
}
|
||||
return {
|
||||
mod,
|
||||
modType,
|
||||
filePath
|
||||
};
|
||||
}
|
||||
async function getComponentTypeModule(loaderTree, moduleType) {
|
||||
const { [moduleType]: module1 } = loaderTree[2];
|
||||
if (typeof module1 !== 'undefined') {
|
||||
return await module1[0]();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-dir-module.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/app-dir-module.ts"],"sourcesContent":["import type { AppDirModules } from '../../build/webpack/loaders/next-app-loader'\nimport { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'\n\n/**\n * LoaderTree is generated in next-app-loader.\n */\nexport type LoaderTree = [\n segment: string,\n parallelRoutes: { [parallelRouterKey: string]: LoaderTree },\n modules: AppDirModules,\n]\n\nexport async function getLayoutOrPageModule(loaderTree: LoaderTree) {\n const { layout, page, defaultPage } = loaderTree[2]\n const isLayout = typeof layout !== 'undefined'\n const isPage = typeof page !== 'undefined'\n const isDefaultPage =\n typeof defaultPage !== 'undefined' && loaderTree[0] === DEFAULT_SEGMENT_KEY\n\n let mod = undefined\n let modType: 'layout' | 'page' | undefined = undefined\n let filePath = undefined\n\n if (isLayout) {\n mod = await layout[0]()\n modType = 'layout'\n filePath = layout[1]\n } else if (isPage) {\n mod = await page[0]()\n modType = 'page'\n filePath = page[1]\n } else if (isDefaultPage) {\n mod = await defaultPage[0]()\n modType = 'page'\n filePath = defaultPage[1]\n }\n\n return { mod, modType, filePath }\n}\n\nexport async function getComponentTypeModule(\n loaderTree: LoaderTree,\n moduleType: 'layout' | 'not-found' | 'forbidden' | 'unauthorized'\n) {\n const { [moduleType]: module } = loaderTree[2]\n if (typeof module !== 'undefined') {\n return await module[0]()\n }\n return undefined\n}\n"],"names":["getComponentTypeModule","getLayoutOrPageModule","loaderTree","layout","page","defaultPage","isLayout","isPage","isDefaultPage","DEFAULT_SEGMENT_KEY","mod","undefined","modType","filePath","moduleType","module"],"mappings":";;;;;;;;;;;;;;;IAwCsBA,sBAAsB;eAAtBA;;IA5BAC,qBAAqB;eAArBA;;;yBAXc;AAW7B,eAAeA,sBAAsBC,UAAsB;IAChE,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEC,WAAW,EAAE,GAAGH,UAAU,CAAC,EAAE;IACnD,MAAMI,WAAW,OAAOH,WAAW;IACnC,MAAMI,SAAS,OAAOH,SAAS;IAC/B,MAAMI,gBACJ,OAAOH,gBAAgB,eAAeH,UAAU,CAAC,EAAE,KAAKO,4BAAmB;IAE7E,IAAIC,MAAMC;IACV,IAAIC,UAAyCD;IAC7C,IAAIE,WAAWF;IAEf,IAAIL,UAAU;QACZI,MAAM,MAAMP,MAAM,CAAC,EAAE;QACrBS,UAAU;QACVC,WAAWV,MAAM,CAAC,EAAE;IACtB,OAAO,IAAII,QAAQ;QACjBG,MAAM,MAAMN,IAAI,CAAC,EAAE;QACnBQ,UAAU;QACVC,WAAWT,IAAI,CAAC,EAAE;IACpB,OAAO,IAAII,eAAe;QACxBE,MAAM,MAAML,WAAW,CAAC,EAAE;QAC1BO,UAAU;QACVC,WAAWR,WAAW,CAAC,EAAE;IAC3B;IAEA,OAAO;QAAEK;QAAKE;QAASC;IAAS;AAClC;AAEO,eAAeb,uBACpBE,UAAsB,EACtBY,UAAiE;IAEjE,MAAM,EAAE,CAACA,WAAW,EAAEC,OAAM,EAAE,GAAGb,UAAU,CAAC,EAAE;IAC9C,IAAI,OAAOa,YAAW,aAAa;QACjC,OAAO,MAAMA,OAAM,CAAC,EAAE;IACxB;IACA,OAAOJ;AACT"}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
export declare function logStartInfo({ networkUrl, appUrl, envInfo, expFeatureInfo, maxExperimentalFeatures, }: {
|
||||
networkUrl: string | null;
|
||||
appUrl: string | null;
|
||||
envInfo?: string[];
|
||||
expFeatureInfo?: string[];
|
||||
maxExperimentalFeatures?: number;
|
||||
}): void;
|
||||
export declare function getStartServerInfo(dir: string, dev: boolean): Promise<{
|
||||
envInfo?: string[];
|
||||
expFeatureInfo?: string[];
|
||||
}>;
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
getStartServerInfo: null,
|
||||
logStartInfo: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
getStartServerInfo: function() {
|
||||
return getStartServerInfo;
|
||||
},
|
||||
logStartInfo: function() {
|
||||
return logStartInfo;
|
||||
}
|
||||
});
|
||||
const _env = require("@next/env");
|
||||
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../../build/output/log"));
|
||||
const _picocolors = require("../../lib/picocolors");
|
||||
const _constants = require("../../shared/lib/constants");
|
||||
const _config = /*#__PURE__*/ _interop_require_wildcard(require("../config"));
|
||||
function _getRequireWildcardCache(nodeInterop) {
|
||||
if (typeof WeakMap !== "function") return null;
|
||||
var cacheBabelInterop = new WeakMap();
|
||||
var cacheNodeInterop = new WeakMap();
|
||||
return (_getRequireWildcardCache = function(nodeInterop) {
|
||||
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
|
||||
})(nodeInterop);
|
||||
}
|
||||
function _interop_require_wildcard(obj, nodeInterop) {
|
||||
if (!nodeInterop && obj && obj.__esModule) {
|
||||
return obj;
|
||||
}
|
||||
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
|
||||
return {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
var cache = _getRequireWildcardCache(nodeInterop);
|
||||
if (cache && cache.has(obj)) {
|
||||
return cache.get(obj);
|
||||
}
|
||||
var newObj = {
|
||||
__proto__: null
|
||||
};
|
||||
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
|
||||
for(var key in obj){
|
||||
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
|
||||
if (desc && (desc.get || desc.set)) {
|
||||
Object.defineProperty(newObj, key, desc);
|
||||
} else {
|
||||
newObj[key] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
newObj.default = obj;
|
||||
if (cache) {
|
||||
cache.set(obj, newObj);
|
||||
}
|
||||
return newObj;
|
||||
}
|
||||
function logStartInfo({ networkUrl, appUrl, envInfo, expFeatureInfo, maxExperimentalFeatures = Infinity }) {
|
||||
_log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"15.1.0"}`))}${process.env.TURBOPACK ? ' (Turbopack)' : ''}`);
|
||||
if (appUrl) {
|
||||
_log.bootstrap(`- Local: ${appUrl}`);
|
||||
}
|
||||
if (networkUrl) {
|
||||
_log.bootstrap(`- Network: ${networkUrl}`);
|
||||
}
|
||||
if (envInfo == null ? void 0 : envInfo.length) _log.bootstrap(`- Environments: ${envInfo.join(', ')}`);
|
||||
if (expFeatureInfo == null ? void 0 : expFeatureInfo.length) {
|
||||
_log.bootstrap(`- Experiments (use with caution):`);
|
||||
// only show a maximum number of flags
|
||||
for (const exp of expFeatureInfo.slice(0, maxExperimentalFeatures)){
|
||||
_log.bootstrap(` · ${exp}`);
|
||||
}
|
||||
/* indicate if there are more than the maximum shown no. flags */ if (expFeatureInfo.length > maxExperimentalFeatures) {
|
||||
_log.bootstrap(` · ...`);
|
||||
}
|
||||
}
|
||||
// New line after the bootstrap info
|
||||
_log.info('');
|
||||
}
|
||||
async function getStartServerInfo(dir, dev) {
|
||||
let expFeatureInfo = [];
|
||||
await (0, _config.default)(dev ? _constants.PHASE_DEVELOPMENT_SERVER : _constants.PHASE_PRODUCTION_BUILD, dir, {
|
||||
onLoadUserConfig (userConfig) {
|
||||
const userNextConfigExperimental = (0, _config.getEnabledExperimentalFeatures)(userConfig.experimental);
|
||||
expFeatureInfo = userNextConfigExperimental.sort((a, b)=>a.length - b.length);
|
||||
}
|
||||
});
|
||||
// we need to reset env if we are going to create
|
||||
// the worker process with the esm loader so that the
|
||||
// initial env state is correct
|
||||
let envInfo = [];
|
||||
const { loadedEnvFiles } = (0, _env.loadEnvConfig)(dir, true, console, false);
|
||||
if (loadedEnvFiles.length > 0) {
|
||||
envInfo = loadedEnvFiles.map((f)=>f.path);
|
||||
}
|
||||
return {
|
||||
envInfo,
|
||||
expFeatureInfo
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=app-info-log.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/app-info-log.ts"],"sourcesContent":["import { loadEnvConfig } from '@next/env'\nimport * as Log from '../../build/output/log'\nimport { bold, purple } from '../../lib/picocolors'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PHASE_PRODUCTION_BUILD,\n} from '../../shared/lib/constants'\nimport loadConfig, { getEnabledExperimentalFeatures } from '../config'\n\nexport function logStartInfo({\n networkUrl,\n appUrl,\n envInfo,\n expFeatureInfo,\n maxExperimentalFeatures = Infinity,\n}: {\n networkUrl: string | null\n appUrl: string | null\n envInfo?: string[]\n expFeatureInfo?: string[]\n maxExperimentalFeatures?: number\n}) {\n Log.bootstrap(\n `${bold(\n purple(`${Log.prefixes.ready} Next.js ${process.env.__NEXT_VERSION}`)\n )}${process.env.TURBOPACK ? ' (Turbopack)' : ''}`\n )\n if (appUrl) {\n Log.bootstrap(`- Local: ${appUrl}`)\n }\n if (networkUrl) {\n Log.bootstrap(`- Network: ${networkUrl}`)\n }\n if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`)\n\n if (expFeatureInfo?.length) {\n Log.bootstrap(`- Experiments (use with caution):`)\n // only show a maximum number of flags\n for (const exp of expFeatureInfo.slice(0, maxExperimentalFeatures)) {\n Log.bootstrap(` · ${exp}`)\n }\n /* indicate if there are more than the maximum shown no. flags */\n if (expFeatureInfo.length > maxExperimentalFeatures) {\n Log.bootstrap(` · ...`)\n }\n }\n\n // New line after the bootstrap info\n Log.info('')\n}\n\nexport async function getStartServerInfo(\n dir: string,\n dev: boolean\n): Promise<{\n envInfo?: string[]\n expFeatureInfo?: string[]\n}> {\n let expFeatureInfo: string[] = []\n await loadConfig(\n dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD,\n dir,\n {\n onLoadUserConfig(userConfig) {\n const userNextConfigExperimental = getEnabledExperimentalFeatures(\n userConfig.experimental\n )\n expFeatureInfo = userNextConfigExperimental.sort(\n (a, b) => a.length - b.length\n )\n },\n }\n )\n\n // we need to reset env if we are going to create\n // the worker process with the esm loader so that the\n // initial env state is correct\n let envInfo: string[] = []\n const { loadedEnvFiles } = loadEnvConfig(dir, true, console, false)\n if (loadedEnvFiles.length > 0) {\n envInfo = loadedEnvFiles.map((f) => f.path)\n }\n\n return {\n envInfo,\n expFeatureInfo,\n }\n}\n"],"names":["getStartServerInfo","logStartInfo","networkUrl","appUrl","envInfo","expFeatureInfo","maxExperimentalFeatures","Infinity","Log","bootstrap","bold","purple","prefixes","ready","process","env","__NEXT_VERSION","TURBOPACK","length","join","exp","slice","info","dir","dev","loadConfig","PHASE_DEVELOPMENT_SERVER","PHASE_PRODUCTION_BUILD","onLoadUserConfig","userConfig","userNextConfigExperimental","getEnabledExperimentalFeatures","experimental","sort","a","b","loadedEnvFiles","loadEnvConfig","console","map","f","path"],"mappings":";;;;;;;;;;;;;;;IAmDsBA,kBAAkB;eAAlBA;;IA1CNC,YAAY;eAAZA;;;qBATc;6DACT;4BACQ;2BAItB;gEACoD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEpD,SAASA,aAAa,EAC3BC,UAAU,EACVC,MAAM,EACNC,OAAO,EACPC,cAAc,EACdC,0BAA0BC,QAAQ,EAOnC;IACCC,KAAIC,SAAS,CACX,GAAGC,IAAAA,gBAAI,EACLC,IAAAA,kBAAM,EAAC,GAAGH,KAAII,QAAQ,CAACC,KAAK,CAAC,SAAS,EAAEC,QAAQC,GAAG,CAACC,cAAc,EAAE,KAClEF,QAAQC,GAAG,CAACE,SAAS,GAAG,iBAAiB,IAAI;IAEnD,IAAId,QAAQ;QACVK,KAAIC,SAAS,CAAC,CAAC,gBAAgB,EAAEN,QAAQ;IAC3C;IACA,IAAID,YAAY;QACdM,KAAIC,SAAS,CAAC,CAAC,gBAAgB,EAAEP,YAAY;IAC/C;IACA,IAAIE,2BAAAA,QAASc,MAAM,EAAEV,KAAIC,SAAS,CAAC,CAAC,gBAAgB,EAAEL,QAAQe,IAAI,CAAC,OAAO;IAE1E,IAAId,kCAAAA,eAAgBa,MAAM,EAAE;QAC1BV,KAAIC,SAAS,CAAC,CAAC,iCAAiC,CAAC;QACjD,sCAAsC;QACtC,KAAK,MAAMW,OAAOf,eAAegB,KAAK,CAAC,GAAGf,yBAA0B;YAClEE,KAAIC,SAAS,CAAC,CAAC,IAAI,EAAEW,KAAK;QAC5B;QACA,+DAA+D,GAC/D,IAAIf,eAAea,MAAM,GAAGZ,yBAAyB;YACnDE,KAAIC,SAAS,CAAC,CAAC,OAAO,CAAC;QACzB;IACF;IAEA,oCAAoC;IACpCD,KAAIc,IAAI,CAAC;AACX;AAEO,eAAetB,mBACpBuB,GAAW,EACXC,GAAY;IAKZ,IAAInB,iBAA2B,EAAE;IACjC,MAAMoB,IAAAA,eAAU,EACdD,MAAME,mCAAwB,GAAGC,iCAAsB,EACvDJ,KACA;QACEK,kBAAiBC,UAAU;YACzB,MAAMC,6BAA6BC,IAAAA,sCAA8B,EAC/DF,WAAWG,YAAY;YAEzB3B,iBAAiByB,2BAA2BG,IAAI,CAC9C,CAACC,GAAGC,IAAMD,EAAEhB,MAAM,GAAGiB,EAAEjB,MAAM;QAEjC;IACF;IAGF,iDAAiD;IACjD,qDAAqD;IACrD,+BAA+B;IAC/B,IAAId,UAAoB,EAAE;IAC1B,MAAM,EAAEgC,cAAc,EAAE,GAAGC,IAAAA,kBAAa,EAACd,KAAK,MAAMe,SAAS;IAC7D,IAAIF,eAAelB,MAAM,GAAG,GAAG;QAC7Bd,UAAUgC,eAAeG,GAAG,CAAC,CAACC,IAAMA,EAAEC,IAAI;IAC5C;IAEA,OAAO;QACLrC;QACAC;IACF;AACF"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export declare class AsyncCallbackSet {
|
||||
private callbacks;
|
||||
add(callback: () => Promise<void>): void;
|
||||
runAll(): Promise<void>;
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "AsyncCallbackSet", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return AsyncCallbackSet;
|
||||
}
|
||||
});
|
||||
class AsyncCallbackSet {
|
||||
add(callback) {
|
||||
this.callbacks.push(callback);
|
||||
}
|
||||
async runAll() {
|
||||
if (!this.callbacks.length) {
|
||||
return;
|
||||
}
|
||||
const callbacks = this.callbacks;
|
||||
this.callbacks = [];
|
||||
await Promise.allSettled(callbacks.map(// NOTE: wrapped in an async function to protect against synchronous exceptions
|
||||
async (f)=>f()));
|
||||
}
|
||||
constructor(){
|
||||
this.callbacks = [];
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=async-callback-set.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/async-callback-set.ts"],"sourcesContent":["export class AsyncCallbackSet {\n private callbacks: (() => Promise<void>)[] = []\n\n public add(callback: () => Promise<void>) {\n this.callbacks.push(callback)\n }\n\n public async runAll(): Promise<void> {\n if (!this.callbacks.length) {\n return\n }\n const callbacks = this.callbacks\n this.callbacks = []\n await Promise.allSettled(\n callbacks.map(\n // NOTE: wrapped in an async function to protect against synchronous exceptions\n async (f) => f()\n )\n )\n }\n}\n"],"names":["AsyncCallbackSet","add","callback","callbacks","push","runAll","length","Promise","allSettled","map","f"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA;IAGJC,IAAIC,QAA6B,EAAE;QACxC,IAAI,CAACC,SAAS,CAACC,IAAI,CAACF;IACtB;IAEA,MAAaG,SAAwB;QACnC,IAAI,CAAC,IAAI,CAACF,SAAS,CAACG,MAAM,EAAE;YAC1B;QACF;QACA,MAAMH,YAAY,IAAI,CAACA,SAAS;QAChC,IAAI,CAACA,SAAS,GAAG,EAAE;QACnB,MAAMI,QAAQC,UAAU,CACtBL,UAAUM,GAAG,CACX,+EAA+E;QAC/E,OAAOC,IAAMA;IAGnB;;aAlBQP,YAAqC,EAAE;;AAmBjD"}
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
import type { CacheHandler } from './types';
|
||||
declare const DefaultCacheHandler: CacheHandler;
|
||||
export default DefaultCacheHandler;
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
This is the default "use cache" handler it defaults
|
||||
to an in memory store
|
||||
*/ "use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "default", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return _default;
|
||||
}
|
||||
});
|
||||
const _lrucache = require("../lru-cache");
|
||||
const _tagsmanifestexternal = require("../incremental-cache/tags-manifest.external");
|
||||
// LRU cache default to max 50 MB but in future track
|
||||
const memoryCache = new _lrucache.LRUCache(50000000);
|
||||
const pendingSets = new Map();
|
||||
const DefaultCacheHandler = {
|
||||
async get (cacheKey, softTags) {
|
||||
await pendingSets.get(cacheKey);
|
||||
const privateEntry = memoryCache.get(cacheKey);
|
||||
if (!privateEntry) {
|
||||
return undefined;
|
||||
}
|
||||
const entry = privateEntry.entry;
|
||||
if (performance.timeOrigin + performance.now() > entry.timestamp + entry.revalidate * 1000) {
|
||||
// In memory caches should expire after revalidate time because it is unlikely that
|
||||
// a new entry will be able to be used before it is dropped from the cache.
|
||||
return undefined;
|
||||
}
|
||||
if ((0, _tagsmanifestexternal.isTagStale)(entry.tags, entry.timestamp) || (0, _tagsmanifestexternal.isTagStale)(softTags, entry.timestamp)) {
|
||||
return undefined;
|
||||
}
|
||||
const [returnStream, newSaved] = entry.value.tee();
|
||||
entry.value = newSaved;
|
||||
return {
|
||||
...entry,
|
||||
value: returnStream
|
||||
};
|
||||
},
|
||||
async set (cacheKey, pendingEntry) {
|
||||
let resolvePending = ()=>{};
|
||||
const pendingPromise = new Promise((resolve)=>{
|
||||
resolvePending = resolve;
|
||||
});
|
||||
pendingSets.set(cacheKey, pendingPromise);
|
||||
const entry = await pendingEntry;
|
||||
let size = 0;
|
||||
try {
|
||||
const [value, clonedValue] = entry.value.tee();
|
||||
entry.value = value;
|
||||
const reader = clonedValue.getReader();
|
||||
for(let chunk; !(chunk = await reader.read()).done;){
|
||||
size += Buffer.from(chunk.value).byteLength;
|
||||
}
|
||||
memoryCache.set(cacheKey, {
|
||||
entry,
|
||||
isErrored: false,
|
||||
errorRetryCount: 0,
|
||||
size
|
||||
});
|
||||
} catch (err) {
|
||||
console.error(`Error while saving cache key: ${cacheKey}`, err);
|
||||
// TODO: store partial buffer with error after we retry 3 times
|
||||
} finally{
|
||||
resolvePending();
|
||||
pendingSets.delete(cacheKey);
|
||||
}
|
||||
},
|
||||
async unstable_expireTags (...tags) {
|
||||
for (const tag of tags){
|
||||
if (!_tagsmanifestexternal.tagsManifest.items[tag]) {
|
||||
_tagsmanifestexternal.tagsManifest.items[tag] = {};
|
||||
}
|
||||
// TODO: use performance.now and update file-system-cache?
|
||||
_tagsmanifestexternal.tagsManifest.items[tag].revalidatedAt = Date.now();
|
||||
}
|
||||
},
|
||||
async receiveExpiredTags (...tags) {
|
||||
return this.unstable_expireTags(...tags);
|
||||
}
|
||||
};
|
||||
const _default = DefaultCacheHandler;
|
||||
|
||||
//# sourceMappingURL=default.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+34
@@ -0,0 +1,34 @@
|
||||
export interface CacheEntry {
|
||||
/**
|
||||
* The ReadableStream can error and only have partial
|
||||
* data so any cache handlers need to handle this case
|
||||
* and decide to keep the partial cache around or not
|
||||
*/
|
||||
value: ReadableStream<Uint8Array>;
|
||||
/**
|
||||
* The tags configured for the entry excluding soft tags
|
||||
*/
|
||||
tags: string[];
|
||||
/**
|
||||
* This is for the client not used to calculate cache entry expiration
|
||||
*/
|
||||
stale: number;
|
||||
/**
|
||||
* When the cache entry was created
|
||||
*/
|
||||
timestamp: number;
|
||||
/**
|
||||
* How long the entry can last (should be longer than revalidate)
|
||||
*/
|
||||
expire: number;
|
||||
/**
|
||||
* How long until the entry should revalidate
|
||||
*/
|
||||
revalidate: number;
|
||||
}
|
||||
export interface CacheHandler {
|
||||
get(cacheKey: string, softTags: string[]): Promise<undefined | CacheEntry>;
|
||||
set(cacheKey: string, entry: Promise<CacheEntry>): Promise<void>;
|
||||
unstable_expireTags(...tags: string[]): Promise<void>;
|
||||
receiveExpiredTags(...tags: string[]): Promise<void>;
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// In-memory caches are fragile and should not use stale-while-revalidate
|
||||
// semantics on the caches because it's not worth warming up an entry that's
|
||||
// likely going to get evicted before we get to use it anyway. However,
|
||||
// we also don't want to reuse a stale entry for too long so stale entries
|
||||
// should be considered expired/missing in such CacheHandlers.
|
||||
// This is the entry we store
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/cache-handlers/types.ts"],"sourcesContent":["// In-memory caches are fragile and should not use stale-while-revalidate\n// semantics on the caches because it's not worth warming up an entry that's\n// likely going to get evicted before we get to use it anyway. However,\n// we also don't want to reuse a stale entry for too long so stale entries\n// should be considered expired/missing in such CacheHandlers.\n\n// This is the entry we store\nexport interface CacheEntry {\n /**\n * The ReadableStream can error and only have partial\n * data so any cache handlers need to handle this case\n * and decide to keep the partial cache around or not\n */\n value: ReadableStream<Uint8Array>\n\n /**\n * The tags configured for the entry excluding soft tags\n */\n tags: string[]\n\n /**\n * This is for the client not used to calculate cache entry expiration\n */\n stale: number\n\n /**\n * When the cache entry was created\n */\n timestamp: number\n\n /**\n * How long the entry can last (should be longer than revalidate)\n */\n expire: number\n\n /**\n * How long until the entry should revalidate\n */\n revalidate: number\n}\n\nexport interface CacheHandler {\n get(cacheKey: string, softTags: string[]): Promise<undefined | CacheEntry>\n\n set(cacheKey: string, entry: Promise<CacheEntry>): Promise<void>\n\n // This is called when unstable_expireTags('') is called\n // and should update tags manifest accordingly\n unstable_expireTags(...tags: string[]): Promise<void>\n\n // This is called when an action request sends\n // NEXT_CACHE_REVALIDATED_TAGS_HEADER and tells\n // us these tags are expired and the manifest\n // should be updated this differs since in a multi\n // instance environment you don't propagate these\n // as they are request specific\n receiveExpiredTags(...tags: string[]): Promise<void>\n}\n"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAC5E,uEAAuE;AACvE,0EAA0E;AAC1E,8DAA8D;AAE9D,6BAA6B"}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Clones a response by teeing the body so we can return two independent
|
||||
* ReadableStreams from it. This avoids the bug in the undici library around
|
||||
* response cloning.
|
||||
*
|
||||
* After cloning, the original response's body will be consumed and closed.
|
||||
*
|
||||
* @see https://github.com/vercel/next.js/pull/73274
|
||||
*
|
||||
* @param original - The original response to clone.
|
||||
* @returns A tuple containing two independent clones of the original response.
|
||||
*/
|
||||
export declare function cloneResponse(original: Response): [Response, Response];
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Clones a response by teeing the body so we can return two independent
|
||||
* ReadableStreams from it. This avoids the bug in the undici library around
|
||||
* response cloning.
|
||||
*
|
||||
* After cloning, the original response's body will be consumed and closed.
|
||||
*
|
||||
* @see https://github.com/vercel/next.js/pull/73274
|
||||
*
|
||||
* @param original - The original response to clone.
|
||||
* @returns A tuple containing two independent clones of the original response.
|
||||
*/ "use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "cloneResponse", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return cloneResponse;
|
||||
}
|
||||
});
|
||||
function cloneResponse(original) {
|
||||
// If the response has no body, then we can just return the original response
|
||||
// twice because it's immutable.
|
||||
if (!original.body) {
|
||||
return [
|
||||
original,
|
||||
original
|
||||
];
|
||||
}
|
||||
const [body1, body2] = original.body.tee();
|
||||
const cloned1 = new Response(body1, {
|
||||
status: original.status,
|
||||
statusText: original.statusText,
|
||||
headers: original.headers
|
||||
});
|
||||
Object.defineProperty(cloned1, 'url', {
|
||||
value: original.url
|
||||
});
|
||||
const cloned2 = new Response(body2, {
|
||||
status: original.status,
|
||||
statusText: original.statusText,
|
||||
headers: original.headers
|
||||
});
|
||||
Object.defineProperty(cloned2, 'url', {
|
||||
value: original.url
|
||||
});
|
||||
return [
|
||||
cloned1,
|
||||
cloned2
|
||||
];
|
||||
}
|
||||
|
||||
//# sourceMappingURL=clone-response.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/clone-response.ts"],"sourcesContent":["/**\n * Clones a response by teeing the body so we can return two independent\n * ReadableStreams from it. This avoids the bug in the undici library around\n * response cloning.\n *\n * After cloning, the original response's body will be consumed and closed.\n *\n * @see https://github.com/vercel/next.js/pull/73274\n *\n * @param original - The original response to clone.\n * @returns A tuple containing two independent clones of the original response.\n */\nexport function cloneResponse(original: Response): [Response, Response] {\n // If the response has no body, then we can just return the original response\n // twice because it's immutable.\n if (!original.body) {\n return [original, original]\n }\n\n const [body1, body2] = original.body.tee()\n\n const cloned1 = new Response(body1, {\n status: original.status,\n statusText: original.statusText,\n headers: original.headers,\n })\n\n Object.defineProperty(cloned1, 'url', {\n value: original.url,\n })\n\n const cloned2 = new Response(body2, {\n status: original.status,\n statusText: original.statusText,\n headers: original.headers,\n })\n\n Object.defineProperty(cloned2, 'url', {\n value: original.url,\n })\n\n return [cloned1, cloned2]\n}\n"],"names":["cloneResponse","original","body","body1","body2","tee","cloned1","Response","status","statusText","headers","Object","defineProperty","value","url","cloned2"],"mappings":"AAAA;;;;;;;;;;;CAWC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,cAAcC,QAAkB;IAC9C,6EAA6E;IAC7E,gCAAgC;IAChC,IAAI,CAACA,SAASC,IAAI,EAAE;QAClB,OAAO;YAACD;YAAUA;SAAS;IAC7B;IAEA,MAAM,CAACE,OAAOC,MAAM,GAAGH,SAASC,IAAI,CAACG,GAAG;IAExC,MAAMC,UAAU,IAAIC,SAASJ,OAAO;QAClCK,QAAQP,SAASO,MAAM;QACvBC,YAAYR,SAASQ,UAAU;QAC/BC,SAAST,SAASS,OAAO;IAC3B;IAEAC,OAAOC,cAAc,CAACN,SAAS,OAAO;QACpCO,OAAOZ,SAASa,GAAG;IACrB;IAEA,MAAMC,UAAU,IAAIR,SAASH,OAAO;QAClCI,QAAQP,SAASO,MAAM;QACvBC,YAAYR,SAASQ,UAAU;QAC/BC,SAAST,SAASS,OAAO;IAC3B;IAEAC,OAAOC,cAAc,CAACG,SAAS,OAAO;QACpCF,OAAOZ,SAASa,GAAG;IACrB;IAEA,OAAO;QAACR;QAASS;KAAQ;AAC3B"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
declare const privateCpuProfileName: string | undefined;
|
||||
declare const isCpuProfileEnabled: string | undefined;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
const privateCpuProfileName = process.env.__NEXT_PRIVATE_CPU_PROFILE;
|
||||
const isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName;
|
||||
if (isCpuProfileEnabled) {
|
||||
const { Session } = require('inspector');
|
||||
const fs = require('fs');
|
||||
const session = new Session();
|
||||
session.connect();
|
||||
session.post('Profiler.enable');
|
||||
session.post('Profiler.start');
|
||||
function saveProfile() {
|
||||
session.post('Profiler.stop', (error, param)=>{
|
||||
if (error) {
|
||||
console.error('Cannot generate CPU profiling:', error);
|
||||
return;
|
||||
}
|
||||
// Write profile to disk
|
||||
const filename = `${privateCpuProfileName || 'CPU.main'}.${Date.now()}.cpuprofile`;
|
||||
fs.writeFileSync(`./${filename}`, JSON.stringify(param.profile));
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
process.on('SIGINT', saveProfile);
|
||||
process.on('SIGTERM', saveProfile);
|
||||
process.on('exit', saveProfile);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=cpu-profile.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/cpu-profile.ts"],"sourcesContent":["const privateCpuProfileName = process.env.__NEXT_PRIVATE_CPU_PROFILE\nconst isCpuProfileEnabled = process.env.NEXT_CPU_PROF || privateCpuProfileName\n\nif (isCpuProfileEnabled) {\n const { Session } = require('inspector') as typeof import('inspector')\n const fs = require('fs')\n\n const session = new Session()\n session.connect()\n\n session.post('Profiler.enable')\n session.post('Profiler.start')\n\n function saveProfile() {\n session.post('Profiler.stop', (error, param) => {\n if (error) {\n console.error('Cannot generate CPU profiling:', error)\n return\n }\n\n // Write profile to disk\n const filename = `${\n privateCpuProfileName || 'CPU.main'\n }.${Date.now()}.cpuprofile`\n fs.writeFileSync(`./${filename}`, JSON.stringify(param.profile))\n process.exit(0)\n })\n }\n process.on('SIGINT', saveProfile)\n process.on('SIGTERM', saveProfile)\n process.on('exit', saveProfile)\n}\n"],"names":["privateCpuProfileName","process","env","__NEXT_PRIVATE_CPU_PROFILE","isCpuProfileEnabled","NEXT_CPU_PROF","Session","require","fs","session","connect","post","saveProfile","error","param","console","filename","Date","now","writeFileSync","JSON","stringify","profile","exit","on"],"mappings":";AAAA,MAAMA,wBAAwBC,QAAQC,GAAG,CAACC,0BAA0B;AACpE,MAAMC,sBAAsBH,QAAQC,GAAG,CAACG,aAAa,IAAIL;AAEzD,IAAII,qBAAqB;IACvB,MAAM,EAAEE,OAAO,EAAE,GAAGC,QAAQ;IAC5B,MAAMC,KAAKD,QAAQ;IAEnB,MAAME,UAAU,IAAIH;IACpBG,QAAQC,OAAO;IAEfD,QAAQE,IAAI,CAAC;IACbF,QAAQE,IAAI,CAAC;IAEb,SAASC;QACPH,QAAQE,IAAI,CAAC,iBAAiB,CAACE,OAAOC;YACpC,IAAID,OAAO;gBACTE,QAAQF,KAAK,CAAC,kCAAkCA;gBAChD;YACF;YAEA,wBAAwB;YACxB,MAAMG,WAAW,GACfhB,yBAAyB,WAC1B,CAAC,EAAEiB,KAAKC,GAAG,GAAG,WAAW,CAAC;YAC3BV,GAAGW,aAAa,CAAC,CAAC,EAAE,EAAEH,UAAU,EAAEI,KAAKC,SAAS,CAACP,MAAMQ,OAAO;YAC9DrB,QAAQsB,IAAI,CAAC;QACf;IACF;IACAtB,QAAQuB,EAAE,CAAC,UAAUZ;IACrBX,QAAQuB,EAAE,CAAC,WAAWZ;IACtBX,QAAQuB,EAAE,CAAC,QAAQZ;AACrB"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function createDedupeFetch(originalFetch: typeof fetch): (resource: URL | RequestInfo, options?: RequestInit) => Promise<Response>;
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
/**
|
||||
* Based on https://github.com/facebook/react/blob/d4e78c42a94be027b4dc7ed2659a5fddfbf9bd4e/packages/react/src/ReactFetch.js
|
||||
*/ "use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "createDedupeFetch", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return createDedupeFetch;
|
||||
}
|
||||
});
|
||||
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
|
||||
const _cloneresponse = require("./clone-response");
|
||||
const _invarianterror = require("../../shared/lib/invariant-error");
|
||||
function _getRequireWildcardCache(nodeInterop) {
|
||||
if (typeof WeakMap !== "function") return null;
|
||||
var cacheBabelInterop = new WeakMap();
|
||||
var cacheNodeInterop = new WeakMap();
|
||||
return (_getRequireWildcardCache = function(nodeInterop) {
|
||||
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
|
||||
})(nodeInterop);
|
||||
}
|
||||
function _interop_require_wildcard(obj, nodeInterop) {
|
||||
if (!nodeInterop && obj && obj.__esModule) {
|
||||
return obj;
|
||||
}
|
||||
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
|
||||
return {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
var cache = _getRequireWildcardCache(nodeInterop);
|
||||
if (cache && cache.has(obj)) {
|
||||
return cache.get(obj);
|
||||
}
|
||||
var newObj = {
|
||||
__proto__: null
|
||||
};
|
||||
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
|
||||
for(var key in obj){
|
||||
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
|
||||
if (desc && (desc.get || desc.set)) {
|
||||
Object.defineProperty(newObj, key, desc);
|
||||
} else {
|
||||
newObj[key] = obj[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
newObj.default = obj;
|
||||
if (cache) {
|
||||
cache.set(obj, newObj);
|
||||
}
|
||||
return newObj;
|
||||
}
|
||||
const simpleCacheKey = '["GET",[],null,"follow",null,null,null,null]' // generateCacheKey(new Request('https://blank'));
|
||||
;
|
||||
function generateCacheKey(request) {
|
||||
// We pick the fields that goes into the key used to dedupe requests.
|
||||
// We don't include the `cache` field, because we end up using whatever
|
||||
// caching resulted from the first request.
|
||||
// Notably we currently don't consider non-standard (or future) options.
|
||||
// This might not be safe. TODO: warn for non-standard extensions differing.
|
||||
// IF YOU CHANGE THIS UPDATE THE simpleCacheKey ABOVE.
|
||||
return JSON.stringify([
|
||||
request.method,
|
||||
Array.from(request.headers.entries()),
|
||||
request.mode,
|
||||
request.redirect,
|
||||
request.credentials,
|
||||
request.referrer,
|
||||
request.referrerPolicy,
|
||||
request.integrity
|
||||
]);
|
||||
}
|
||||
function createDedupeFetch(originalFetch) {
|
||||
const getCacheEntries = _react.cache(// eslint-disable-next-line @typescript-eslint/no-unused-vars -- url is the cache key
|
||||
(url)=>[]);
|
||||
return function dedupeFetch(resource, options) {
|
||||
if (options && options.signal) {
|
||||
// If we're passed a signal, then we assume that
|
||||
// someone else controls the lifetime of this object and opts out of
|
||||
// caching. It's effectively the opt-out mechanism.
|
||||
// Ideally we should be able to check this on the Request but
|
||||
// it always gets initialized with its own signal so we don't
|
||||
// know if it's supposed to override - unless we also override the
|
||||
// Request constructor.
|
||||
return originalFetch(resource, options);
|
||||
}
|
||||
// Normalize the Request
|
||||
let url;
|
||||
let cacheKey;
|
||||
if (typeof resource === 'string' && !options) {
|
||||
// Fast path.
|
||||
cacheKey = simpleCacheKey;
|
||||
url = resource;
|
||||
} else {
|
||||
// Normalize the request.
|
||||
// if resource is not a string or a URL (its an instance of Request)
|
||||
// then do not instantiate a new Request but instead
|
||||
// reuse the request as to not disturb the body in the event it's a ReadableStream.
|
||||
const request = typeof resource === 'string' || resource instanceof URL ? new Request(resource, options) : resource;
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD' || request.keepalive) {
|
||||
// We currently don't dedupe requests that might have side-effects. Those
|
||||
// have to be explicitly cached. We assume that the request doesn't have a
|
||||
// body if it's GET or HEAD.
|
||||
// keepalive gets treated the same as if you passed a custom cache signal.
|
||||
return originalFetch(resource, options);
|
||||
}
|
||||
cacheKey = generateCacheKey(request);
|
||||
url = request.url;
|
||||
}
|
||||
const cacheEntries = getCacheEntries(url);
|
||||
for(let i = 0, j = cacheEntries.length; i < j; i += 1){
|
||||
const [key, promise] = cacheEntries[i];
|
||||
if (key === cacheKey) {
|
||||
return promise.then(()=>{
|
||||
const response = cacheEntries[i][2];
|
||||
if (!response) throw new _invarianterror.InvariantError('No cached response');
|
||||
// We're cloning the response using this utility because there exists
|
||||
// a bug in the undici library around response cloning. See the
|
||||
// following pull request for more details:
|
||||
// https://github.com/vercel/next.js/pull/73274
|
||||
const [cloned1, cloned2] = (0, _cloneresponse.cloneResponse)(response);
|
||||
cacheEntries[i][2] = cloned2;
|
||||
return cloned1;
|
||||
});
|
||||
}
|
||||
}
|
||||
// We pass the original arguments here in case normalizing the Request
|
||||
// doesn't include all the options in this environment.
|
||||
const promise = originalFetch(resource, options);
|
||||
const entry = [
|
||||
cacheKey,
|
||||
promise,
|
||||
null
|
||||
];
|
||||
cacheEntries.push(entry);
|
||||
return promise.then((response)=>{
|
||||
// We're cloning the response using this utility because there exists
|
||||
// a bug in the undici library around response cloning. See the
|
||||
// following pull request for more details:
|
||||
// https://github.com/vercel/next.js/pull/73274
|
||||
const [cloned1, cloned2] = (0, _cloneresponse.cloneResponse)(response);
|
||||
entry[2] = cloned2;
|
||||
return cloned1;
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=dedupe-fetch.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+25
@@ -0,0 +1,25 @@
|
||||
import type { IncomingMessage } from 'http';
|
||||
import type { DevBundler } from './router-utils/setup-dev-bundler';
|
||||
import type { WorkerRequestHandler } from './types';
|
||||
import { LRUCache } from './lru-cache';
|
||||
/**
|
||||
* The DevBundlerService provides an interface to perform tasks with the
|
||||
* bundler while in development.
|
||||
*/
|
||||
export declare class DevBundlerService {
|
||||
private readonly bundler;
|
||||
private readonly handler;
|
||||
appIsrManifestInner: InstanceType<typeof LRUCache>;
|
||||
constructor(bundler: DevBundler, handler: WorkerRequestHandler);
|
||||
ensurePage: typeof this.bundler.hotReloader.ensurePage;
|
||||
logErrorWithOriginalStack: (err: unknown, type?: "unhandledRejection" | "uncaughtException" | "warning" | "app-dir") => void;
|
||||
getFallbackErrorComponents(url?: string): Promise<void>;
|
||||
getCompilationError(page: string): Promise<any>;
|
||||
revalidate({ urlPath, revalidateHeaders, opts: revalidateOpts, }: {
|
||||
urlPath: string;
|
||||
revalidateHeaders: IncomingMessage['headers'];
|
||||
opts: any;
|
||||
}): Promise<{}>;
|
||||
get appIsrManifest(): Record<string, boolean>;
|
||||
setAppIsrStatus(key: string, value: boolean | null): void;
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "DevBundlerService", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return DevBundlerService;
|
||||
}
|
||||
});
|
||||
const _lrucache = require("./lru-cache");
|
||||
const _mockrequest = require("./mock-request");
|
||||
const _hotreloadertypes = require("../dev/hot-reloader-types");
|
||||
class DevBundlerService {
|
||||
constructor(bundler, handler){
|
||||
this.bundler = bundler;
|
||||
this.handler = handler;
|
||||
this.ensurePage = async (definition)=>{
|
||||
// TODO: remove after ensure is pulled out of server
|
||||
return await this.bundler.hotReloader.ensurePage(definition);
|
||||
};
|
||||
this.logErrorWithOriginalStack = this.bundler.logErrorWithOriginalStack.bind(this.bundler);
|
||||
this.appIsrManifestInner = new _lrucache.LRUCache(8000, function length() {
|
||||
return 16;
|
||||
});
|
||||
}
|
||||
async getFallbackErrorComponents(url) {
|
||||
await this.bundler.hotReloader.buildFallbackError();
|
||||
// Build the error page to ensure the fallback is built too.
|
||||
// TODO: See if this can be moved into hotReloader or removed.
|
||||
await this.bundler.hotReloader.ensurePage({
|
||||
page: '/_error',
|
||||
clientOnly: false,
|
||||
definition: undefined,
|
||||
url
|
||||
});
|
||||
}
|
||||
async getCompilationError(page) {
|
||||
const errors = await this.bundler.hotReloader.getCompilationErrors(page);
|
||||
if (!errors) return;
|
||||
// Return the very first error we found.
|
||||
return errors[0];
|
||||
}
|
||||
async revalidate({ urlPath, revalidateHeaders, opts: revalidateOpts }) {
|
||||
const mocked = (0, _mockrequest.createRequestResponseMocks)({
|
||||
url: urlPath,
|
||||
headers: revalidateHeaders
|
||||
});
|
||||
await this.handler(mocked.req, mocked.res);
|
||||
await mocked.res.hasStreamed;
|
||||
if (mocked.res.getHeader('x-nextjs-cache') !== 'REVALIDATED' && !(mocked.res.statusCode === 404 && revalidateOpts.unstable_onlyGenerated)) {
|
||||
throw new Error(`Invalid response ${mocked.res.statusCode}`);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
get appIsrManifest() {
|
||||
const serializableManifest = {};
|
||||
for (const key of this.appIsrManifestInner.keys()){
|
||||
serializableManifest[key] = this.appIsrManifestInner.get(key);
|
||||
}
|
||||
return serializableManifest;
|
||||
}
|
||||
setAppIsrStatus(key, value) {
|
||||
var _this_bundler_hotReloader, _this_bundler;
|
||||
if (value === null) {
|
||||
this.appIsrManifestInner.remove(key);
|
||||
} else {
|
||||
this.appIsrManifestInner.set(key, value);
|
||||
}
|
||||
(_this_bundler = this.bundler) == null ? void 0 : (_this_bundler_hotReloader = _this_bundler.hotReloader) == null ? void 0 : _this_bundler_hotReloader.send({
|
||||
action: _hotreloadertypes.HMR_ACTIONS_SENT_TO_BROWSER.APP_ISR_MANIFEST,
|
||||
data: this.appIsrManifest
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=dev-bundler-service.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+11
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* FNV-1a Hash implementation
|
||||
* @author Travis Webb (tjwebb) <me@traviswebb.com>
|
||||
*
|
||||
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
|
||||
*
|
||||
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
|
||||
* and still making use of Javascript's 53-bit integer space.
|
||||
*/
|
||||
export declare const fnv1a52: (str: string) => number;
|
||||
export declare const generateETag: (payload: string, weak?: boolean) => string;
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* FNV-1a Hash implementation
|
||||
* @author Travis Webb (tjwebb) <me@traviswebb.com>
|
||||
*
|
||||
* Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js
|
||||
*
|
||||
* Simplified, optimized and add modified for 52 bit, which provides a larger hash space
|
||||
* and still making use of Javascript's 53-bit integer space.
|
||||
*/ "use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
fnv1a52: null,
|
||||
generateETag: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
fnv1a52: function() {
|
||||
return fnv1a52;
|
||||
},
|
||||
generateETag: function() {
|
||||
return generateETag;
|
||||
}
|
||||
});
|
||||
const fnv1a52 = (str)=>{
|
||||
const len = str.length;
|
||||
let i = 0, t0 = 0, v0 = 0x2325, t1 = 0, v1 = 0x8422, t2 = 0, v2 = 0x9ce4, t3 = 0, v3 = 0xcbf2;
|
||||
while(i < len){
|
||||
v0 ^= str.charCodeAt(i++);
|
||||
t0 = v0 * 435;
|
||||
t1 = v1 * 435;
|
||||
t2 = v2 * 435;
|
||||
t3 = v3 * 435;
|
||||
t2 += v0 << 8;
|
||||
t3 += v1 << 8;
|
||||
t1 += t0 >>> 16;
|
||||
v0 = t0 & 65535;
|
||||
t2 += t1 >>> 16;
|
||||
v1 = t1 & 65535;
|
||||
v3 = t3 + (t2 >>> 16) & 65535;
|
||||
v2 = t2 & 65535;
|
||||
}
|
||||
return (v3 & 15) * 281474976710656 + v2 * 4294967296 + v1 * 65536 + (v0 ^ v3 >> 4);
|
||||
};
|
||||
const generateETag = (payload, weak = false)=>{
|
||||
const prefix = weak ? 'W/"' : '"';
|
||||
return prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '"';
|
||||
};
|
||||
|
||||
//# sourceMappingURL=etag.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/etag.ts"],"sourcesContent":["/**\n * FNV-1a Hash implementation\n * @author Travis Webb (tjwebb) <me@traviswebb.com>\n *\n * Ported from https://github.com/tjwebb/fnv-plus/blob/master/index.js\n *\n * Simplified, optimized and add modified for 52 bit, which provides a larger hash space\n * and still making use of Javascript's 53-bit integer space.\n */\nexport const fnv1a52 = (str: string) => {\n const len = str.length\n let i = 0,\n t0 = 0,\n v0 = 0x2325,\n t1 = 0,\n v1 = 0x8422,\n t2 = 0,\n v2 = 0x9ce4,\n t3 = 0,\n v3 = 0xcbf2\n\n while (i < len) {\n v0 ^= str.charCodeAt(i++)\n t0 = v0 * 435\n t1 = v1 * 435\n t2 = v2 * 435\n t3 = v3 * 435\n t2 += v0 << 8\n t3 += v1 << 8\n t1 += t0 >>> 16\n v0 = t0 & 65535\n t2 += t1 >>> 16\n v1 = t1 & 65535\n v3 = (t3 + (t2 >>> 16)) & 65535\n v2 = t2 & 65535\n }\n\n return (\n (v3 & 15) * 281474976710656 +\n v2 * 4294967296 +\n v1 * 65536 +\n (v0 ^ (v3 >> 4))\n )\n}\n\nexport const generateETag = (payload: string, weak = false) => {\n const prefix = weak ? 'W/\"' : '\"'\n return (\n prefix + fnv1a52(payload).toString(36) + payload.length.toString(36) + '\"'\n )\n}\n"],"names":["fnv1a52","generateETag","str","len","length","i","t0","v0","t1","v1","t2","v2","t3","v3","charCodeAt","payload","weak","prefix","toString"],"mappings":"AAAA;;;;;;;;CAQC;;;;;;;;;;;;;;;IACYA,OAAO;eAAPA;;IAoCAC,YAAY;eAAZA;;;AApCN,MAAMD,UAAU,CAACE;IACtB,MAAMC,MAAMD,IAAIE,MAAM;IACtB,IAAIC,IAAI,GACNC,KAAK,GACLC,KAAK,QACLC,KAAK,GACLC,KAAK,QACLC,KAAK,GACLC,KAAK,QACLC,KAAK,GACLC,KAAK;IAEP,MAAOR,IAAIF,IAAK;QACdI,MAAML,IAAIY,UAAU,CAACT;QACrBC,KAAKC,KAAK;QACVC,KAAKC,KAAK;QACVC,KAAKC,KAAK;QACVC,KAAKC,KAAK;QACVH,MAAMH,MAAM;QACZK,MAAMH,MAAM;QACZD,MAAMF,OAAO;QACbC,KAAKD,KAAK;QACVI,MAAMF,OAAO;QACbC,KAAKD,KAAK;QACVK,KAAK,AAACD,KAAMF,CAAAA,OAAO,EAAC,IAAM;QAC1BC,KAAKD,KAAK;IACZ;IAEA,OACE,AAACG,CAAAA,KAAK,EAAC,IAAK,kBACZF,KAAK,aACLF,KAAK,QACJF,CAAAA,KAAMM,MAAM,CAAC;AAElB;AAEO,MAAMZ,eAAe,CAACc,SAAiBC,OAAO,KAAK;IACxD,MAAMC,SAASD,OAAO,QAAQ;IAC9B,OACEC,SAASjB,QAAQe,SAASG,QAAQ,CAAC,MAAMH,QAAQX,MAAM,CAACc,QAAQ,CAAC,MAAM;AAE3E"}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { LoadedEnvFiles } from '@next/env';
|
||||
export declare function createEnvDefinitions({ distDir, loadedEnvFiles, }: {
|
||||
distDir: string;
|
||||
loadedEnvFiles: LoadedEnvFiles;
|
||||
}): Promise<string | undefined>;
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "createEnvDefinitions", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return createEnvDefinitions;
|
||||
}
|
||||
});
|
||||
const _nodepath = require("node:path");
|
||||
const _promises = require("node:fs/promises");
|
||||
async function createEnvDefinitions({ distDir, loadedEnvFiles }) {
|
||||
const envLines = [];
|
||||
const seenKeys = new Set();
|
||||
// env files are in order of priority
|
||||
for (const { path, env } of loadedEnvFiles){
|
||||
for(const key in env){
|
||||
if (!seenKeys.has(key)) {
|
||||
envLines.push(` /** Loaded from \`${path}\` */`);
|
||||
envLines.push(` ${key}?: string`);
|
||||
seenKeys.add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
const envStr = envLines.join('\n');
|
||||
const definitionStr = `// Type definitions for Next.js environment variables
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
interface ProcessEnv {
|
||||
${envStr}
|
||||
}
|
||||
}
|
||||
}
|
||||
export {}`;
|
||||
if (process.env.NODE_ENV === 'test') {
|
||||
return definitionStr;
|
||||
}
|
||||
try {
|
||||
// we expect the types directory to already exist
|
||||
const envDtsPath = (0, _nodepath.join)(distDir, 'types', 'env.d.ts');
|
||||
// do not await, this is not essential for further process
|
||||
(0, _promises.writeFile)(envDtsPath, definitionStr, 'utf-8');
|
||||
} catch (e) {
|
||||
console.error('Failed to write env.d.ts:', e);
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=create-env-definitions.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/experimental/create-env-definitions.ts"],"sourcesContent":["import type { LoadedEnvFiles } from '@next/env'\nimport { join } from 'node:path'\nimport { writeFile } from 'node:fs/promises'\n\nexport async function createEnvDefinitions({\n distDir,\n loadedEnvFiles,\n}: {\n distDir: string\n loadedEnvFiles: LoadedEnvFiles\n}) {\n const envLines = []\n const seenKeys = new Set()\n // env files are in order of priority\n for (const { path, env } of loadedEnvFiles) {\n for (const key in env) {\n if (!seenKeys.has(key)) {\n envLines.push(` /** Loaded from \\`${path}\\` */`)\n envLines.push(` ${key}?: string`)\n seenKeys.add(key)\n }\n }\n }\n const envStr = envLines.join('\\n')\n\n const definitionStr = `// Type definitions for Next.js environment variables\ndeclare global {\n namespace NodeJS {\n interface ProcessEnv {\n${envStr}\n }\n }\n}\nexport {}`\n\n if (process.env.NODE_ENV === 'test') {\n return definitionStr\n }\n\n try {\n // we expect the types directory to already exist\n const envDtsPath = join(distDir, 'types', 'env.d.ts')\n // do not await, this is not essential for further process\n writeFile(envDtsPath, definitionStr, 'utf-8')\n } catch (e) {\n console.error('Failed to write env.d.ts:', e)\n }\n}\n"],"names":["createEnvDefinitions","distDir","loadedEnvFiles","envLines","seenKeys","Set","path","env","key","has","push","add","envStr","join","definitionStr","process","NODE_ENV","envDtsPath","writeFile","e","console","error"],"mappings":";;;;+BAIsBA;;;eAAAA;;;0BAHD;0BACK;AAEnB,eAAeA,qBAAqB,EACzCC,OAAO,EACPC,cAAc,EAIf;IACC,MAAMC,WAAW,EAAE;IACnB,MAAMC,WAAW,IAAIC;IACrB,qCAAqC;IACrC,KAAK,MAAM,EAAEC,IAAI,EAAEC,GAAG,EAAE,IAAIL,eAAgB;QAC1C,IAAK,MAAMM,OAAOD,IAAK;YACrB,IAAI,CAACH,SAASK,GAAG,CAACD,MAAM;gBACtBL,SAASO,IAAI,CAAC,CAAC,wBAAwB,EAAEJ,KAAK,KAAK,CAAC;gBACpDH,SAASO,IAAI,CAAC,CAAC,MAAM,EAAEF,IAAI,SAAS,CAAC;gBACrCJ,SAASO,GAAG,CAACH;YACf;QACF;IACF;IACA,MAAMI,SAAST,SAASU,IAAI,CAAC;IAE7B,MAAMC,gBAAgB,CAAC;;;;AAIzB,EAAEF,OAAO;;;;SAIA,CAAC;IAER,IAAIG,QAAQR,GAAG,CAACS,QAAQ,KAAK,QAAQ;QACnC,OAAOF;IACT;IAEA,IAAI;QACF,iDAAiD;QACjD,MAAMG,aAAaJ,IAAAA,cAAI,EAACZ,SAAS,SAAS;QAC1C,0DAA0D;QAC1DiB,IAAAA,mBAAS,EAACD,YAAYH,eAAe;IACvC,EAAE,OAAOK,GAAG;QACVC,QAAQC,KAAK,CAAC,6BAA6BF;IAC7C;AACF"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* If set to `incremental`, only those leaf pages that export
|
||||
* `experimental_ppr = true` will have partial prerendering enabled. If any
|
||||
* page exports this value as `false` or does not export it at all will not
|
||||
* have partial prerendering enabled. If set to a boolean, it the options for
|
||||
* `experimental_ppr` will be ignored.
|
||||
*/
|
||||
export type ExperimentalPPRConfig = boolean | 'incremental';
|
||||
/**
|
||||
* Returns true if partial prerendering is enabled for the application. It does
|
||||
* not tell you if a given route has PPR enabled, as that requires analysis of
|
||||
* the route's configuration.
|
||||
*
|
||||
* @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.
|
||||
*/
|
||||
export declare function checkIsAppPPREnabled(config: ExperimentalPPRConfig | undefined): boolean;
|
||||
/**
|
||||
* Returns true if partial prerendering is supported for the current page with
|
||||
* the provided app configuration. If the application doesn't have partial
|
||||
* prerendering enabled, this function will always return false. If you want to
|
||||
* check if the application has partial prerendering enabled
|
||||
*
|
||||
* @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.
|
||||
*/
|
||||
export declare function checkIsRoutePPREnabled(config: ExperimentalPPRConfig | undefined, appConfig: {
|
||||
experimental_ppr?: boolean;
|
||||
}): boolean;
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* If set to `incremental`, only those leaf pages that export
|
||||
* `experimental_ppr = true` will have partial prerendering enabled. If any
|
||||
* page exports this value as `false` or does not export it at all will not
|
||||
* have partial prerendering enabled. If set to a boolean, it the options for
|
||||
* `experimental_ppr` will be ignored.
|
||||
*/ "use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
checkIsAppPPREnabled: null,
|
||||
checkIsRoutePPREnabled: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
checkIsAppPPREnabled: function() {
|
||||
return checkIsAppPPREnabled;
|
||||
},
|
||||
checkIsRoutePPREnabled: function() {
|
||||
return checkIsRoutePPREnabled;
|
||||
}
|
||||
});
|
||||
function checkIsAppPPREnabled(config) {
|
||||
// If the config is undefined, partial prerendering is disabled.
|
||||
if (typeof config === 'undefined') return false;
|
||||
// If the config is a boolean, use it directly.
|
||||
if (typeof config === 'boolean') return config;
|
||||
// If the config is a string, it must be 'incremental' to enable partial
|
||||
// prerendering.
|
||||
if (config === 'incremental') return true;
|
||||
return false;
|
||||
}
|
||||
function checkIsRoutePPREnabled(config, appConfig) {
|
||||
// If the config is undefined, partial prerendering is disabled.
|
||||
if (typeof config === 'undefined') return false;
|
||||
// If the config is a boolean, use it directly.
|
||||
if (typeof config === 'boolean') return config;
|
||||
// If the config is a string, it must be 'incremental' to enable partial
|
||||
// prerendering.
|
||||
if (config === 'incremental' && appConfig.experimental_ppr === true) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=ppr.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/experimental/ppr.ts"],"sourcesContent":["/**\n * If set to `incremental`, only those leaf pages that export\n * `experimental_ppr = true` will have partial prerendering enabled. If any\n * page exports this value as `false` or does not export it at all will not\n * have partial prerendering enabled. If set to a boolean, it the options for\n * `experimental_ppr` will be ignored.\n */\n\nexport type ExperimentalPPRConfig = boolean | 'incremental'\n\n/**\n * Returns true if partial prerendering is enabled for the application. It does\n * not tell you if a given route has PPR enabled, as that requires analysis of\n * the route's configuration.\n *\n * @see {@link checkIsRoutePPREnabled} - for checking if a specific route has PPR enabled.\n */\nexport function checkIsAppPPREnabled(\n config: ExperimentalPPRConfig | undefined\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n // If the config is a string, it must be 'incremental' to enable partial\n // prerendering.\n if (config === 'incremental') return true\n\n return false\n}\n\n/**\n * Returns true if partial prerendering is supported for the current page with\n * the provided app configuration. If the application doesn't have partial\n * prerendering enabled, this function will always return false. If you want to\n * check if the application has partial prerendering enabled\n *\n * @see {@link checkIsAppPPREnabled} for checking if the application has PPR enabled.\n */\nexport function checkIsRoutePPREnabled(\n config: ExperimentalPPRConfig | undefined,\n appConfig: {\n experimental_ppr?: boolean\n }\n): boolean {\n // If the config is undefined, partial prerendering is disabled.\n if (typeof config === 'undefined') return false\n\n // If the config is a boolean, use it directly.\n if (typeof config === 'boolean') return config\n\n // If the config is a string, it must be 'incremental' to enable partial\n // prerendering.\n if (config === 'incremental' && appConfig.experimental_ppr === true) {\n return true\n }\n\n return false\n}\n"],"names":["checkIsAppPPREnabled","checkIsRoutePPREnabled","config","appConfig","experimental_ppr"],"mappings":"AAAA;;;;;;CAMC;;;;;;;;;;;;;;;IAWeA,oBAAoB;eAApBA;;IAwBAC,sBAAsB;eAAtBA;;;AAxBT,SAASD,qBACdE,MAAyC;IAEzC,gEAAgE;IAChE,IAAI,OAAOA,WAAW,aAAa,OAAO;IAE1C,+CAA+C;IAC/C,IAAI,OAAOA,WAAW,WAAW,OAAOA;IAExC,wEAAwE;IACxE,gBAAgB;IAChB,IAAIA,WAAW,eAAe,OAAO;IAErC,OAAO;AACT;AAUO,SAASD,uBACdC,MAAyC,EACzCC,SAEC;IAED,gEAAgE;IAChE,IAAI,OAAOD,WAAW,aAAa,OAAO;IAE1C,+CAA+C;IAC/C,IAAI,OAAOA,WAAW,WAAW,OAAOA;IAExC,wEAAwE;IACxE,gBAAgB;IAChB,IAAIA,WAAW,iBAAiBC,UAAUC,gBAAgB,KAAK,MAAM;QACnE,OAAO;IACT;IAEA,OAAO;AACT"}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import type { PageExtensions } from '../../build/page-extensions-type';
|
||||
/**
|
||||
* Finds a page file with the given parameters. If the page is duplicated with
|
||||
* multiple extensions it will throw, otherwise it will return the *relative*
|
||||
* path to the page file or null if it is not found.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
export declare function findPageFile(pagesDir: string, normalizedPagePath: string, pageExtensions: PageExtensions, isAppDir: boolean): Promise<string | null>;
|
||||
/**
|
||||
*
|
||||
* createValidFileMatcher receives configured page extensions and return helpers to determine:
|
||||
* `isLayoutsLeafPage`: if a file is a valid page file or routes file under app directory
|
||||
* `isTrackedFiles`: if it's a tracked file for webpack watcher
|
||||
*
|
||||
*/
|
||||
export declare function createValidFileMatcher(pageExtensions: PageExtensions, appDirPath: string | undefined): {
|
||||
isPageFile: (filePath: string) => boolean;
|
||||
isAppRouterPage: (filePath: string) => boolean;
|
||||
isMetadataFile: (filePath: string) => boolean;
|
||||
isRootNotFound: (filePath: string) => boolean;
|
||||
};
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
createValidFileMatcher: null,
|
||||
findPageFile: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
createValidFileMatcher: function() {
|
||||
return createValidFileMatcher;
|
||||
},
|
||||
findPageFile: function() {
|
||||
return findPageFile;
|
||||
}
|
||||
});
|
||||
const _fileexists = require("../../lib/file-exists");
|
||||
const _getpagepaths = require("../../shared/lib/page-path/get-page-paths");
|
||||
const _nonnullable = require("../../lib/non-nullable");
|
||||
const _path = require("path");
|
||||
const _fs = require("fs");
|
||||
const _log = require("../../build/output/log");
|
||||
const _picocolors = require("../../lib/picocolors");
|
||||
const _ismetadataroute = require("../../lib/metadata/is-metadata-route");
|
||||
async function isTrueCasePagePath(pagePath, pagesDir) {
|
||||
const pageSegments = (0, _path.normalize)(pagePath).split(_path.sep).filter(Boolean);
|
||||
const segmentExistsPromises = pageSegments.map(async (segment, i)=>{
|
||||
const segmentParentDir = (0, _path.join)(pagesDir, ...pageSegments.slice(0, i));
|
||||
const parentDirEntries = await _fs.promises.readdir(segmentParentDir);
|
||||
return parentDirEntries.includes(segment);
|
||||
});
|
||||
return (await Promise.all(segmentExistsPromises)).every(Boolean);
|
||||
}
|
||||
async function findPageFile(pagesDir, normalizedPagePath, pageExtensions, isAppDir) {
|
||||
const pagePaths = (0, _getpagepaths.getPagePaths)(normalizedPagePath, pageExtensions, isAppDir);
|
||||
const [existingPath, ...others] = (await Promise.all(pagePaths.map(async (path)=>{
|
||||
const filePath = (0, _path.join)(pagesDir, path);
|
||||
try {
|
||||
return await (0, _fileexists.fileExists)(filePath) ? path : null;
|
||||
} catch (err) {
|
||||
var _err_code;
|
||||
if (!(err == null ? void 0 : (_err_code = err.code) == null ? void 0 : _err_code.includes('ENOTDIR'))) throw err;
|
||||
}
|
||||
return null;
|
||||
}))).filter(_nonnullable.nonNullable);
|
||||
if (!existingPath) {
|
||||
return null;
|
||||
}
|
||||
if (!await isTrueCasePagePath(existingPath, pagesDir)) {
|
||||
return null;
|
||||
}
|
||||
if (others.length > 0) {
|
||||
(0, _log.warn)(`Duplicate page detected. ${(0, _picocolors.cyan)((0, _path.join)('pages', existingPath))} and ${(0, _picocolors.cyan)((0, _path.join)('pages', others[0]))} both resolve to ${(0, _picocolors.cyan)(normalizedPagePath)}.`);
|
||||
}
|
||||
return existingPath;
|
||||
}
|
||||
function createValidFileMatcher(pageExtensions, appDirPath) {
|
||||
const getExtensionRegexString = (extensions)=>`(?:${extensions.join('|')})`;
|
||||
const validExtensionFileRegex = new RegExp('\\.' + getExtensionRegexString(pageExtensions) + '$');
|
||||
const leafOnlyPageFileRegex = new RegExp(`(^(page|route)|[\\\\/](page|route))\\.${getExtensionRegexString(pageExtensions)}$`);
|
||||
const rootNotFoundFileRegex = new RegExp(`^not-found\\.${getExtensionRegexString(pageExtensions)}$`);
|
||||
/** TODO-METADATA: support other metadata routes
|
||||
* regex for:
|
||||
*
|
||||
* /robots.txt|<ext>
|
||||
* /sitemap.xml|<ext>
|
||||
* /favicon.ico
|
||||
* /manifest.json|<ext>
|
||||
* <route>/icon.png|jpg|<ext>
|
||||
* <route>/apple-touch-icon.png|jpg|<ext>
|
||||
*
|
||||
*/ /**
|
||||
* Match the file if it's a metadata route file, static: if the file is a static metadata file.
|
||||
* It needs to be a file which doesn't match the custom metadata routes e.g. `app/robots.txt/route.js`
|
||||
*/ function isMetadataFile(filePath) {
|
||||
const appDirRelativePath = appDirPath ? filePath.replace(appDirPath, '') : filePath;
|
||||
return (0, _ismetadataroute.isMetadataRouteFile)(appDirRelativePath, pageExtensions, true);
|
||||
}
|
||||
// Determine if the file is leaf node page file or route file under layouts,
|
||||
// 'page.<extension>' | 'route.<extension>'
|
||||
function isAppRouterPage(filePath) {
|
||||
return leafOnlyPageFileRegex.test(filePath) || isMetadataFile(filePath);
|
||||
}
|
||||
function isPageFile(filePath) {
|
||||
return validExtensionFileRegex.test(filePath) || isMetadataFile(filePath);
|
||||
}
|
||||
function isRootNotFound(filePath) {
|
||||
if (!appDirPath) {
|
||||
return false;
|
||||
}
|
||||
if (!filePath.startsWith(appDirPath + _path.sep)) {
|
||||
return false;
|
||||
}
|
||||
const rest = filePath.slice(appDirPath.length + 1);
|
||||
return rootNotFoundFileRegex.test(rest);
|
||||
}
|
||||
return {
|
||||
isPageFile,
|
||||
isAppRouterPage,
|
||||
isMetadataFile,
|
||||
isRootNotFound
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=find-page-file.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+7
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Formats a hostname so that it is a valid host that can be fetched by wrapping
|
||||
* IPv6 hosts with brackets.
|
||||
* @param hostname
|
||||
* @returns
|
||||
*/
|
||||
export declare function formatHostname(hostname: string): string;
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "formatHostname", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return formatHostname;
|
||||
}
|
||||
});
|
||||
const _isipv6 = require("./is-ipv6");
|
||||
function formatHostname(hostname) {
|
||||
return (0, _isipv6.isIPv6)(hostname) ? `[${hostname}]` : hostname;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=format-hostname.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/format-hostname.ts"],"sourcesContent":["import { isIPv6 } from './is-ipv6'\n\n/**\n * Formats a hostname so that it is a valid host that can be fetched by wrapping\n * IPv6 hosts with brackets.\n * @param hostname\n * @returns\n */\nexport function formatHostname(hostname: string): string {\n return isIPv6(hostname) ? `[${hostname}]` : hostname\n}\n"],"names":["formatHostname","hostname","isIPv6"],"mappings":";;;;+BAQgBA;;;eAAAA;;;wBARO;AAQhB,SAASA,eAAeC,QAAgB;IAC7C,OAAOC,IAAAA,cAAM,EAACD,YAAY,CAAC,CAAC,EAAEA,SAAS,CAAC,CAAC,GAAGA;AAC9C"}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import type { DomainLocale, I18NConfig } from '../config-shared';
|
||||
import type { NextParsedUrlQuery } from '../request-meta';
|
||||
/**
|
||||
* The result of matching a locale aware route.
|
||||
*/
|
||||
export interface LocaleAnalysisResult {
|
||||
/**
|
||||
* The pathname without the locale prefix (if any).
|
||||
*/
|
||||
pathname: string;
|
||||
/**
|
||||
* The detected locale. If no locale was detected, this will be `undefined`.
|
||||
*/
|
||||
detectedLocale?: string;
|
||||
/**
|
||||
* True if the locale was inferred from the default locale.
|
||||
*/
|
||||
inferredFromDefault: boolean;
|
||||
}
|
||||
type LocaleAnalysisOptions = {
|
||||
/**
|
||||
* When provided, it will be used as the default locale if the locale
|
||||
* cannot be inferred from the pathname.
|
||||
*/
|
||||
defaultLocale?: string;
|
||||
};
|
||||
/**
|
||||
* The I18NProvider is used to match locale aware routes, detect the locale from
|
||||
* the pathname and hostname and normalize the pathname by removing the locale
|
||||
* prefix.
|
||||
*/
|
||||
export declare class I18NProvider {
|
||||
readonly config: Readonly<I18NConfig>;
|
||||
private readonly lowerCaseLocales;
|
||||
private readonly lowerCaseDomains?;
|
||||
constructor(config: Readonly<I18NConfig>);
|
||||
/**
|
||||
* Detects the domain locale from the hostname and the detected locale if
|
||||
* provided.
|
||||
*
|
||||
* @param hostname The hostname to detect the domain locale from, this must be lowercased.
|
||||
* @param detectedLocale The detected locale to use if the hostname does not match.
|
||||
* @returns The domain locale if found, `undefined` otherwise.
|
||||
*/
|
||||
detectDomainLocale(hostname?: string, detectedLocale?: string): DomainLocale | undefined;
|
||||
/**
|
||||
* Pulls the pre-computed locale and inference results from the query
|
||||
* object.
|
||||
*
|
||||
* @param pathname the pathname that could contain a locale prefix
|
||||
* @param query the query object
|
||||
* @returns the locale analysis result
|
||||
*/
|
||||
fromQuery(pathname: string, query: NextParsedUrlQuery): LocaleAnalysisResult;
|
||||
/**
|
||||
* Validates that the locale is valid.
|
||||
*
|
||||
* @param locale The locale to validate.
|
||||
* @returns `true` if the locale is valid, `false` otherwise.
|
||||
*/
|
||||
private validate;
|
||||
/**
|
||||
* Validates that the locales in the query object are valid.
|
||||
*
|
||||
* @param query The query object to validate.
|
||||
* @returns `true` if the locale is valid, `false` otherwise.
|
||||
*/
|
||||
validateQuery(query: NextParsedUrlQuery): boolean;
|
||||
/**
|
||||
* Analyzes the pathname for a locale and returns the pathname without it.
|
||||
*
|
||||
* @param pathname The pathname that could contain a locale prefix.
|
||||
* @param options The options to use when matching the locale.
|
||||
* @returns The matched locale and the pathname without the locale prefix
|
||||
* (if any).
|
||||
*/
|
||||
analyze(pathname: string, options?: LocaleAnalysisOptions): LocaleAnalysisResult;
|
||||
}
|
||||
export {};
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "I18NProvider", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return I18NProvider;
|
||||
}
|
||||
});
|
||||
class I18NProvider {
|
||||
constructor(config){
|
||||
var _config_domains;
|
||||
this.config = config;
|
||||
if (!config.locales.length) {
|
||||
throw new Error('Invariant: No locales provided');
|
||||
}
|
||||
this.lowerCaseLocales = config.locales.map((locale)=>locale.toLowerCase());
|
||||
this.lowerCaseDomains = (_config_domains = config.domains) == null ? void 0 : _config_domains.map((domainLocale)=>{
|
||||
var _domainLocale_locales;
|
||||
const domain = domainLocale.domain.toLowerCase();
|
||||
return {
|
||||
defaultLocale: domainLocale.defaultLocale.toLowerCase(),
|
||||
hostname: domain.split(':', 1)[0],
|
||||
domain,
|
||||
locales: (_domainLocale_locales = domainLocale.locales) == null ? void 0 : _domainLocale_locales.map((locale)=>locale.toLowerCase()),
|
||||
http: domainLocale.http
|
||||
};
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Detects the domain locale from the hostname and the detected locale if
|
||||
* provided.
|
||||
*
|
||||
* @param hostname The hostname to detect the domain locale from, this must be lowercased.
|
||||
* @param detectedLocale The detected locale to use if the hostname does not match.
|
||||
* @returns The domain locale if found, `undefined` otherwise.
|
||||
*/ detectDomainLocale(hostname, detectedLocale) {
|
||||
if (!hostname || !this.lowerCaseDomains || !this.config.domains) return;
|
||||
if (detectedLocale) detectedLocale = detectedLocale.toLowerCase();
|
||||
for(let i = 0; i < this.lowerCaseDomains.length; i++){
|
||||
var // Configuration validation ensures that the locale is not repeated in
|
||||
// other domains locales.
|
||||
_domainLocale_locales;
|
||||
const domainLocale = this.lowerCaseDomains[i];
|
||||
if (// We assume that the hostname is already lowercased.
|
||||
domainLocale.hostname === hostname || ((_domainLocale_locales = domainLocale.locales) == null ? void 0 : _domainLocale_locales.some((locale)=>locale === detectedLocale))) {
|
||||
return this.config.domains[i];
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Pulls the pre-computed locale and inference results from the query
|
||||
* object.
|
||||
*
|
||||
* @param pathname the pathname that could contain a locale prefix
|
||||
* @param query the query object
|
||||
* @returns the locale analysis result
|
||||
*/ fromQuery(pathname, query) {
|
||||
const detectedLocale = query.__nextLocale;
|
||||
// If a locale was detected on the query, analyze the pathname to ensure
|
||||
// that the locale matches.
|
||||
if (detectedLocale) {
|
||||
const analysis = this.analyze(pathname);
|
||||
// If the analysis contained a locale we should validate it against the
|
||||
// query and strip it from the pathname.
|
||||
if (analysis.detectedLocale) {
|
||||
if (analysis.detectedLocale !== detectedLocale) {
|
||||
throw new Error(`Invariant: The detected locale does not match the locale in the query. Expected to find '${detectedLocale}' in '${pathname}' but found '${analysis.detectedLocale}'}`);
|
||||
}
|
||||
pathname = analysis.pathname;
|
||||
}
|
||||
}
|
||||
return {
|
||||
pathname,
|
||||
detectedLocale,
|
||||
inferredFromDefault: query.__nextInferredLocaleFromDefault === '1'
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Validates that the locale is valid.
|
||||
*
|
||||
* @param locale The locale to validate.
|
||||
* @returns `true` if the locale is valid, `false` otherwise.
|
||||
*/ validate(locale) {
|
||||
return this.lowerCaseLocales.includes(locale.toLowerCase());
|
||||
}
|
||||
/**
|
||||
* Validates that the locales in the query object are valid.
|
||||
*
|
||||
* @param query The query object to validate.
|
||||
* @returns `true` if the locale is valid, `false` otherwise.
|
||||
*/ validateQuery(query) {
|
||||
if (query.__nextLocale && !this.validate(query.__nextLocale)) {
|
||||
return false;
|
||||
}
|
||||
if (query.__nextDefaultLocale && !this.validate(query.__nextDefaultLocale)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/**
|
||||
* Analyzes the pathname for a locale and returns the pathname without it.
|
||||
*
|
||||
* @param pathname The pathname that could contain a locale prefix.
|
||||
* @param options The options to use when matching the locale.
|
||||
* @returns The matched locale and the pathname without the locale prefix
|
||||
* (if any).
|
||||
*/ analyze(pathname, options = {}) {
|
||||
let detectedLocale = options.defaultLocale;
|
||||
// By default, we assume that the default locale was inferred if there was
|
||||
// no detected locale.
|
||||
let inferredFromDefault = typeof detectedLocale === 'string';
|
||||
// The first segment will be empty, because it has a leading `/`. If
|
||||
// there is no further segment, there is no locale (or it's the default).
|
||||
const segments = pathname.split('/', 2);
|
||||
if (!segments[1]) return {
|
||||
detectedLocale,
|
||||
pathname,
|
||||
inferredFromDefault
|
||||
};
|
||||
// The second segment will contain the locale part if any.
|
||||
const segment = segments[1].toLowerCase();
|
||||
// See if the segment matches one of the locales. If it doesn't, there is
|
||||
// no locale (or it's the default).
|
||||
const index = this.lowerCaseLocales.indexOf(segment);
|
||||
if (index < 0) return {
|
||||
detectedLocale,
|
||||
pathname,
|
||||
inferredFromDefault
|
||||
};
|
||||
// Return the case-sensitive locale.
|
||||
detectedLocale = this.config.locales[index];
|
||||
inferredFromDefault = false;
|
||||
// Remove the `/${locale}` part of the pathname.
|
||||
pathname = pathname.slice(detectedLocale.length + 1) || '/';
|
||||
return {
|
||||
detectedLocale,
|
||||
pathname,
|
||||
inferredFromDefault
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=i18n-provider.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
import type { FallbackRouteParams } from '../request/fallback-params';
|
||||
export declare function getImplicitTags(page: string, url: {
|
||||
pathname: string;
|
||||
search?: string;
|
||||
}, fallbackRouteParams: null | FallbackRouteParams): string[];
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "getImplicitTags", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return getImplicitTags;
|
||||
}
|
||||
});
|
||||
const _constants = require("../../lib/constants");
|
||||
const getDerivedTags = (pathname)=>{
|
||||
const derivedTags = [
|
||||
`/layout`
|
||||
];
|
||||
// we automatically add the current path segments as tags
|
||||
// for revalidatePath handling
|
||||
if (pathname.startsWith('/')) {
|
||||
const pathnameParts = pathname.split('/');
|
||||
for(let i = 1; i < pathnameParts.length + 1; i++){
|
||||
let curPathname = pathnameParts.slice(0, i).join('/');
|
||||
if (curPathname) {
|
||||
// all derived tags other than the page are layout tags
|
||||
if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {
|
||||
curPathname = `${curPathname}${!curPathname.endsWith('/') ? '/' : ''}layout`;
|
||||
}
|
||||
derivedTags.push(curPathname);
|
||||
}
|
||||
}
|
||||
}
|
||||
return derivedTags;
|
||||
};
|
||||
function getImplicitTags(page, url, fallbackRouteParams) {
|
||||
// TODO: Cache the result
|
||||
const newTags = [];
|
||||
const hasFallbackRouteParams = fallbackRouteParams && fallbackRouteParams.size > 0;
|
||||
// Add the derived tags from the page.
|
||||
const derivedTags = getDerivedTags(page);
|
||||
for (let tag of derivedTags){
|
||||
tag = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`;
|
||||
newTags.push(tag);
|
||||
}
|
||||
// Add the tags from the pathname. If the route has unknown params, we don't
|
||||
// want to add the pathname as a tag, as it will be invalid.
|
||||
if (url.pathname && !hasFallbackRouteParams) {
|
||||
const tag = `${_constants.NEXT_CACHE_IMPLICIT_TAG_ID}${url.pathname}`;
|
||||
newTags.push(tag);
|
||||
}
|
||||
return newTags;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=implicit-tags.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/implicit-tags.ts"],"sourcesContent":["import { NEXT_CACHE_IMPLICIT_TAG_ID } from '../../lib/constants'\nimport type { FallbackRouteParams } from '../request/fallback-params'\n\nconst getDerivedTags = (pathname: string): string[] => {\n const derivedTags: string[] = [`/layout`]\n\n // we automatically add the current path segments as tags\n // for revalidatePath handling\n if (pathname.startsWith('/')) {\n const pathnameParts = pathname.split('/')\n\n for (let i = 1; i < pathnameParts.length + 1; i++) {\n let curPathname = pathnameParts.slice(0, i).join('/')\n\n if (curPathname) {\n // all derived tags other than the page are layout tags\n if (!curPathname.endsWith('/page') && !curPathname.endsWith('/route')) {\n curPathname = `${curPathname}${\n !curPathname.endsWith('/') ? '/' : ''\n }layout`\n }\n derivedTags.push(curPathname)\n }\n }\n }\n return derivedTags\n}\n\nexport function getImplicitTags(\n page: string,\n url: {\n pathname: string\n search?: string\n },\n fallbackRouteParams: null | FallbackRouteParams\n) {\n // TODO: Cache the result\n const newTags: string[] = []\n const hasFallbackRouteParams =\n fallbackRouteParams && fallbackRouteParams.size > 0\n\n // Add the derived tags from the page.\n const derivedTags = getDerivedTags(page)\n for (let tag of derivedTags) {\n tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${tag}`\n newTags.push(tag)\n }\n\n // Add the tags from the pathname. If the route has unknown params, we don't\n // want to add the pathname as a tag, as it will be invalid.\n if (url.pathname && !hasFallbackRouteParams) {\n const tag = `${NEXT_CACHE_IMPLICIT_TAG_ID}${url.pathname}`\n newTags.push(tag)\n }\n\n return newTags\n}\n"],"names":["getImplicitTags","getDerivedTags","pathname","derivedTags","startsWith","pathnameParts","split","i","length","curPathname","slice","join","endsWith","push","page","url","fallbackRouteParams","newTags","hasFallbackRouteParams","size","tag","NEXT_CACHE_IMPLICIT_TAG_ID"],"mappings":";;;;+BA4BgBA;;;eAAAA;;;2BA5B2B;AAG3C,MAAMC,iBAAiB,CAACC;IACtB,MAAMC,cAAwB;QAAC,CAAC,OAAO,CAAC;KAAC;IAEzC,yDAAyD;IACzD,8BAA8B;IAC9B,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,MAAMC,gBAAgBH,SAASI,KAAK,CAAC;QAErC,IAAK,IAAIC,IAAI,GAAGA,IAAIF,cAAcG,MAAM,GAAG,GAAGD,IAAK;YACjD,IAAIE,cAAcJ,cAAcK,KAAK,CAAC,GAAGH,GAAGI,IAAI,CAAC;YAEjD,IAAIF,aAAa;gBACf,uDAAuD;gBACvD,IAAI,CAACA,YAAYG,QAAQ,CAAC,YAAY,CAACH,YAAYG,QAAQ,CAAC,WAAW;oBACrEH,cAAc,GAAGA,cACf,CAACA,YAAYG,QAAQ,CAAC,OAAO,MAAM,GACpC,MAAM,CAAC;gBACV;gBACAT,YAAYU,IAAI,CAACJ;YACnB;QACF;IACF;IACA,OAAON;AACT;AAEO,SAASH,gBACdc,IAAY,EACZC,GAGC,EACDC,mBAA+C;IAE/C,yBAAyB;IACzB,MAAMC,UAAoB,EAAE;IAC5B,MAAMC,yBACJF,uBAAuBA,oBAAoBG,IAAI,GAAG;IAEpD,sCAAsC;IACtC,MAAMhB,cAAcF,eAAea;IACnC,KAAK,IAAIM,OAAOjB,YAAa;QAC3BiB,MAAM,GAAGC,qCAA0B,GAAGD,KAAK;QAC3CH,QAAQJ,IAAI,CAACO;IACf;IAEA,4EAA4E;IAC5E,4DAA4D;IAC5D,IAAIL,IAAIb,QAAQ,IAAI,CAACgB,wBAAwB;QAC3C,MAAME,MAAM,GAAGC,qCAA0B,GAAGN,IAAIb,QAAQ,EAAE;QAC1De,QAAQJ,IAAI,CAACO;IACf;IAEA,OAAOH;AACT"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './';
|
||||
export default class FetchCache implements CacheHandler {
|
||||
private headers;
|
||||
private cacheEndpoint?;
|
||||
private hasMatchingTags;
|
||||
static isAvailable(ctx: {
|
||||
_requestHeaders: CacheHandlerContext['_requestHeaders'];
|
||||
}): boolean;
|
||||
constructor(ctx: CacheHandlerContext);
|
||||
resetRequestCache(): void;
|
||||
revalidateTag(...args: Parameters<CacheHandler['revalidateTag']>): Promise<void>;
|
||||
get(...args: Parameters<CacheHandler['get']>): Promise<CacheHandlerValue | null>;
|
||||
set(...args: Parameters<CacheHandler['set']>): Promise<void>;
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "default", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return FetchCache;
|
||||
}
|
||||
});
|
||||
const _responsecache = require("../../response-cache");
|
||||
const _lrucache = require("../lru-cache");
|
||||
const _constants = require("../../../lib/constants");
|
||||
let rateLimitedUntil = 0;
|
||||
let memoryCache;
|
||||
const CACHE_TAGS_HEADER = 'x-vercel-cache-tags';
|
||||
const CACHE_HEADERS_HEADER = 'x-vercel-sc-headers';
|
||||
const CACHE_STATE_HEADER = 'x-vercel-cache-state';
|
||||
const CACHE_REVALIDATE_HEADER = 'x-vercel-revalidate';
|
||||
const CACHE_FETCH_URL_HEADER = 'x-vercel-cache-item-name';
|
||||
const CACHE_CONTROL_VALUE_HEADER = 'x-vercel-cache-control';
|
||||
const DEBUG = Boolean(process.env.NEXT_PRIVATE_DEBUG_CACHE);
|
||||
async function fetchRetryWithTimeout(url, init, retryIndex = 0) {
|
||||
const controller = new AbortController();
|
||||
const timeout = setTimeout(()=>{
|
||||
controller.abort();
|
||||
}, 500);
|
||||
return fetch(url, {
|
||||
...init || {},
|
||||
signal: controller.signal
|
||||
}).catch((err)=>{
|
||||
if (retryIndex === 3) {
|
||||
throw err;
|
||||
} else {
|
||||
if (DEBUG) {
|
||||
console.log(`Fetch failed for ${url} retry ${retryIndex}`);
|
||||
}
|
||||
return fetchRetryWithTimeout(url, init, retryIndex + 1);
|
||||
}
|
||||
}).finally(()=>{
|
||||
clearTimeout(timeout);
|
||||
});
|
||||
}
|
||||
class FetchCache {
|
||||
hasMatchingTags(arr1, arr2) {
|
||||
if (arr1.length !== arr2.length) return false;
|
||||
const set1 = new Set(arr1);
|
||||
const set2 = new Set(arr2);
|
||||
if (set1.size !== set2.size) return false;
|
||||
for (let tag of set1){
|
||||
if (!set2.has(tag)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static isAvailable(ctx) {
|
||||
return !!(ctx._requestHeaders['x-vercel-sc-host'] || process.env.SUSPENSE_CACHE_URL);
|
||||
}
|
||||
constructor(ctx){
|
||||
this.headers = {};
|
||||
this.headers['Content-Type'] = 'application/json';
|
||||
if (CACHE_HEADERS_HEADER in ctx._requestHeaders) {
|
||||
const newHeaders = JSON.parse(ctx._requestHeaders[CACHE_HEADERS_HEADER]);
|
||||
for(const k in newHeaders){
|
||||
this.headers[k] = newHeaders[k];
|
||||
}
|
||||
delete ctx._requestHeaders[CACHE_HEADERS_HEADER];
|
||||
}
|
||||
const scHost = ctx._requestHeaders['x-vercel-sc-host'] || process.env.SUSPENSE_CACHE_URL;
|
||||
const scBasePath = ctx._requestHeaders['x-vercel-sc-basepath'] || process.env.SUSPENSE_CACHE_BASEPATH;
|
||||
if (process.env.SUSPENSE_CACHE_AUTH_TOKEN) {
|
||||
this.headers['Authorization'] = `Bearer ${process.env.SUSPENSE_CACHE_AUTH_TOKEN}`;
|
||||
}
|
||||
if (scHost) {
|
||||
const scProto = process.env.SUSPENSE_CACHE_PROTO || 'https';
|
||||
this.cacheEndpoint = `${scProto}://${scHost}${scBasePath || ''}`;
|
||||
if (DEBUG) {
|
||||
console.log('using cache endpoint', this.cacheEndpoint);
|
||||
}
|
||||
} else if (DEBUG) {
|
||||
console.log('no cache endpoint available');
|
||||
}
|
||||
if (ctx.maxMemoryCacheSize) {
|
||||
if (!memoryCache) {
|
||||
if (DEBUG) {
|
||||
console.log('using memory store for fetch cache');
|
||||
}
|
||||
memoryCache = new _lrucache.LRUCache(ctx.maxMemoryCacheSize, function length({ value }) {
|
||||
var _JSON_stringify;
|
||||
if (!value) {
|
||||
return 25;
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.REDIRECT) {
|
||||
return JSON.stringify(value.props).length;
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.IMAGE) {
|
||||
throw new Error('invariant image should not be incremental-cache');
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.FETCH) {
|
||||
return JSON.stringify(value.data || '').length;
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.APP_ROUTE) {
|
||||
return value.body.length;
|
||||
}
|
||||
// rough estimate of size of cache value
|
||||
return value.html.length + (((_JSON_stringify = JSON.stringify(value.kind === _responsecache.CachedRouteKind.APP_PAGE ? value.rscData : value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
if (DEBUG) {
|
||||
console.log('not using memory store for fetch cache');
|
||||
}
|
||||
}
|
||||
}
|
||||
resetRequestCache() {
|
||||
memoryCache == null ? void 0 : memoryCache.reset();
|
||||
}
|
||||
async revalidateTag(...args) {
|
||||
let [tags] = args;
|
||||
tags = typeof tags === 'string' ? [
|
||||
tags
|
||||
] : tags;
|
||||
if (DEBUG) {
|
||||
console.log('revalidateTag', tags);
|
||||
}
|
||||
if (!tags.length) return;
|
||||
if (Date.now() < rateLimitedUntil) {
|
||||
if (DEBUG) {
|
||||
console.log('rate limited ', rateLimitedUntil);
|
||||
}
|
||||
return;
|
||||
}
|
||||
for(let i = 0; i < Math.ceil(tags.length / 64); i++){
|
||||
const currentTags = tags.slice(i * 64, i * 64 + 64);
|
||||
try {
|
||||
const res = await fetchRetryWithTimeout(`${this.cacheEndpoint}/v1/suspense-cache/revalidate?tags=${currentTags.map((tag)=>encodeURIComponent(tag)).join(',')}`, {
|
||||
method: 'POST',
|
||||
headers: this.headers,
|
||||
// @ts-expect-error not on public type
|
||||
next: {
|
||||
internal: true
|
||||
}
|
||||
});
|
||||
if (res.status === 429) {
|
||||
const retryAfter = res.headers.get('retry-after') || '60000';
|
||||
rateLimitedUntil = Date.now() + parseInt(retryAfter);
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(`Request failed with status ${res.status}.`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn(`Failed to revalidate tag`, currentTags, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
async get(...args) {
|
||||
var _data_value;
|
||||
const [key, ctx] = args;
|
||||
const { tags, softTags, kind: kindHint, fetchIdx, fetchUrl } = ctx;
|
||||
if (kindHint !== _responsecache.IncrementalCacheKind.FETCH) {
|
||||
return null;
|
||||
}
|
||||
if (Date.now() < rateLimitedUntil) {
|
||||
if (DEBUG) {
|
||||
console.log('rate limited');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// memory cache is cleared at the end of each request
|
||||
// so that revalidate events are pulled from upstream
|
||||
// on successive requests
|
||||
let data = memoryCache == null ? void 0 : memoryCache.get(key);
|
||||
const hasFetchKindAndMatchingTags = (data == null ? void 0 : (_data_value = data.value) == null ? void 0 : _data_value.kind) === _responsecache.CachedRouteKind.FETCH && this.hasMatchingTags(tags ?? [], data.value.tags ?? []);
|
||||
// Get data from fetch cache. Also check if new tags have been
|
||||
// specified with the same cache key (fetch URL)
|
||||
if (this.cacheEndpoint && (!data || !hasFetchKindAndMatchingTags)) {
|
||||
try {
|
||||
const start = Date.now();
|
||||
const fetchParams = {
|
||||
internal: true,
|
||||
fetchType: 'cache-get',
|
||||
fetchUrl: fetchUrl,
|
||||
fetchIdx
|
||||
};
|
||||
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/${key}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
...this.headers,
|
||||
[CACHE_FETCH_URL_HEADER]: fetchUrl,
|
||||
[CACHE_TAGS_HEADER]: (tags == null ? void 0 : tags.join(',')) || '',
|
||||
[_constants.NEXT_CACHE_SOFT_TAGS_HEADER]: (softTags == null ? void 0 : softTags.join(',')) || ''
|
||||
},
|
||||
next: fetchParams
|
||||
});
|
||||
if (res.status === 429) {
|
||||
const retryAfter = res.headers.get('retry-after') || '60000';
|
||||
rateLimitedUntil = Date.now() + parseInt(retryAfter);
|
||||
}
|
||||
if (res.status === 404) {
|
||||
if (DEBUG) {
|
||||
console.log(`no fetch cache entry for ${key}, duration: ${Date.now() - start}ms`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!res.ok) {
|
||||
console.error(await res.text());
|
||||
throw new Error(`invalid response from cache ${res.status}`);
|
||||
}
|
||||
const cached = await res.json();
|
||||
if (!cached || cached.kind !== _responsecache.CachedRouteKind.FETCH) {
|
||||
DEBUG && console.log({
|
||||
cached
|
||||
});
|
||||
throw new Error('invalid cache value');
|
||||
}
|
||||
// if new tags were specified, merge those tags to the existing tags
|
||||
if (cached.kind === _responsecache.CachedRouteKind.FETCH) {
|
||||
cached.tags ??= [];
|
||||
for (const tag of tags ?? []){
|
||||
if (!cached.tags.includes(tag)) {
|
||||
cached.tags.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
const cacheState = res.headers.get(CACHE_STATE_HEADER);
|
||||
const age = res.headers.get('age');
|
||||
data = {
|
||||
value: cached,
|
||||
// if it's already stale set it to a time in the past
|
||||
// if not derive last modified from age
|
||||
lastModified: cacheState !== 'fresh' ? Date.now() - _constants.CACHE_ONE_YEAR : Date.now() - parseInt(age || '0', 10) * 1000
|
||||
};
|
||||
if (DEBUG) {
|
||||
console.log(`got fetch cache entry for ${key}, duration: ${Date.now() - start}ms, size: ${Object.keys(cached).length}, cache-state: ${cacheState} tags: ${tags == null ? void 0 : tags.join(',')} softTags: ${softTags == null ? void 0 : softTags.join(',')}`);
|
||||
}
|
||||
if (data) {
|
||||
memoryCache == null ? void 0 : memoryCache.set(key, data);
|
||||
}
|
||||
} catch (err) {
|
||||
// unable to get data from fetch-cache
|
||||
if (DEBUG) {
|
||||
console.error(`Failed to get from fetch-cache`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
return data || null;
|
||||
}
|
||||
async set(...args) {
|
||||
const [key, data, ctx] = args;
|
||||
const { fetchCache, fetchIdx, fetchUrl, tags } = ctx;
|
||||
if (!fetchCache) return;
|
||||
if (Date.now() < rateLimitedUntil) {
|
||||
if (DEBUG) {
|
||||
console.log('rate limited');
|
||||
}
|
||||
return;
|
||||
}
|
||||
memoryCache == null ? void 0 : memoryCache.set(key, {
|
||||
value: data,
|
||||
lastModified: Date.now()
|
||||
});
|
||||
if (this.cacheEndpoint) {
|
||||
try {
|
||||
const start = Date.now();
|
||||
if (data !== null && 'revalidate' in data) {
|
||||
this.headers[CACHE_REVALIDATE_HEADER] = data.revalidate.toString();
|
||||
}
|
||||
if (!this.headers[CACHE_REVALIDATE_HEADER] && data !== null && 'data' in data) {
|
||||
this.headers[CACHE_CONTROL_VALUE_HEADER] = data.data.headers['cache-control'];
|
||||
}
|
||||
const body = JSON.stringify({
|
||||
...data,
|
||||
// we send the tags in the header instead
|
||||
// of in the body here
|
||||
tags: undefined
|
||||
});
|
||||
if (DEBUG) {
|
||||
console.log('set cache', key);
|
||||
}
|
||||
const fetchParams = {
|
||||
internal: true,
|
||||
fetchType: 'cache-set',
|
||||
fetchUrl,
|
||||
fetchIdx
|
||||
};
|
||||
const res = await fetch(`${this.cacheEndpoint}/v1/suspense-cache/${key}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...this.headers,
|
||||
[CACHE_FETCH_URL_HEADER]: fetchUrl || '',
|
||||
[CACHE_TAGS_HEADER]: (tags == null ? void 0 : tags.join(',')) || ''
|
||||
},
|
||||
body: body,
|
||||
next: fetchParams
|
||||
});
|
||||
if (res.status === 429) {
|
||||
const retryAfter = res.headers.get('retry-after') || '60000';
|
||||
rateLimitedUntil = Date.now() + parseInt(retryAfter);
|
||||
}
|
||||
if (!res.ok) {
|
||||
DEBUG && console.log(await res.text());
|
||||
throw new Error(`invalid response ${res.status}`);
|
||||
}
|
||||
if (DEBUG) {
|
||||
console.log(`successfully set to fetch-cache for ${key}, duration: ${Date.now() - start}ms, size: ${body.length}`);
|
||||
}
|
||||
} catch (err) {
|
||||
// unable to set to fetch-cache
|
||||
if (DEBUG) {
|
||||
console.error(`Failed to update fetch cache`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=fetch-cache.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+20
@@ -0,0 +1,20 @@
|
||||
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './';
|
||||
import type { CacheFs } from '../../../shared/lib/utils';
|
||||
type FileSystemCacheContext = Omit<CacheHandlerContext, 'fs' | 'serverDistDir'> & {
|
||||
fs: CacheFs;
|
||||
serverDistDir: string;
|
||||
};
|
||||
export default class FileSystemCache implements CacheHandler {
|
||||
private fs;
|
||||
private flushToDisk?;
|
||||
private serverDistDir;
|
||||
private revalidatedTags;
|
||||
private debug;
|
||||
constructor(ctx: FileSystemCacheContext);
|
||||
resetRequestCache(): void;
|
||||
revalidateTag(...args: Parameters<CacheHandler['revalidateTag']>): Promise<void>;
|
||||
get(...args: Parameters<CacheHandler['get']>): Promise<CacheHandlerValue | null>;
|
||||
set(...args: Parameters<CacheHandler['set']>): Promise<void>;
|
||||
private getFilePath;
|
||||
}
|
||||
export {};
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "default", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return FileSystemCache;
|
||||
}
|
||||
});
|
||||
const _responsecache = require("../../response-cache");
|
||||
const _lrucache = require("../lru-cache");
|
||||
const _path = /*#__PURE__*/ _interop_require_default(require("../../../shared/lib/isomorphic/path"));
|
||||
const _constants = require("../../../lib/constants");
|
||||
const _tagsmanifestexternal = require("./tags-manifest.external");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
let memoryCache;
|
||||
class FileSystemCache {
|
||||
constructor(ctx){
|
||||
this.fs = ctx.fs;
|
||||
this.flushToDisk = ctx.flushToDisk;
|
||||
this.serverDistDir = ctx.serverDistDir;
|
||||
this.revalidatedTags = ctx.revalidatedTags;
|
||||
this.debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
|
||||
if (ctx.maxMemoryCacheSize) {
|
||||
if (!memoryCache) {
|
||||
if (this.debug) {
|
||||
console.log('using memory store for fetch cache');
|
||||
}
|
||||
memoryCache = new _lrucache.LRUCache(ctx.maxMemoryCacheSize, function length({ value }) {
|
||||
var _JSON_stringify;
|
||||
if (!value) {
|
||||
return 25;
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.REDIRECT) {
|
||||
return JSON.stringify(value.props).length;
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.IMAGE) {
|
||||
throw new Error('invariant image should not be incremental-cache');
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.FETCH) {
|
||||
return JSON.stringify(value.data || '').length;
|
||||
} else if (value.kind === _responsecache.CachedRouteKind.APP_ROUTE) {
|
||||
return value.body.length;
|
||||
}
|
||||
// rough estimate of size of cache value
|
||||
return value.html.length + (((_JSON_stringify = JSON.stringify(value.kind === _responsecache.CachedRouteKind.APP_PAGE ? value.rscData : value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0);
|
||||
});
|
||||
}
|
||||
} else if (this.debug) {
|
||||
console.log('not using memory store for fetch cache');
|
||||
}
|
||||
}
|
||||
resetRequestCache() {}
|
||||
async revalidateTag(...args) {
|
||||
let [tags] = args;
|
||||
tags = typeof tags === 'string' ? [
|
||||
tags
|
||||
] : tags;
|
||||
if (this.debug) {
|
||||
console.log('revalidateTag', tags);
|
||||
}
|
||||
if (tags.length === 0) {
|
||||
return;
|
||||
}
|
||||
for (const tag of tags){
|
||||
const data = _tagsmanifestexternal.tagsManifest.items[tag] || {};
|
||||
data.revalidatedAt = Date.now();
|
||||
_tagsmanifestexternal.tagsManifest.items[tag] = data;
|
||||
}
|
||||
}
|
||||
async get(...args) {
|
||||
var _data_value, _data_value1, _data_value2;
|
||||
const [key, ctx] = args;
|
||||
const { tags, softTags, kind, isRoutePPREnabled, isFallback } = ctx;
|
||||
let data = memoryCache == null ? void 0 : memoryCache.get(key);
|
||||
if (this.debug) {
|
||||
console.log('get', key, tags, kind, !!data);
|
||||
}
|
||||
// let's check the disk for seed data
|
||||
if (!data && process.env.NEXT_RUNTIME !== 'edge') {
|
||||
if (kind === _responsecache.IncrementalCacheKind.APP_ROUTE) {
|
||||
try {
|
||||
const filePath = this.getFilePath(`${key}.body`, _responsecache.IncrementalCacheKind.APP_ROUTE);
|
||||
const fileData = await this.fs.readFile(filePath);
|
||||
const { mtime } = await this.fs.stat(filePath);
|
||||
const meta = JSON.parse(await this.fs.readFile(filePath.replace(/\.body$/, _constants.NEXT_META_SUFFIX), 'utf8'));
|
||||
const cacheEntry = {
|
||||
lastModified: mtime.getTime(),
|
||||
value: {
|
||||
kind: _responsecache.CachedRouteKind.APP_ROUTE,
|
||||
body: fileData,
|
||||
headers: meta.headers,
|
||||
status: meta.status
|
||||
}
|
||||
};
|
||||
return cacheEntry;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const filePath = this.getFilePath(kind === _responsecache.IncrementalCacheKind.FETCH ? key : `${key}.html`, kind);
|
||||
const fileData = await this.fs.readFile(filePath, 'utf8');
|
||||
const { mtime } = await this.fs.stat(filePath);
|
||||
if (kind === _responsecache.IncrementalCacheKind.FETCH) {
|
||||
var _data_value3;
|
||||
if (!this.flushToDisk) return null;
|
||||
const lastModified = mtime.getTime();
|
||||
const parsedData = JSON.parse(fileData);
|
||||
data = {
|
||||
lastModified,
|
||||
value: parsedData
|
||||
};
|
||||
if (((_data_value3 = data.value) == null ? void 0 : _data_value3.kind) === _responsecache.CachedRouteKind.FETCH) {
|
||||
var _data_value4;
|
||||
const storedTags = (_data_value4 = data.value) == null ? void 0 : _data_value4.tags;
|
||||
// update stored tags if a new one is being added
|
||||
// TODO: remove this when we can send the tags
|
||||
// via header on GET same as SET
|
||||
if (!(tags == null ? void 0 : tags.every((tag)=>storedTags == null ? void 0 : storedTags.includes(tag)))) {
|
||||
if (this.debug) {
|
||||
console.log('tags vs storedTags mismatch', tags, storedTags);
|
||||
}
|
||||
await this.set(key, data.value, {
|
||||
tags,
|
||||
isRoutePPREnabled
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (kind === _responsecache.IncrementalCacheKind.APP_PAGE) {
|
||||
// We try to load the metadata file, but if it fails, we don't
|
||||
// error. We also don't load it if this is a fallback.
|
||||
let meta;
|
||||
try {
|
||||
meta = JSON.parse(await this.fs.readFile(filePath.replace(/\.html$/, _constants.NEXT_META_SUFFIX), 'utf8'));
|
||||
} catch {}
|
||||
let maybeSegmentData;
|
||||
if (meta == null ? void 0 : meta.segmentPaths) {
|
||||
// Collect all the segment data for this page.
|
||||
// TODO: To optimize file system reads, we should consider creating
|
||||
// separate cache entries for each segment, rather than storing them
|
||||
// all on the page's entry. Though the behavior is
|
||||
// identical regardless.
|
||||
const segmentData = new Map();
|
||||
maybeSegmentData = segmentData;
|
||||
const segmentsDir = key + _constants.RSC_SEGMENTS_DIR_SUFFIX;
|
||||
await Promise.all(meta.segmentPaths.map(async (segmentPath)=>{
|
||||
const segmentDataFilePath = this.getFilePath(segmentPath === '/' ? segmentsDir + '/_index' + _constants.RSC_SEGMENT_SUFFIX : segmentsDir + segmentPath + _constants.RSC_SEGMENT_SUFFIX, _responsecache.IncrementalCacheKind.APP_PAGE);
|
||||
try {
|
||||
segmentData.set(segmentPath, await this.fs.readFile(segmentDataFilePath));
|
||||
} catch {
|
||||
// This shouldn't happen, but if for some reason we fail to
|
||||
// load a segment from the filesystem, treat it the same as if
|
||||
// the segment is dynamic and does not have a prefetch.
|
||||
}
|
||||
}));
|
||||
}
|
||||
let rscData;
|
||||
if (!isFallback) {
|
||||
rscData = await this.fs.readFile(this.getFilePath(`${key}${isRoutePPREnabled ? _constants.RSC_PREFETCH_SUFFIX : _constants.RSC_SUFFIX}`, _responsecache.IncrementalCacheKind.APP_PAGE));
|
||||
}
|
||||
data = {
|
||||
lastModified: mtime.getTime(),
|
||||
value: {
|
||||
kind: _responsecache.CachedRouteKind.APP_PAGE,
|
||||
html: fileData,
|
||||
rscData,
|
||||
postponed: meta == null ? void 0 : meta.postponed,
|
||||
headers: meta == null ? void 0 : meta.headers,
|
||||
status: meta == null ? void 0 : meta.status,
|
||||
segmentData: maybeSegmentData
|
||||
}
|
||||
};
|
||||
} else if (kind === _responsecache.IncrementalCacheKind.PAGES) {
|
||||
let meta;
|
||||
let pageData = {};
|
||||
if (!isFallback) {
|
||||
pageData = JSON.parse(await this.fs.readFile(this.getFilePath(`${key}${_constants.NEXT_DATA_SUFFIX}`, _responsecache.IncrementalCacheKind.PAGES), 'utf8'));
|
||||
}
|
||||
data = {
|
||||
lastModified: mtime.getTime(),
|
||||
value: {
|
||||
kind: _responsecache.CachedRouteKind.PAGES,
|
||||
html: fileData,
|
||||
pageData,
|
||||
headers: meta == null ? void 0 : meta.headers,
|
||||
status: meta == null ? void 0 : meta.status
|
||||
}
|
||||
};
|
||||
} else {
|
||||
throw new Error(`Invariant: Unexpected route kind ${kind} in file system cache.`);
|
||||
}
|
||||
if (data) {
|
||||
memoryCache == null ? void 0 : memoryCache.set(key, data);
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if ((data == null ? void 0 : (_data_value = data.value) == null ? void 0 : _data_value.kind) === _responsecache.CachedRouteKind.APP_PAGE || (data == null ? void 0 : (_data_value1 = data.value) == null ? void 0 : _data_value1.kind) === _responsecache.CachedRouteKind.PAGES) {
|
||||
var _data_value_headers;
|
||||
let cacheTags;
|
||||
const tagsHeader = (_data_value_headers = data.value.headers) == null ? void 0 : _data_value_headers[_constants.NEXT_CACHE_TAGS_HEADER];
|
||||
if (typeof tagsHeader === 'string') {
|
||||
cacheTags = tagsHeader.split(',');
|
||||
}
|
||||
if (cacheTags == null ? void 0 : cacheTags.length) {
|
||||
const isStale = cacheTags.some((tag)=>{
|
||||
var _tagsManifest_items_tag;
|
||||
return (_tagsmanifestexternal.tagsManifest == null ? void 0 : (_tagsManifest_items_tag = _tagsmanifestexternal.tagsManifest.items[tag]) == null ? void 0 : _tagsManifest_items_tag.revalidatedAt) && (_tagsmanifestexternal.tagsManifest == null ? void 0 : _tagsmanifestexternal.tagsManifest.items[tag].revalidatedAt) >= ((data == null ? void 0 : data.lastModified) || Date.now());
|
||||
});
|
||||
// we trigger a blocking validation if an ISR page
|
||||
// had a tag revalidated, if we want to be a background
|
||||
// revalidation instead we return data.lastModified = -1
|
||||
if (isStale) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else if ((data == null ? void 0 : (_data_value2 = data.value) == null ? void 0 : _data_value2.kind) === _responsecache.CachedRouteKind.FETCH) {
|
||||
const combinedTags = [
|
||||
...tags || [],
|
||||
...softTags || []
|
||||
];
|
||||
const wasRevalidated = combinedTags.some((tag)=>{
|
||||
var _tagsManifest_items_tag;
|
||||
if (this.revalidatedTags.includes(tag)) {
|
||||
return true;
|
||||
}
|
||||
return (_tagsmanifestexternal.tagsManifest == null ? void 0 : (_tagsManifest_items_tag = _tagsmanifestexternal.tagsManifest.items[tag]) == null ? void 0 : _tagsManifest_items_tag.revalidatedAt) && (_tagsmanifestexternal.tagsManifest == null ? void 0 : _tagsmanifestexternal.tagsManifest.items[tag].revalidatedAt) >= ((data == null ? void 0 : data.lastModified) || Date.now());
|
||||
});
|
||||
// When revalidate tag is called we don't return
|
||||
// stale data so it's updated right away
|
||||
if (wasRevalidated) {
|
||||
data = undefined;
|
||||
}
|
||||
}
|
||||
return data ?? null;
|
||||
}
|
||||
async set(...args) {
|
||||
const [key, data, ctx] = args;
|
||||
const { isFallback } = ctx;
|
||||
memoryCache == null ? void 0 : memoryCache.set(key, {
|
||||
value: data,
|
||||
lastModified: Date.now()
|
||||
});
|
||||
if (this.debug) {
|
||||
console.log('set', key);
|
||||
}
|
||||
if (!this.flushToDisk || !data) return;
|
||||
if (data.kind === _responsecache.CachedRouteKind.APP_ROUTE) {
|
||||
const filePath = this.getFilePath(`${key}.body`, _responsecache.IncrementalCacheKind.APP_ROUTE);
|
||||
await this.fs.mkdir(_path.default.dirname(filePath));
|
||||
await this.fs.writeFile(filePath, data.body);
|
||||
const meta = {
|
||||
headers: data.headers,
|
||||
status: data.status,
|
||||
postponed: undefined,
|
||||
segmentPaths: undefined
|
||||
};
|
||||
await this.fs.writeFile(filePath.replace(/\.body$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta, null, 2));
|
||||
} else if (data.kind === _responsecache.CachedRouteKind.PAGES || data.kind === _responsecache.CachedRouteKind.APP_PAGE) {
|
||||
const isAppPath = data.kind === _responsecache.CachedRouteKind.APP_PAGE;
|
||||
const htmlPath = this.getFilePath(`${key}.html`, isAppPath ? _responsecache.IncrementalCacheKind.APP_PAGE : _responsecache.IncrementalCacheKind.PAGES);
|
||||
await this.fs.mkdir(_path.default.dirname(htmlPath));
|
||||
await this.fs.writeFile(htmlPath, data.html);
|
||||
// Fallbacks don't generate a data file.
|
||||
if (!isFallback) {
|
||||
await this.fs.writeFile(this.getFilePath(`${key}${isAppPath ? ctx.isRoutePPREnabled ? _constants.RSC_PREFETCH_SUFFIX : _constants.RSC_SUFFIX : _constants.NEXT_DATA_SUFFIX}`, isAppPath ? _responsecache.IncrementalCacheKind.APP_PAGE : _responsecache.IncrementalCacheKind.PAGES), isAppPath ? data.rscData : JSON.stringify(data.pageData));
|
||||
}
|
||||
if ((data == null ? void 0 : data.kind) === _responsecache.CachedRouteKind.APP_PAGE) {
|
||||
const meta = {
|
||||
headers: data.headers,
|
||||
status: data.status,
|
||||
postponed: data.postponed,
|
||||
segmentPaths: undefined
|
||||
};
|
||||
await this.fs.writeFile(htmlPath.replace(/\.html$/, _constants.NEXT_META_SUFFIX), JSON.stringify(meta));
|
||||
}
|
||||
} else if (data.kind === _responsecache.CachedRouteKind.FETCH) {
|
||||
const filePath = this.getFilePath(key, _responsecache.IncrementalCacheKind.FETCH);
|
||||
await this.fs.mkdir(_path.default.dirname(filePath));
|
||||
await this.fs.writeFile(filePath, JSON.stringify({
|
||||
...data,
|
||||
tags: ctx.tags
|
||||
}));
|
||||
}
|
||||
}
|
||||
getFilePath(pathname, kind) {
|
||||
switch(kind){
|
||||
case _responsecache.IncrementalCacheKind.FETCH:
|
||||
// we store in .next/cache/fetch-cache so it can be persisted
|
||||
// across deploys
|
||||
return _path.default.join(this.serverDistDir, '..', 'cache', 'fetch-cache', pathname);
|
||||
case _responsecache.IncrementalCacheKind.PAGES:
|
||||
return _path.default.join(this.serverDistDir, 'pages', pathname);
|
||||
case _responsecache.IncrementalCacheKind.IMAGE:
|
||||
case _responsecache.IncrementalCacheKind.APP_PAGE:
|
||||
case _responsecache.IncrementalCacheKind.APP_ROUTE:
|
||||
return _path.default.join(this.serverDistDir, 'app', pathname);
|
||||
default:
|
||||
throw new Error(`Unexpected file path kind: ${kind}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=file-system-cache.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+91
@@ -0,0 +1,91 @@
|
||||
import type { CacheFs } from '../../../shared/lib/utils';
|
||||
import type { PrerenderManifest } from '../../../build';
|
||||
import { type IncrementalCacheValue, type IncrementalCacheEntry, type IncrementalCache as IncrementalCacheType, IncrementalCacheKind } from '../../response-cache';
|
||||
import type { Revalidate } from '../revalidate';
|
||||
import type { DeepReadonly } from '../../../shared/lib/deep-readonly';
|
||||
export interface CacheHandlerContext {
|
||||
fs?: CacheFs;
|
||||
dev?: boolean;
|
||||
flushToDisk?: boolean;
|
||||
serverDistDir?: string;
|
||||
maxMemoryCacheSize?: number;
|
||||
fetchCacheKeyPrefix?: string;
|
||||
prerenderManifest?: PrerenderManifest;
|
||||
revalidatedTags: string[];
|
||||
_requestHeaders: IncrementalCache['requestHeaders'];
|
||||
}
|
||||
export interface CacheHandlerValue {
|
||||
lastModified?: number;
|
||||
age?: number;
|
||||
cacheState?: string;
|
||||
value: IncrementalCacheValue | null;
|
||||
}
|
||||
export declare class CacheHandler {
|
||||
constructor(_ctx: CacheHandlerContext);
|
||||
get(..._args: Parameters<IncrementalCache['get']>): Promise<CacheHandlerValue | null>;
|
||||
set(..._args: Parameters<IncrementalCache['set']>): Promise<void>;
|
||||
revalidateTag(..._args: Parameters<IncrementalCache['revalidateTag']>): Promise<void>;
|
||||
resetRequestCache(): void;
|
||||
}
|
||||
export declare class IncrementalCache implements IncrementalCacheType {
|
||||
readonly dev?: boolean;
|
||||
readonly disableForTestmode?: boolean;
|
||||
readonly cacheHandler?: CacheHandler;
|
||||
readonly hasCustomCacheHandler: boolean;
|
||||
readonly prerenderManifest: DeepReadonly<PrerenderManifest>;
|
||||
readonly requestHeaders: Record<string, undefined | string | string[]>;
|
||||
readonly requestProtocol?: 'http' | 'https';
|
||||
readonly allowedRevalidateHeaderKeys?: string[];
|
||||
readonly minimalMode?: boolean;
|
||||
readonly fetchCacheKeyPrefix?: string;
|
||||
readonly revalidatedTags?: string[];
|
||||
readonly isOnDemandRevalidate?: boolean;
|
||||
readonly hasDynamicIO?: boolean;
|
||||
private readonly locks;
|
||||
/**
|
||||
* The revalidate timings for routes. This will source the timings from the
|
||||
* prerender manifest until the in-memory cache is updated with new timings.
|
||||
*/
|
||||
private readonly revalidateTimings;
|
||||
constructor({ fs, dev, dynamicIO, flushToDisk, fetchCache, minimalMode, serverDistDir, requestHeaders, requestProtocol, maxMemoryCacheSize, getPrerenderManifest, fetchCacheKeyPrefix, CurCacheHandler, allowedRevalidateHeaderKeys, }: {
|
||||
fs?: CacheFs;
|
||||
dev: boolean;
|
||||
dynamicIO: boolean;
|
||||
fetchCache?: boolean;
|
||||
minimalMode?: boolean;
|
||||
serverDistDir?: string;
|
||||
flushToDisk?: boolean;
|
||||
requestProtocol?: 'http' | 'https';
|
||||
allowedRevalidateHeaderKeys?: string[];
|
||||
requestHeaders: IncrementalCache['requestHeaders'];
|
||||
maxMemoryCacheSize?: number;
|
||||
getPrerenderManifest: () => DeepReadonly<PrerenderManifest>;
|
||||
fetchCacheKeyPrefix?: string;
|
||||
CurCacheHandler?: typeof CacheHandler;
|
||||
});
|
||||
private calculateRevalidate;
|
||||
_getPathname(pathname: string, fetchCache?: boolean): string;
|
||||
resetRequestCache(): void;
|
||||
lock(cacheKey: string): Promise<() => Promise<void>>;
|
||||
revalidateTag(tags: string | string[]): Promise<void>;
|
||||
generateCacheKey(url: string, init?: RequestInit | Request): Promise<string>;
|
||||
get(cacheKey: string, ctx: {
|
||||
kind: IncrementalCacheKind;
|
||||
revalidate?: Revalidate;
|
||||
fetchUrl?: string;
|
||||
fetchIdx?: number;
|
||||
tags?: string[];
|
||||
softTags?: string[];
|
||||
isRoutePPREnabled?: boolean;
|
||||
isFallback: boolean | undefined;
|
||||
}): Promise<IncrementalCacheEntry | null>;
|
||||
set(pathname: string, data: IncrementalCacheValue | null, ctx: {
|
||||
revalidate?: Revalidate;
|
||||
fetchCache?: boolean;
|
||||
fetchUrl?: string;
|
||||
fetchIdx?: number;
|
||||
tags?: string[];
|
||||
isRoutePPREnabled?: boolean;
|
||||
isFallback?: boolean;
|
||||
}): Promise<void>;
|
||||
}
|
||||
+386
@@ -0,0 +1,386 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
CacheHandler: null,
|
||||
IncrementalCache: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
CacheHandler: function() {
|
||||
return CacheHandler;
|
||||
},
|
||||
IncrementalCache: function() {
|
||||
return IncrementalCache;
|
||||
}
|
||||
});
|
||||
const _responsecache = require("../../response-cache");
|
||||
const _fetchcache = /*#__PURE__*/ _interop_require_default(require("./fetch-cache"));
|
||||
const _filesystemcache = /*#__PURE__*/ _interop_require_default(require("./file-system-cache"));
|
||||
const _normalizepagepath = require("../../../shared/lib/page-path/normalize-page-path");
|
||||
const _constants = require("../../../lib/constants");
|
||||
const _toroute = require("../to-route");
|
||||
const _sharedrevalidatetimings = require("./shared-revalidate-timings");
|
||||
const _workunitasyncstorageinstance = require("../../app-render/work-unit-async-storage-instance");
|
||||
const _workunitasyncstorageexternal = require("../../app-render/work-unit-async-storage.external");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
class CacheHandler {
|
||||
// eslint-disable-next-line
|
||||
constructor(_ctx){}
|
||||
async get(..._args) {
|
||||
return {};
|
||||
}
|
||||
async set(..._args) {}
|
||||
async revalidateTag(..._args) {}
|
||||
resetRequestCache() {}
|
||||
}
|
||||
class IncrementalCache {
|
||||
constructor({ fs, dev, dynamicIO, flushToDisk, fetchCache, minimalMode, serverDistDir, requestHeaders, requestProtocol, maxMemoryCacheSize, getPrerenderManifest, fetchCacheKeyPrefix, CurCacheHandler, allowedRevalidateHeaderKeys }){
|
||||
var _this_prerenderManifest_preview, _this_prerenderManifest, _this_prerenderManifest_preview1, _this_prerenderManifest1;
|
||||
this.locks = new Map();
|
||||
const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE;
|
||||
this.hasCustomCacheHandler = Boolean(CurCacheHandler);
|
||||
const cacheHandlersSymbol = Symbol.for('@next/cache-handlers');
|
||||
const _globalThis = globalThis;
|
||||
if (!CurCacheHandler) {
|
||||
// if we have a global cache handler available leverage it
|
||||
const globalCacheHandler = _globalThis[cacheHandlersSymbol];
|
||||
if (globalCacheHandler == null ? void 0 : globalCacheHandler.FetchCache) {
|
||||
CurCacheHandler = globalCacheHandler.FetchCache;
|
||||
} else {
|
||||
if (fs && serverDistDir) {
|
||||
if (debug) {
|
||||
console.log('using filesystem cache handler');
|
||||
}
|
||||
CurCacheHandler = _filesystemcache.default;
|
||||
}
|
||||
if (_fetchcache.default.isAvailable({
|
||||
_requestHeaders: requestHeaders
|
||||
}) && minimalMode && fetchCache) {
|
||||
if (debug) {
|
||||
console.log('using fetch cache handler');
|
||||
}
|
||||
CurCacheHandler = _fetchcache.default;
|
||||
}
|
||||
}
|
||||
} else if (debug) {
|
||||
console.log('using custom cache handler', CurCacheHandler.name);
|
||||
}
|
||||
if (process.env.__NEXT_TEST_MAX_ISR_CACHE) {
|
||||
// Allow cache size to be overridden for testing purposes
|
||||
maxMemoryCacheSize = parseInt(process.env.__NEXT_TEST_MAX_ISR_CACHE, 10);
|
||||
}
|
||||
this.dev = dev;
|
||||
this.hasDynamicIO = dynamicIO;
|
||||
this.disableForTestmode = process.env.NEXT_PRIVATE_TEST_PROXY === 'true';
|
||||
// this is a hack to avoid Webpack knowing this is equal to this.minimalMode
|
||||
// because we replace this.minimalMode to true in production bundles.
|
||||
const minimalModeKey = 'minimalMode';
|
||||
this[minimalModeKey] = minimalMode;
|
||||
this.requestHeaders = requestHeaders;
|
||||
this.requestProtocol = requestProtocol;
|
||||
this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys;
|
||||
this.prerenderManifest = getPrerenderManifest();
|
||||
this.revalidateTimings = new _sharedrevalidatetimings.SharedRevalidateTimings(this.prerenderManifest);
|
||||
this.fetchCacheKeyPrefix = fetchCacheKeyPrefix;
|
||||
let revalidatedTags = [];
|
||||
if (requestHeaders[_constants.PRERENDER_REVALIDATE_HEADER] === ((_this_prerenderManifest = this.prerenderManifest) == null ? void 0 : (_this_prerenderManifest_preview = _this_prerenderManifest.preview) == null ? void 0 : _this_prerenderManifest_preview.previewModeId)) {
|
||||
this.isOnDemandRevalidate = true;
|
||||
}
|
||||
if (minimalMode && typeof requestHeaders[_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER] === 'string' && requestHeaders[_constants.NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER] === ((_this_prerenderManifest1 = this.prerenderManifest) == null ? void 0 : (_this_prerenderManifest_preview1 = _this_prerenderManifest1.preview) == null ? void 0 : _this_prerenderManifest_preview1.previewModeId)) {
|
||||
revalidatedTags = requestHeaders[_constants.NEXT_CACHE_REVALIDATED_TAGS_HEADER].split(',');
|
||||
}
|
||||
if (CurCacheHandler) {
|
||||
this.cacheHandler = new CurCacheHandler({
|
||||
dev,
|
||||
fs,
|
||||
flushToDisk,
|
||||
serverDistDir,
|
||||
revalidatedTags,
|
||||
maxMemoryCacheSize,
|
||||
_requestHeaders: requestHeaders,
|
||||
fetchCacheKeyPrefix
|
||||
});
|
||||
}
|
||||
}
|
||||
calculateRevalidate(pathname, fromTime, dev, isFallback) {
|
||||
// in development we don't have a prerender-manifest
|
||||
// and default to always revalidating to allow easier debugging
|
||||
if (dev) return Math.floor(performance.timeOrigin + performance.now() - 1000);
|
||||
// if an entry isn't present in routes we fallback to a default
|
||||
// of revalidating after 1 second unless it's a fallback request.
|
||||
const initialRevalidateSeconds = this.revalidateTimings.get((0, _toroute.toRoute)(pathname)) ?? (isFallback ? false : 1);
|
||||
const revalidateAfter = typeof initialRevalidateSeconds === 'number' ? initialRevalidateSeconds * 1000 + fromTime : initialRevalidateSeconds;
|
||||
return revalidateAfter;
|
||||
}
|
||||
_getPathname(pathname, fetchCache) {
|
||||
return fetchCache ? pathname : (0, _normalizepagepath.normalizePagePath)(pathname);
|
||||
}
|
||||
resetRequestCache() {
|
||||
var _this_cacheHandler_resetRequestCache, _this_cacheHandler;
|
||||
(_this_cacheHandler = this.cacheHandler) == null ? void 0 : (_this_cacheHandler_resetRequestCache = _this_cacheHandler.resetRequestCache) == null ? void 0 : _this_cacheHandler_resetRequestCache.call(_this_cacheHandler);
|
||||
}
|
||||
async lock(cacheKey) {
|
||||
let unlockNext = ()=>Promise.resolve();
|
||||
const existingLock = this.locks.get(cacheKey);
|
||||
if (existingLock) {
|
||||
await existingLock;
|
||||
}
|
||||
const newLock = new Promise((resolve)=>{
|
||||
unlockNext = async ()=>{
|
||||
resolve();
|
||||
this.locks.delete(cacheKey) // Remove the lock upon release
|
||||
;
|
||||
};
|
||||
});
|
||||
this.locks.set(cacheKey, newLock);
|
||||
return unlockNext;
|
||||
}
|
||||
async revalidateTag(tags) {
|
||||
var _this_cacheHandler_revalidateTag, _this_cacheHandler;
|
||||
return (_this_cacheHandler = this.cacheHandler) == null ? void 0 : (_this_cacheHandler_revalidateTag = _this_cacheHandler.revalidateTag) == null ? void 0 : _this_cacheHandler_revalidateTag.call(_this_cacheHandler, tags);
|
||||
}
|
||||
// x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
|
||||
async generateCacheKey(url, init = {}) {
|
||||
// this should be bumped anytime a fix is made to cache entries
|
||||
// that should bust the cache
|
||||
const MAIN_KEY_PREFIX = 'v3';
|
||||
const bodyChunks = [];
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
if (init.body) {
|
||||
// handle ReadableStream body
|
||||
if (typeof init.body.getReader === 'function') {
|
||||
const readableBody = init.body;
|
||||
const chunks = [];
|
||||
try {
|
||||
await readableBody.pipeTo(new WritableStream({
|
||||
write (chunk) {
|
||||
if (typeof chunk === 'string') {
|
||||
chunks.push(encoder.encode(chunk));
|
||||
bodyChunks.push(chunk);
|
||||
} else {
|
||||
chunks.push(chunk);
|
||||
bodyChunks.push(decoder.decode(chunk, {
|
||||
stream: true
|
||||
}));
|
||||
}
|
||||
}
|
||||
}));
|
||||
// Flush the decoder.
|
||||
bodyChunks.push(decoder.decode());
|
||||
// Create a new buffer with all the chunks.
|
||||
const length = chunks.reduce((total, arr)=>total + arr.length, 0);
|
||||
const arrayBuffer = new Uint8Array(length);
|
||||
// Push each of the chunks into the new array buffer.
|
||||
let offset = 0;
|
||||
for (const chunk of chunks){
|
||||
arrayBuffer.set(chunk, offset);
|
||||
offset += chunk.length;
|
||||
}
|
||||
;
|
||||
init._ogBody = arrayBuffer;
|
||||
} catch (err) {
|
||||
console.error('Problem reading body', err);
|
||||
}
|
||||
} else if (typeof init.body.keys === 'function') {
|
||||
const formData = init.body;
|
||||
init._ogBody = init.body;
|
||||
for (const key of new Set([
|
||||
...formData.keys()
|
||||
])){
|
||||
const values = formData.getAll(key);
|
||||
bodyChunks.push(`${key}=${(await Promise.all(values.map(async (val)=>{
|
||||
if (typeof val === 'string') {
|
||||
return val;
|
||||
} else {
|
||||
return await val.text();
|
||||
}
|
||||
}))).join(',')}`);
|
||||
}
|
||||
// handle blob body
|
||||
} else if (typeof init.body.arrayBuffer === 'function') {
|
||||
const blob = init.body;
|
||||
const arrayBuffer = await blob.arrayBuffer();
|
||||
bodyChunks.push(await blob.text());
|
||||
init._ogBody = new Blob([
|
||||
arrayBuffer
|
||||
], {
|
||||
type: blob.type
|
||||
});
|
||||
} else if (typeof init.body === 'string') {
|
||||
bodyChunks.push(init.body);
|
||||
init._ogBody = init.body;
|
||||
}
|
||||
}
|
||||
const headers = typeof (init.headers || {}).keys === 'function' ? Object.fromEntries(init.headers) : Object.assign({}, init.headers);
|
||||
if ('traceparent' in headers) delete headers['traceparent'];
|
||||
const cacheString = JSON.stringify([
|
||||
MAIN_KEY_PREFIX,
|
||||
this.fetchCacheKeyPrefix || '',
|
||||
url,
|
||||
init.method,
|
||||
headers,
|
||||
init.mode,
|
||||
init.redirect,
|
||||
init.credentials,
|
||||
init.referrer,
|
||||
init.referrerPolicy,
|
||||
init.integrity,
|
||||
init.cache,
|
||||
bodyChunks
|
||||
]);
|
||||
if (process.env.NEXT_RUNTIME === 'edge') {
|
||||
function bufferToHex(buffer) {
|
||||
return Array.prototype.map.call(new Uint8Array(buffer), (b)=>b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
const buffer = encoder.encode(cacheString);
|
||||
return bufferToHex(await crypto.subtle.digest('SHA-256', buffer));
|
||||
} else {
|
||||
const crypto1 = require('crypto');
|
||||
return crypto1.createHash('sha256').update(cacheString).digest('hex');
|
||||
}
|
||||
}
|
||||
// get data from cache if available
|
||||
async get(cacheKey, ctx) {
|
||||
var _this_cacheHandler, _cacheData_value;
|
||||
// unlike other caches if we have a cacheScope we use it even if
|
||||
// testmode would normally disable it or if requestHeaders say 'no-cache'.
|
||||
if (this.hasDynamicIO && ctx.kind === _responsecache.IncrementalCacheKind.FETCH) {
|
||||
const workUnitStore = _workunitasyncstorageinstance.workUnitAsyncStorageInstance.getStore();
|
||||
const resumeDataCache = workUnitStore ? (0, _workunitasyncstorageexternal.getRenderResumeDataCache)(workUnitStore) : null;
|
||||
if (resumeDataCache) {
|
||||
const memoryCacheData = resumeDataCache.fetch.get(cacheKey);
|
||||
if ((memoryCacheData == null ? void 0 : memoryCacheData.kind) === _responsecache.CachedRouteKind.FETCH) {
|
||||
return {
|
||||
isStale: false,
|
||||
value: memoryCacheData,
|
||||
revalidateAfter: false,
|
||||
isFallback: false
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
// we don't leverage the prerender cache in dev mode
|
||||
// so that getStaticProps is always called for easier debugging
|
||||
if (this.disableForTestmode || this.dev && (ctx.kind !== _responsecache.IncrementalCacheKind.FETCH || this.requestHeaders['cache-control'] === 'no-cache')) {
|
||||
return null;
|
||||
}
|
||||
const { isFallback } = ctx;
|
||||
cacheKey = this._getPathname(cacheKey, ctx.kind === _responsecache.IncrementalCacheKind.FETCH);
|
||||
let entry = null;
|
||||
let revalidate = ctx.revalidate;
|
||||
const cacheData = await ((_this_cacheHandler = this.cacheHandler) == null ? void 0 : _this_cacheHandler.get(cacheKey, ctx));
|
||||
if ((cacheData == null ? void 0 : (_cacheData_value = cacheData.value) == null ? void 0 : _cacheData_value.kind) === _responsecache.CachedRouteKind.FETCH) {
|
||||
const combinedTags = [
|
||||
...ctx.tags || [],
|
||||
...ctx.softTags || []
|
||||
];
|
||||
// if a tag was revalidated we don't return stale data
|
||||
if (combinedTags.some((tag)=>{
|
||||
var _this_revalidatedTags;
|
||||
return (_this_revalidatedTags = this.revalidatedTags) == null ? void 0 : _this_revalidatedTags.includes(tag);
|
||||
})) {
|
||||
return null;
|
||||
}
|
||||
revalidate = revalidate || cacheData.value.revalidate;
|
||||
const age = (performance.timeOrigin + performance.now() - (cacheData.lastModified || 0)) / 1000;
|
||||
const isStale = age > revalidate;
|
||||
const data = cacheData.value.data;
|
||||
return {
|
||||
isStale: isStale,
|
||||
value: {
|
||||
kind: _responsecache.CachedRouteKind.FETCH,
|
||||
data,
|
||||
revalidate: revalidate
|
||||
},
|
||||
revalidateAfter: performance.timeOrigin + performance.now() + revalidate * 1000,
|
||||
isFallback
|
||||
};
|
||||
}
|
||||
const curRevalidate = this.revalidateTimings.get((0, _toroute.toRoute)(cacheKey));
|
||||
let isStale;
|
||||
let revalidateAfter;
|
||||
if ((cacheData == null ? void 0 : cacheData.lastModified) === -1) {
|
||||
isStale = -1;
|
||||
revalidateAfter = -1 * _constants.CACHE_ONE_YEAR;
|
||||
} else {
|
||||
revalidateAfter = this.calculateRevalidate(cacheKey, (cacheData == null ? void 0 : cacheData.lastModified) || performance.timeOrigin + performance.now(), this.dev ? ctx.kind !== _responsecache.IncrementalCacheKind.FETCH : false, ctx.isFallback);
|
||||
isStale = revalidateAfter !== false && revalidateAfter < performance.timeOrigin + performance.now() ? true : undefined;
|
||||
}
|
||||
if (cacheData) {
|
||||
entry = {
|
||||
isStale,
|
||||
curRevalidate,
|
||||
revalidateAfter,
|
||||
value: cacheData.value,
|
||||
isFallback
|
||||
};
|
||||
}
|
||||
if (!cacheData && this.prerenderManifest.notFoundRoutes.includes(cacheKey)) {
|
||||
// for the first hit after starting the server the cache
|
||||
// may not have a way to save notFound: true so if
|
||||
// the prerender-manifest marks this as notFound then we
|
||||
// return that entry and trigger a cache set to give it a
|
||||
// chance to update in-memory entries
|
||||
entry = {
|
||||
isStale,
|
||||
value: null,
|
||||
curRevalidate,
|
||||
revalidateAfter,
|
||||
isFallback
|
||||
};
|
||||
this.set(cacheKey, entry.value, ctx);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
// populate the incremental cache with new data
|
||||
async set(pathname, data, ctx) {
|
||||
// Even if we otherwise disable caching for testMode or if no fetchCache is configured
|
||||
// we still always stash results in the cacheScope if one exists. This is because this
|
||||
// is a transient in memory cache that populates caches ahead of a dynamic render in dev mode
|
||||
// to allow the RSC debug info to have the right environment associated to it.
|
||||
if (this.hasDynamicIO && (data == null ? void 0 : data.kind) === _responsecache.CachedRouteKind.FETCH) {
|
||||
const workUnitStore = _workunitasyncstorageinstance.workUnitAsyncStorageInstance.getStore();
|
||||
const prerenderResumeDataCache = workUnitStore ? (0, _workunitasyncstorageexternal.getPrerenderResumeDataCache)(workUnitStore) : null;
|
||||
if (prerenderResumeDataCache) {
|
||||
prerenderResumeDataCache.fetch.set(pathname, data);
|
||||
}
|
||||
}
|
||||
if (this.disableForTestmode || this.dev && !ctx.fetchCache) return;
|
||||
pathname = this._getPathname(pathname, ctx.fetchCache);
|
||||
// FetchCache has upper limit of 2MB per-entry currently
|
||||
const itemSize = JSON.stringify(data).length;
|
||||
if (ctx.fetchCache && // we don't show this error/warning when a custom cache handler is being used
|
||||
// as it might not have this limit
|
||||
!this.hasCustomCacheHandler && itemSize > 2 * 1024 * 1024) {
|
||||
if (this.dev) {
|
||||
throw new Error(`Failed to set Next.js data cache, items over 2MB can not be cached (${itemSize} bytes)`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
var _this_cacheHandler;
|
||||
// Set the value for the revalidate seconds so if it changes we can
|
||||
// update the cache with the new value.
|
||||
if (typeof ctx.revalidate !== 'undefined' && !ctx.fetchCache) {
|
||||
this.revalidateTimings.set((0, _toroute.toRoute)(pathname), ctx.revalidate);
|
||||
}
|
||||
await ((_this_cacheHandler = this.cacheHandler) == null ? void 0 : _this_cacheHandler.set(pathname, data, ctx));
|
||||
} catch (error) {
|
||||
console.warn('Failed to update prerender cache for', pathname, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
import type { PrerenderManifest } from '../../../build';
|
||||
import type { DeepReadonly } from '../../../shared/lib/deep-readonly';
|
||||
import type { Revalidate } from '../revalidate';
|
||||
/**
|
||||
* A shared cache of revalidate timings for routes. This cache is used so we
|
||||
* don't have to modify the prerender manifest when we want to update the
|
||||
* revalidate timings for a route.
|
||||
*/
|
||||
export declare class SharedRevalidateTimings {
|
||||
/**
|
||||
* The prerender manifest that contains the initial revalidate timings for
|
||||
* routes.
|
||||
*/
|
||||
private readonly prerenderManifest;
|
||||
/**
|
||||
* The in-memory cache of revalidate timings for routes. This cache is
|
||||
* populated when the cache is updated with new timings.
|
||||
*/
|
||||
private static readonly timings;
|
||||
constructor(
|
||||
/**
|
||||
* The prerender manifest that contains the initial revalidate timings for
|
||||
* routes.
|
||||
*/
|
||||
prerenderManifest: DeepReadonly<Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>>);
|
||||
/**
|
||||
* Try to get the revalidate timings for a route. This will first try to get
|
||||
* the timings from the in-memory cache. If the timings are not present in the
|
||||
* in-memory cache, then the timings will be sourced from the prerender
|
||||
* manifest.
|
||||
*
|
||||
* @param route the route to get the revalidate timings for
|
||||
* @returns the revalidate timings for the route, or undefined if the timings
|
||||
* are not present in the in-memory cache or the prerender manifest
|
||||
*/
|
||||
get(route: string): Revalidate | undefined;
|
||||
/**
|
||||
* Set the revalidate timings for a route.
|
||||
*
|
||||
* @param route the route to set the revalidate timings for
|
||||
* @param revalidate the revalidate timings for the route
|
||||
*/
|
||||
set(route: string, revalidate: Revalidate): void;
|
||||
/**
|
||||
* Clear the in-memory cache of revalidate timings for routes.
|
||||
*/
|
||||
clear(): void;
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "SharedRevalidateTimings", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return SharedRevalidateTimings;
|
||||
}
|
||||
});
|
||||
class SharedRevalidateTimings {
|
||||
static #_ = /**
|
||||
* The in-memory cache of revalidate timings for routes. This cache is
|
||||
* populated when the cache is updated with new timings.
|
||||
*/ this.timings = new Map();
|
||||
constructor(/**
|
||||
* The prerender manifest that contains the initial revalidate timings for
|
||||
* routes.
|
||||
*/ prerenderManifest){
|
||||
this.prerenderManifest = prerenderManifest;
|
||||
}
|
||||
/**
|
||||
* Try to get the revalidate timings for a route. This will first try to get
|
||||
* the timings from the in-memory cache. If the timings are not present in the
|
||||
* in-memory cache, then the timings will be sourced from the prerender
|
||||
* manifest.
|
||||
*
|
||||
* @param route the route to get the revalidate timings for
|
||||
* @returns the revalidate timings for the route, or undefined if the timings
|
||||
* are not present in the in-memory cache or the prerender manifest
|
||||
*/ get(route) {
|
||||
var _this_prerenderManifest_routes_route, _this_prerenderManifest_dynamicRoutes_route;
|
||||
// This is a copy on write cache that is updated when the cache is updated.
|
||||
// If the cache is never written to, then the timings will be sourced from
|
||||
// the prerender manifest.
|
||||
let revalidate = SharedRevalidateTimings.timings.get(route);
|
||||
if (typeof revalidate !== 'undefined') return revalidate;
|
||||
revalidate = (_this_prerenderManifest_routes_route = this.prerenderManifest.routes[route]) == null ? void 0 : _this_prerenderManifest_routes_route.initialRevalidateSeconds;
|
||||
if (typeof revalidate !== 'undefined') return revalidate;
|
||||
revalidate = (_this_prerenderManifest_dynamicRoutes_route = this.prerenderManifest.dynamicRoutes[route]) == null ? void 0 : _this_prerenderManifest_dynamicRoutes_route.fallbackRevalidate;
|
||||
if (typeof revalidate !== 'undefined') return revalidate;
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Set the revalidate timings for a route.
|
||||
*
|
||||
* @param route the route to set the revalidate timings for
|
||||
* @param revalidate the revalidate timings for the route
|
||||
*/ set(route, revalidate) {
|
||||
SharedRevalidateTimings.timings.set(route, revalidate);
|
||||
}
|
||||
/**
|
||||
* Clear the in-memory cache of revalidate timings for routes.
|
||||
*/ clear() {
|
||||
SharedRevalidateTimings.timings.clear();
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=shared-revalidate-timings.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/incremental-cache/shared-revalidate-timings.ts"],"sourcesContent":["import type { PrerenderManifest } from '../../../build'\nimport type { DeepReadonly } from '../../../shared/lib/deep-readonly'\nimport type { Revalidate } from '../revalidate'\n\n/**\n * A shared cache of revalidate timings for routes. This cache is used so we\n * don't have to modify the prerender manifest when we want to update the\n * revalidate timings for a route.\n */\nexport class SharedRevalidateTimings {\n /**\n * The in-memory cache of revalidate timings for routes. This cache is\n * populated when the cache is updated with new timings.\n */\n private static readonly timings = new Map<string, Revalidate>()\n\n constructor(\n /**\n * The prerender manifest that contains the initial revalidate timings for\n * routes.\n */\n private readonly prerenderManifest: DeepReadonly<\n Pick<PrerenderManifest, 'routes' | 'dynamicRoutes'>\n >\n ) {}\n\n /**\n * Try to get the revalidate timings for a route. This will first try to get\n * the timings from the in-memory cache. If the timings are not present in the\n * in-memory cache, then the timings will be sourced from the prerender\n * manifest.\n *\n * @param route the route to get the revalidate timings for\n * @returns the revalidate timings for the route, or undefined if the timings\n * are not present in the in-memory cache or the prerender manifest\n */\n public get(route: string): Revalidate | undefined {\n // This is a copy on write cache that is updated when the cache is updated.\n // If the cache is never written to, then the timings will be sourced from\n // the prerender manifest.\n let revalidate = SharedRevalidateTimings.timings.get(route)\n if (typeof revalidate !== 'undefined') return revalidate\n\n revalidate = this.prerenderManifest.routes[route]?.initialRevalidateSeconds\n if (typeof revalidate !== 'undefined') return revalidate\n\n revalidate = this.prerenderManifest.dynamicRoutes[route]?.fallbackRevalidate\n if (typeof revalidate !== 'undefined') return revalidate\n\n return undefined\n }\n\n /**\n * Set the revalidate timings for a route.\n *\n * @param route the route to set the revalidate timings for\n * @param revalidate the revalidate timings for the route\n */\n public set(route: string, revalidate: Revalidate) {\n SharedRevalidateTimings.timings.set(route, revalidate)\n }\n\n /**\n * Clear the in-memory cache of revalidate timings for routes.\n */\n public clear() {\n SharedRevalidateTimings.timings.clear()\n }\n}\n"],"names":["SharedRevalidateTimings","timings","Map","constructor","prerenderManifest","get","route","revalidate","routes","initialRevalidateSeconds","dynamicRoutes","fallbackRevalidate","undefined","set","clear"],"mappings":";;;;+BASaA;;;eAAAA;;;AAAN,MAAMA;gBACX;;;GAGC,QACuBC,UAAU,IAAIC;IAEtCC,YACE;;;KAGC,GACD,AAAiBC,iBAEhB,CACD;aAHiBA,oBAAAA;IAGhB;IAEH;;;;;;;;;GASC,GACD,AAAOC,IAAIC,KAAa,EAA0B;YAOnC,sCAGA;QATb,2EAA2E;QAC3E,0EAA0E;QAC1E,0BAA0B;QAC1B,IAAIC,aAAaP,wBAAwBC,OAAO,CAACI,GAAG,CAACC;QACrD,IAAI,OAAOC,eAAe,aAAa,OAAOA;QAE9CA,cAAa,uCAAA,IAAI,CAACH,iBAAiB,CAACI,MAAM,CAACF,MAAM,qBAApC,qCAAsCG,wBAAwB;QAC3E,IAAI,OAAOF,eAAe,aAAa,OAAOA;QAE9CA,cAAa,8CAAA,IAAI,CAACH,iBAAiB,CAACM,aAAa,CAACJ,MAAM,qBAA3C,4CAA6CK,kBAAkB;QAC5E,IAAI,OAAOJ,eAAe,aAAa,OAAOA;QAE9C,OAAOK;IACT;IAEA;;;;;GAKC,GACD,AAAOC,IAAIP,KAAa,EAAEC,UAAsB,EAAE;QAChDP,wBAAwBC,OAAO,CAACY,GAAG,CAACP,OAAOC;IAC7C;IAEA;;GAEC,GACD,AAAOO,QAAQ;QACbd,wBAAwBC,OAAO,CAACa,KAAK;IACvC;AACF"}
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
type TagsManifest = {
|
||||
items: {
|
||||
[tag: string]: {
|
||||
revalidatedAt?: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
export declare const tagsManifest: TagsManifest;
|
||||
export declare const isTagStale: (tags: string[], timestamp: number) => boolean;
|
||||
export {};
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
isTagStale: null,
|
||||
tagsManifest: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
isTagStale: function() {
|
||||
return isTagStale;
|
||||
},
|
||||
tagsManifest: function() {
|
||||
return tagsManifest;
|
||||
}
|
||||
});
|
||||
const tagsManifest = {
|
||||
items: {}
|
||||
};
|
||||
const isTagStale = (tags, timestamp)=>{
|
||||
for (const tag of tags){
|
||||
const tagEntry = tagsManifest.items[tag];
|
||||
if (typeof (tagEntry == null ? void 0 : tagEntry.revalidatedAt) === 'number' && // TODO: use performance.now and update file-system-cache?
|
||||
tagEntry.revalidatedAt >= timestamp) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
//# sourceMappingURL=tags-manifest.external.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/incremental-cache/tags-manifest.external.ts"],"sourcesContent":["type TagsManifest = {\n items: { [tag: string]: { revalidatedAt?: number } }\n}\n\n// we share tags manifest between \"use cache\" handlers and\n// previous file-system-cache\nexport const tagsManifest: TagsManifest = {\n items: {},\n}\n\nexport const isTagStale = (tags: string[], timestamp: number) => {\n for (const tag of tags) {\n const tagEntry = tagsManifest.items[tag]\n if (\n typeof tagEntry?.revalidatedAt === 'number' &&\n // TODO: use performance.now and update file-system-cache?\n tagEntry.revalidatedAt >= timestamp\n ) {\n return true\n }\n }\n return false\n}\n"],"names":["isTagStale","tagsManifest","items","tags","timestamp","tag","tagEntry","revalidatedAt"],"mappings":";;;;;;;;;;;;;;;IAUaA,UAAU;eAAVA;;IAJAC,YAAY;eAAZA;;;AAAN,MAAMA,eAA6B;IACxCC,OAAO,CAAC;AACV;AAEO,MAAMF,aAAa,CAACG,MAAgBC;IACzC,KAAK,MAAMC,OAAOF,KAAM;QACtB,MAAMG,WAAWL,aAAaC,KAAK,CAACG,IAAI;QACxC,IACE,QAAOC,4BAAAA,SAAUC,aAAa,MAAK,YACnC,0DAA0D;QAC1DD,SAASC,aAAa,IAAIH,WAC1B;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT"}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
export declare const INTERCEPTION_ROUTE_MARKERS: readonly ["(..)(..)", "(.)", "(..)", "(...)"];
|
||||
export declare function isInterceptionRouteAppPath(path: string): boolean;
|
||||
export declare function extractInterceptionRouteInformation(path: string): {
|
||||
interceptingRoute: string;
|
||||
interceptedRoute: string;
|
||||
};
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
INTERCEPTION_ROUTE_MARKERS: null,
|
||||
extractInterceptionRouteInformation: null,
|
||||
isInterceptionRouteAppPath: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
INTERCEPTION_ROUTE_MARKERS: function() {
|
||||
return INTERCEPTION_ROUTE_MARKERS;
|
||||
},
|
||||
extractInterceptionRouteInformation: function() {
|
||||
return extractInterceptionRouteInformation;
|
||||
},
|
||||
isInterceptionRouteAppPath: function() {
|
||||
return isInterceptionRouteAppPath;
|
||||
}
|
||||
});
|
||||
const _apppaths = require("../../shared/lib/router/utils/app-paths");
|
||||
const INTERCEPTION_ROUTE_MARKERS = [
|
||||
'(..)(..)',
|
||||
'(.)',
|
||||
'(..)',
|
||||
'(...)'
|
||||
];
|
||||
function isInterceptionRouteAppPath(path) {
|
||||
// TODO-APP: add more serious validation
|
||||
return path.split('/').find((segment)=>INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m))) !== undefined;
|
||||
}
|
||||
function extractInterceptionRouteInformation(path) {
|
||||
let interceptingRoute, marker, interceptedRoute;
|
||||
for (const segment of path.split('/')){
|
||||
marker = INTERCEPTION_ROUTE_MARKERS.find((m)=>segment.startsWith(m));
|
||||
if (marker) {
|
||||
;
|
||||
[interceptingRoute, interceptedRoute] = path.split(marker, 2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!interceptingRoute || !marker || !interceptedRoute) {
|
||||
throw new Error(`Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);
|
||||
}
|
||||
interceptingRoute = (0, _apppaths.normalizeAppPath)(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed
|
||||
;
|
||||
switch(marker){
|
||||
case '(.)':
|
||||
// (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route
|
||||
if (interceptingRoute === '/') {
|
||||
interceptedRoute = `/${interceptedRoute}`;
|
||||
} else {
|
||||
interceptedRoute = interceptingRoute + '/' + interceptedRoute;
|
||||
}
|
||||
break;
|
||||
case '(..)':
|
||||
// (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route
|
||||
if (interceptingRoute === '/') {
|
||||
throw new Error(`Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`);
|
||||
}
|
||||
interceptedRoute = interceptingRoute.split('/').slice(0, -1).concat(interceptedRoute).join('/');
|
||||
break;
|
||||
case '(...)':
|
||||
// (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route
|
||||
interceptedRoute = '/' + interceptedRoute;
|
||||
break;
|
||||
case '(..)(..)':
|
||||
// (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route
|
||||
const splitInterceptingRoute = interceptingRoute.split('/');
|
||||
if (splitInterceptingRoute.length <= 2) {
|
||||
throw new Error(`Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`);
|
||||
}
|
||||
interceptedRoute = splitInterceptingRoute.slice(0, -2).concat(interceptedRoute).join('/');
|
||||
break;
|
||||
default:
|
||||
throw new Error('Invariant: unexpected marker');
|
||||
}
|
||||
return {
|
||||
interceptingRoute,
|
||||
interceptedRoute
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=interception-routes.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/interception-routes.ts"],"sourcesContent":["import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\n\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n '(..)(..)',\n '(.)',\n '(..)',\n '(...)',\n] as const\n\nexport function isInterceptionRouteAppPath(path: string): boolean {\n // TODO-APP: add more serious validation\n return (\n path\n .split('/')\n .find((segment) =>\n INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n ) !== undefined\n )\n}\n\nexport function extractInterceptionRouteInformation(path: string) {\n let interceptingRoute: string | undefined,\n marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined,\n interceptedRoute: string | undefined\n\n for (const segment of path.split('/')) {\n marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n if (marker) {\n ;[interceptingRoute, interceptedRoute] = path.split(marker, 2)\n break\n }\n }\n\n if (!interceptingRoute || !marker || !interceptedRoute) {\n throw new Error(\n `Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`\n )\n }\n\n interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n\n switch (marker) {\n case '(.)':\n // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n if (interceptingRoute === '/') {\n interceptedRoute = `/${interceptedRoute}`\n } else {\n interceptedRoute = interceptingRoute + '/' + interceptedRoute\n }\n break\n case '(..)':\n // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n if (interceptingRoute === '/') {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n )\n }\n interceptedRoute = interceptingRoute\n .split('/')\n .slice(0, -1)\n .concat(interceptedRoute)\n .join('/')\n break\n case '(...)':\n // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n interceptedRoute = '/' + interceptedRoute\n break\n case '(..)(..)':\n // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n\n const splitInterceptingRoute = interceptingRoute.split('/')\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n )\n }\n\n interceptedRoute = splitInterceptingRoute\n .slice(0, -2)\n .concat(interceptedRoute)\n .join('/')\n break\n default:\n throw new Error('Invariant: unexpected marker')\n }\n\n return { interceptingRoute, interceptedRoute }\n}\n"],"names":["INTERCEPTION_ROUTE_MARKERS","extractInterceptionRouteInformation","isInterceptionRouteAppPath","path","split","find","segment","m","startsWith","undefined","interceptingRoute","marker","interceptedRoute","Error","normalizeAppPath","slice","concat","join","splitInterceptingRoute","length"],"mappings":";;;;;;;;;;;;;;;;IAGaA,0BAA0B;eAA1BA;;IAkBGC,mCAAmC;eAAnCA;;IAXAC,0BAA0B;eAA1BA;;;0BAViB;AAG1B,MAAMF,6BAA6B;IACxC;IACA;IACA;IACA;CACD;AAEM,SAASE,2BAA2BC,IAAY;IACrD,wCAAwC;IACxC,OACEA,KACGC,KAAK,CAAC,KACNC,IAAI,CAAC,CAACC,UACLN,2BAA2BK,IAAI,CAAC,CAACE,IAAMD,QAAQE,UAAU,CAACD,SACtDE;AAEZ;AAEO,SAASR,oCAAoCE,IAAY;IAC9D,IAAIO,mBACFC,QACAC;IAEF,KAAK,MAAMN,WAAWH,KAAKC,KAAK,CAAC,KAAM;QACrCO,SAASX,2BAA2BK,IAAI,CAAC,CAACE,IAAMD,QAAQE,UAAU,CAACD;QACnE,IAAII,QAAQ;;YACT,CAACD,mBAAmBE,iBAAiB,GAAGT,KAAKC,KAAK,CAACO,QAAQ;YAC5D;QACF;IACF;IAEA,IAAI,CAACD,qBAAqB,CAACC,UAAU,CAACC,kBAAkB;QACtD,MAAM,IAAIC,MACR,CAAC,4BAA4B,EAAEV,KAAK,iFAAiF,CAAC;IAE1H;IAEAO,oBAAoBI,IAAAA,0BAAgB,EAACJ,mBAAmB,iDAAiD;;IAEzG,OAAQC;QACN,KAAK;YACH,oIAAoI;YACpI,IAAID,sBAAsB,KAAK;gBAC7BE,mBAAmB,CAAC,CAAC,EAAEA,kBAAkB;YAC3C,OAAO;gBACLA,mBAAmBF,oBAAoB,MAAME;YAC/C;YACA;QACF,KAAK;YACH,uHAAuH;YACvH,IAAIF,sBAAsB,KAAK;gBAC7B,MAAM,IAAIG,MACR,CAAC,4BAA4B,EAAEV,KAAK,4DAA4D,CAAC;YAErG;YACAS,mBAAmBF,kBAChBN,KAAK,CAAC,KACNW,KAAK,CAAC,GAAG,CAAC,GACVC,MAAM,CAACJ,kBACPK,IAAI,CAAC;YACR;QACF,KAAK;YACH,kIAAkI;YAClIL,mBAAmB,MAAMA;YACzB;QACF,KAAK;YACH,iIAAiI;YAEjI,MAAMM,yBAAyBR,kBAAkBN,KAAK,CAAC;YACvD,IAAIc,uBAAuBC,MAAM,IAAI,GAAG;gBACtC,MAAM,IAAIN,MACR,CAAC,4BAA4B,EAAEV,KAAK,+DAA+D,CAAC;YAExG;YAEAS,mBAAmBM,uBAChBH,KAAK,CAAC,GAAG,CAAC,GACVC,MAAM,CAACJ,kBACPK,IAAI,CAAC;YACR;QACF;YACE,MAAM,IAAIJ,MAAM;IACpB;IAEA,OAAO;QAAEH;QAAmBE;IAAiB;AAC/C"}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
export declare function isIPv6(s: string): boolean;
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
// Regex from `node/lib/internal/net.js`: https://github.com/nodejs/node/blob/9fc57006c27564ed7f75eee090eca86786508f51/lib/internal/net.js#L19-L29
|
||||
// License included below:
|
||||
// Copyright Joyent, Inc. and other Node 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.
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "isIPv6", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return isIPv6;
|
||||
}
|
||||
});
|
||||
const v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])';
|
||||
const v4Str = `(${v4Seg}[.]){3}${v4Seg}`;
|
||||
const v6Seg = '(?:[0-9a-fA-F]{1,4})';
|
||||
const IPv6Reg = new RegExp('^(' + `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` + `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` + `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` + `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` + `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` + `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` + `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` + `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` + ')(%[0-9a-zA-Z-.:]{1,})?$');
|
||||
function isIPv6(s) {
|
||||
return IPv6Reg.test(s);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=is-ipv6.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/is-ipv6.ts"],"sourcesContent":["// Regex from `node/lib/internal/net.js`: https://github.com/nodejs/node/blob/9fc57006c27564ed7f75eee090eca86786508f51/lib/internal/net.js#L19-L29\n// License included below:\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nconst v4Seg = '(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'\nconst v4Str = `(${v4Seg}[.]){3}${v4Seg}`\nconst v6Seg = '(?:[0-9a-fA-F]{1,4})'\nconst IPv6Reg = new RegExp(\n '^(' +\n `(?:${v6Seg}:){7}(?:${v6Seg}|:)|` +\n `(?:${v6Seg}:){6}(?:${v4Str}|:${v6Seg}|:)|` +\n `(?:${v6Seg}:){5}(?::${v4Str}|(:${v6Seg}){1,2}|:)|` +\n `(?:${v6Seg}:){4}(?:(:${v6Seg}){0,1}:${v4Str}|(:${v6Seg}){1,3}|:)|` +\n `(?:${v6Seg}:){3}(?:(:${v6Seg}){0,2}:${v4Str}|(:${v6Seg}){1,4}|:)|` +\n `(?:${v6Seg}:){2}(?:(:${v6Seg}){0,3}:${v4Str}|(:${v6Seg}){1,5}|:)|` +\n `(?:${v6Seg}:){1}(?:(:${v6Seg}){0,4}:${v4Str}|(:${v6Seg}){1,6}|:)|` +\n `(?::((?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +\n ')(%[0-9a-zA-Z-.:]{1,})?$'\n)\n\nexport function isIPv6(s: string) {\n return IPv6Reg.test(s)\n}\n"],"names":["isIPv6","v4Seg","v4Str","v6Seg","IPv6Reg","RegExp","s","test"],"mappings":"AAAA,kJAAkJ;AAClJ,0BAA0B;AAC1B,sDAAsD;AACtD,EAAE;AACF,0EAA0E;AAC1E,gEAAgE;AAChE,sEAAsE;AACtE,sEAAsE;AACtE,4EAA4E;AAC5E,qEAAqE;AACrE,wBAAwB;AACxB,EAAE;AACF,0EAA0E;AAC1E,yDAAyD;AACzD,EAAE;AACF,0EAA0E;AAC1E,6DAA6D;AAC7D,4EAA4E;AAC5E,2EAA2E;AAC3E,wEAAwE;AACxE,4EAA4E;AAC5E,yCAAyC;;;;;+BAkBzBA;;;eAAAA;;;AAhBhB,MAAMC,QAAQ;AACd,MAAMC,QAAQ,CAAC,CAAC,EAAED,MAAM,OAAO,EAAEA,OAAO;AACxC,MAAME,QAAQ;AACd,MAAMC,UAAU,IAAIC,OAClB,OACE,CAAC,GAAG,EAAEF,MAAM,QAAQ,EAAEA,MAAM,IAAI,CAAC,GACjC,CAAC,GAAG,EAAEA,MAAM,QAAQ,EAAED,MAAM,EAAE,EAAEC,MAAM,IAAI,CAAC,GAC3C,CAAC,GAAG,EAAEA,MAAM,SAAS,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnD,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,GAAG,EAAEA,MAAM,UAAU,EAAEA,MAAM,OAAO,EAAED,MAAM,GAAG,EAAEC,MAAM,UAAU,CAAC,GACnE,CAAC,SAAS,EAAEA,MAAM,OAAO,EAAED,MAAM,KAAK,EAAEC,MAAM,UAAU,CAAC,GACzD;AAGG,SAASH,OAAOM,CAAS;IAC9B,OAAOF,QAAQG,IAAI,CAACD;AACtB"}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
export declare class LRUCache<T> {
|
||||
private cache;
|
||||
private sizes;
|
||||
private totalSize;
|
||||
private maxSize;
|
||||
private calculateSize;
|
||||
constructor(maxSize: number, calculateSize?: (value: T) => number);
|
||||
set(key?: string | null, value?: T): void;
|
||||
has(key?: string | null): boolean;
|
||||
get(key?: string | null): T | undefined;
|
||||
private touch;
|
||||
private evictIfNecessary;
|
||||
private evictLeastRecentlyUsed;
|
||||
reset(): void;
|
||||
keys(): string[];
|
||||
remove(key: string): void;
|
||||
clear(): void;
|
||||
get size(): number;
|
||||
get currentSize(): number;
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "LRUCache", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return LRUCache;
|
||||
}
|
||||
});
|
||||
class LRUCache {
|
||||
constructor(maxSize, calculateSize){
|
||||
this.cache = new Map();
|
||||
this.sizes = new Map();
|
||||
this.totalSize = 0;
|
||||
this.maxSize = maxSize;
|
||||
this.calculateSize = calculateSize || (()=>1);
|
||||
}
|
||||
set(key, value) {
|
||||
if (!key || !value) return;
|
||||
const size = this.calculateSize(value);
|
||||
if (size > this.maxSize) {
|
||||
console.warn('Single item size exceeds maxSize');
|
||||
return;
|
||||
}
|
||||
if (this.cache.has(key)) {
|
||||
this.totalSize -= this.sizes.get(key) || 0;
|
||||
}
|
||||
this.cache.set(key, value);
|
||||
this.sizes.set(key, size);
|
||||
this.totalSize += size;
|
||||
this.touch(key);
|
||||
}
|
||||
has(key) {
|
||||
if (!key) return false;
|
||||
this.touch(key);
|
||||
return Boolean(this.cache.get(key));
|
||||
}
|
||||
get(key) {
|
||||
if (!key) return;
|
||||
const value = this.cache.get(key);
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
this.touch(key);
|
||||
return value;
|
||||
}
|
||||
touch(key) {
|
||||
const value = this.cache.get(key);
|
||||
if (value !== undefined) {
|
||||
this.cache.delete(key);
|
||||
this.cache.set(key, value);
|
||||
this.evictIfNecessary();
|
||||
}
|
||||
}
|
||||
evictIfNecessary() {
|
||||
while(this.totalSize > this.maxSize && this.cache.size > 0){
|
||||
this.evictLeastRecentlyUsed();
|
||||
}
|
||||
}
|
||||
evictLeastRecentlyUsed() {
|
||||
const lruKey = this.cache.keys().next().value;
|
||||
if (lruKey !== undefined) {
|
||||
const lruSize = this.sizes.get(lruKey) || 0;
|
||||
this.totalSize -= lruSize;
|
||||
this.cache.delete(lruKey);
|
||||
this.sizes.delete(lruKey);
|
||||
}
|
||||
}
|
||||
reset() {
|
||||
this.cache.clear();
|
||||
this.sizes.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
keys() {
|
||||
return [
|
||||
...this.cache.keys()
|
||||
];
|
||||
}
|
||||
remove(key) {
|
||||
if (this.cache.has(key)) {
|
||||
this.totalSize -= this.sizes.get(key) || 0;
|
||||
this.cache.delete(key);
|
||||
this.sizes.delete(key);
|
||||
}
|
||||
}
|
||||
clear() {
|
||||
this.cache.clear();
|
||||
this.sizes.clear();
|
||||
this.totalSize = 0;
|
||||
}
|
||||
get size() {
|
||||
return this.cache.size;
|
||||
}
|
||||
get currentSize() {
|
||||
return this.totalSize;
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=lru-cache.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
export declare function matchNextDataPathname(pathname: string | null | undefined): false | Record<string, any>;
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "matchNextDataPathname", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return matchNextDataPathname;
|
||||
}
|
||||
});
|
||||
const _pathmatch = require("../../shared/lib/router/utils/path-match");
|
||||
const matcher = (0, _pathmatch.getPathMatch)('/_next/data/:path*');
|
||||
function matchNextDataPathname(pathname) {
|
||||
if (typeof pathname !== 'string') return false;
|
||||
return matcher(pathname);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=match-next-data-pathname.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/match-next-data-pathname.ts"],"sourcesContent":["import { getPathMatch } from '../../shared/lib/router/utils/path-match'\n\nconst matcher = getPathMatch('/_next/data/:path*')\n\nexport function matchNextDataPathname(pathname: string | null | undefined) {\n if (typeof pathname !== 'string') return false\n\n return matcher(pathname)\n}\n"],"names":["matchNextDataPathname","matcher","getPathMatch","pathname"],"mappings":";;;;+BAIgBA;;;eAAAA;;;2BAJa;AAE7B,MAAMC,UAAUC,IAAAA,uBAAY,EAAC;AAEtB,SAASF,sBAAsBG,QAAmC;IACvE,IAAI,OAAOA,aAAa,UAAU,OAAO;IAEzC,OAAOF,QAAQE;AACjB"}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import type { ServerResponse, OutgoingHttpHeaders, OutgoingHttpHeader, IncomingMessage, IncomingHttpHeaders } from 'http';
|
||||
import type { Socket } from 'net';
|
||||
import Stream from 'stream';
|
||||
interface MockedRequestOptions {
|
||||
url: string;
|
||||
headers: IncomingHttpHeaders;
|
||||
method: string;
|
||||
readable?: Stream.Readable;
|
||||
socket?: Socket | null;
|
||||
}
|
||||
export declare class MockedRequest extends Stream.Readable implements IncomingMessage {
|
||||
url: string;
|
||||
readonly statusCode?: number | undefined;
|
||||
readonly statusMessage?: string | undefined;
|
||||
readonly headers: IncomingHttpHeaders;
|
||||
readonly method: string;
|
||||
readonly httpVersion = "1.0";
|
||||
readonly httpVersionMajor = 1;
|
||||
readonly httpVersionMinor = 0;
|
||||
private bodyReadable?;
|
||||
socket: Socket;
|
||||
constructor({ url, headers, method, socket, readable, }: MockedRequestOptions);
|
||||
get headersDistinct(): NodeJS.Dict<string[]>;
|
||||
_read(size: number): void;
|
||||
/**
|
||||
* The `connection` property is just an alias for the `socket` property.
|
||||
*
|
||||
* @deprecated — since v13.0.0 - Use socket instead.
|
||||
*/
|
||||
get connection(): Socket;
|
||||
get aborted(): boolean;
|
||||
get complete(): boolean;
|
||||
get trailers(): NodeJS.Dict<string>;
|
||||
get trailersDistinct(): NodeJS.Dict<string[]>;
|
||||
get rawTrailers(): string[];
|
||||
get rawHeaders(): string[];
|
||||
setTimeout(): this;
|
||||
}
|
||||
export interface MockedResponseOptions {
|
||||
statusCode?: number;
|
||||
socket?: Socket | null;
|
||||
headers?: OutgoingHttpHeaders;
|
||||
resWriter?: (chunk: Uint8Array | Buffer | string) => boolean;
|
||||
}
|
||||
export declare class MockedResponse extends Stream.Writable implements ServerResponse {
|
||||
statusCode: number;
|
||||
statusMessage: string;
|
||||
finished: boolean;
|
||||
headersSent: boolean;
|
||||
readonly socket: Socket | null;
|
||||
private resWriter;
|
||||
readonly headPromise: Promise<void>;
|
||||
private headPromiseResolve?;
|
||||
constructor(res?: MockedResponseOptions);
|
||||
appendHeader(name: string, value: string | string[]): this;
|
||||
/**
|
||||
* The `connection` property is just an alias for the `socket` property.
|
||||
*
|
||||
* @deprecated — since v13.0.0 - Use socket instead.
|
||||
*/
|
||||
get connection(): Socket | null;
|
||||
write(chunk: Uint8Array | Buffer | string): boolean;
|
||||
end(): this;
|
||||
/**
|
||||
* This method is a no-op because the `MockedResponse` instance is not
|
||||
* actually connected to a socket. This method is not specified on the
|
||||
* interface type for `ServerResponse` but is called by Node.js.
|
||||
*
|
||||
* @see https://github.com/nodejs/node/pull/7949
|
||||
*/
|
||||
_implicitHeader(): void;
|
||||
_write(chunk: Buffer | string, _encoding: string, callback: () => void): void;
|
||||
writeHead(statusCode: number, statusMessage?: string | undefined, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined): this;
|
||||
writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[] | undefined): this;
|
||||
hasHeader(name: string): boolean;
|
||||
getHeader(name: string): string | undefined;
|
||||
getHeaders(): OutgoingHttpHeaders;
|
||||
getHeaderNames(): string[];
|
||||
setHeader(name: string, value: OutgoingHttpHeader): this;
|
||||
removeHeader(name: string): void;
|
||||
flushHeaders(): void;
|
||||
get strictContentLength(): boolean;
|
||||
writeEarlyHints(): void;
|
||||
get req(): IncomingMessage;
|
||||
assignSocket(): void;
|
||||
detachSocket(): void;
|
||||
writeContinue(): void;
|
||||
writeProcessing(): void;
|
||||
get upgrading(): boolean;
|
||||
get chunkedEncoding(): boolean;
|
||||
get shouldKeepAlive(): boolean;
|
||||
get useChunkedEncodingByDefault(): boolean;
|
||||
get sendDate(): boolean;
|
||||
setTimeout(): this;
|
||||
addTrailers(): void;
|
||||
setHeaders(): this;
|
||||
}
|
||||
interface RequestResponseMockerOptions {
|
||||
url: string;
|
||||
headers?: IncomingHttpHeaders;
|
||||
method?: string;
|
||||
bodyReadable?: Stream.Readable;
|
||||
resWriter?: (chunk: Uint8Array | Buffer | string) => boolean;
|
||||
socket?: Socket | null;
|
||||
}
|
||||
export declare function createRequestResponseMocks({ url, headers, method, bodyReadable, resWriter, socket, }: RequestResponseMockerOptions): {
|
||||
req: MockedRequest;
|
||||
res: MockedResponse;
|
||||
};
|
||||
export {};
|
||||
+324
@@ -0,0 +1,324 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
MockedRequest: null,
|
||||
MockedResponse: null,
|
||||
createRequestResponseMocks: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
MockedRequest: function() {
|
||||
return MockedRequest;
|
||||
},
|
||||
MockedResponse: function() {
|
||||
return MockedResponse;
|
||||
},
|
||||
createRequestResponseMocks: function() {
|
||||
return createRequestResponseMocks;
|
||||
}
|
||||
});
|
||||
const _stream = /*#__PURE__*/ _interop_require_default(require("stream"));
|
||||
const _utils = require("../web/utils");
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
class MockedRequest extends _stream.default.Readable {
|
||||
constructor({ url, headers, method, socket = null, readable }){
|
||||
super(), // This is hardcoded for now, but can be updated to be configurable if needed.
|
||||
this.httpVersion = '1.0', this.httpVersionMajor = 1, this.httpVersionMinor = 0, // If we don't actually have a socket, we'll just use a mock one that
|
||||
// always returns false for the `encrypted` property and undefined for the
|
||||
// `remoteAddress` property.
|
||||
this.socket = new Proxy({}, {
|
||||
get: (_target, prop)=>{
|
||||
if (prop !== 'encrypted' && prop !== 'remoteAddress') {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
if (prop === 'remoteAddress') return undefined;
|
||||
// For this mock request, always ensure we just respond with the encrypted
|
||||
// set to false to ensure there's no odd leakages.
|
||||
return false;
|
||||
}
|
||||
});
|
||||
this.url = url;
|
||||
this.headers = headers;
|
||||
this.method = method;
|
||||
if (readable) {
|
||||
this.bodyReadable = readable;
|
||||
this.bodyReadable.on('end', ()=>this.emit('end'));
|
||||
this.bodyReadable.on('close', ()=>this.emit('close'));
|
||||
}
|
||||
if (socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
}
|
||||
get headersDistinct() {
|
||||
const headers = {};
|
||||
for (const [key, value] of Object.entries(this.headers)){
|
||||
if (!value) continue;
|
||||
headers[key] = Array.isArray(value) ? value : [
|
||||
value
|
||||
];
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
_read(size) {
|
||||
if (this.bodyReadable) {
|
||||
return this.bodyReadable._read(size);
|
||||
} else {
|
||||
this.emit('end');
|
||||
this.emit('close');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* The `connection` property is just an alias for the `socket` property.
|
||||
*
|
||||
* @deprecated — since v13.0.0 - Use socket instead.
|
||||
*/ get connection() {
|
||||
return this.socket;
|
||||
}
|
||||
// The following methods are not implemented as they are not used in the
|
||||
// Next.js codebase.
|
||||
get aborted() {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
get complete() {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
get trailers() {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
get trailersDistinct() {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
get rawTrailers() {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
get rawHeaders() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
setTimeout() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
||||
class MockedResponse extends _stream.default.Writable {
|
||||
constructor(res = {}){
|
||||
super(), this.statusMessage = '', this.finished = false, this.headersSent = false, /**
|
||||
* A list of buffers that have been written to the response.
|
||||
*
|
||||
* @internal - used internally by Next.js
|
||||
*/ this.buffers = [];
|
||||
this.statusCode = res.statusCode ?? 200;
|
||||
this.socket = res.socket ?? null;
|
||||
this.headers = res.headers ? (0, _utils.fromNodeOutgoingHttpHeaders)(res.headers) : new Headers();
|
||||
this.headPromise = new Promise((resolve)=>{
|
||||
this.headPromiseResolve = resolve;
|
||||
});
|
||||
// Attach listeners for the `finish`, `end`, and `error` events to the
|
||||
// `MockedResponse` instance.
|
||||
this.hasStreamed = new Promise((resolve, reject)=>{
|
||||
this.on('finish', ()=>resolve(true));
|
||||
this.on('end', ()=>resolve(true));
|
||||
this.on('error', (err)=>reject(err));
|
||||
}).then((val)=>{
|
||||
this.headPromiseResolve == null ? void 0 : this.headPromiseResolve.call(this);
|
||||
return val;
|
||||
});
|
||||
if (res.resWriter) {
|
||||
this.resWriter = res.resWriter;
|
||||
}
|
||||
}
|
||||
appendHeader(name, value) {
|
||||
const values = Array.isArray(value) ? value : [
|
||||
value
|
||||
];
|
||||
for (const v of values){
|
||||
this.headers.append(name, v);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Returns true if the response has been sent, false otherwise.
|
||||
*
|
||||
* @internal - used internally by Next.js
|
||||
*/ get isSent() {
|
||||
return this.finished || this.headersSent;
|
||||
}
|
||||
/**
|
||||
* The `connection` property is just an alias for the `socket` property.
|
||||
*
|
||||
* @deprecated — since v13.0.0 - Use socket instead.
|
||||
*/ get connection() {
|
||||
return this.socket;
|
||||
}
|
||||
write(chunk) {
|
||||
if (this.resWriter) {
|
||||
return this.resWriter(chunk);
|
||||
}
|
||||
this.buffers.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
return true;
|
||||
}
|
||||
end() {
|
||||
this.finished = true;
|
||||
return super.end(...arguments);
|
||||
}
|
||||
/**
|
||||
* This method is a no-op because the `MockedResponse` instance is not
|
||||
* actually connected to a socket. This method is not specified on the
|
||||
* interface type for `ServerResponse` but is called by Node.js.
|
||||
*
|
||||
* @see https://github.com/nodejs/node/pull/7949
|
||||
*/ _implicitHeader() {}
|
||||
_write(chunk, _encoding, callback) {
|
||||
this.write(chunk);
|
||||
// According to Node.js documentation, the callback MUST be invoked to
|
||||
// signal that the write completed successfully. If this callback is not
|
||||
// invoked, the 'finish' event will not be emitted.
|
||||
//
|
||||
// https://nodejs.org/docs/latest-v16.x/api/stream.html#writable_writechunk-encoding-callback
|
||||
callback();
|
||||
}
|
||||
writeHead(statusCode, statusMessage, headers) {
|
||||
if (!headers && typeof statusMessage !== 'string') {
|
||||
headers = statusMessage;
|
||||
} else if (typeof statusMessage === 'string' && statusMessage.length > 0) {
|
||||
this.statusMessage = statusMessage;
|
||||
}
|
||||
if (headers) {
|
||||
// When headers have been set with response.setHeader(), they will be
|
||||
// merged with any headers passed to response.writeHead(), with the
|
||||
// headers passed to response.writeHead() given precedence.
|
||||
//
|
||||
// https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers
|
||||
//
|
||||
// For this reason, we need to only call `set` to ensure that this will
|
||||
// overwrite any existing headers.
|
||||
if (Array.isArray(headers)) {
|
||||
// headers may be an Array where the keys and values are in the same list.
|
||||
// It is not a list of tuples. So, the even-numbered offsets are key
|
||||
// values, and the odd-numbered offsets are the associated values. The
|
||||
// array is in the same format as request.rawHeaders.
|
||||
for(let i = 0; i < headers.length; i += 2){
|
||||
// The header key is always a string according to the spec.
|
||||
this.setHeader(headers[i], headers[i + 1]);
|
||||
}
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(headers)){
|
||||
// Skip undefined values
|
||||
if (typeof value === 'undefined') continue;
|
||||
this.setHeader(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.statusCode = statusCode;
|
||||
this.headersSent = true;
|
||||
this.headPromiseResolve == null ? void 0 : this.headPromiseResolve.call(this);
|
||||
return this;
|
||||
}
|
||||
hasHeader(name) {
|
||||
return this.headers.has(name);
|
||||
}
|
||||
getHeader(name) {
|
||||
return this.headers.get(name) ?? undefined;
|
||||
}
|
||||
getHeaders() {
|
||||
return (0, _utils.toNodeOutgoingHttpHeaders)(this.headers);
|
||||
}
|
||||
getHeaderNames() {
|
||||
return Array.from(this.headers.keys());
|
||||
}
|
||||
setHeader(name, value) {
|
||||
if (Array.isArray(value)) {
|
||||
// Because `set` here should override any existing values, we need to
|
||||
// delete the existing values before setting the new ones via `append`.
|
||||
this.headers.delete(name);
|
||||
for (const v of value){
|
||||
this.headers.append(name, v);
|
||||
}
|
||||
} else if (typeof value === 'number') {
|
||||
this.headers.set(name, value.toString());
|
||||
} else {
|
||||
this.headers.set(name, value);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
removeHeader(name) {
|
||||
this.headers.delete(name);
|
||||
}
|
||||
flushHeaders() {
|
||||
// This is a no-op because we don't actually have a socket to flush the
|
||||
// headers to.
|
||||
}
|
||||
// The following methods are not implemented as they are not used in the
|
||||
// Next.js codebase.
|
||||
get strictContentLength() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
writeEarlyHints() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
get req() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
assignSocket() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
detachSocket() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
writeContinue() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
writeProcessing() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
get upgrading() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
get chunkedEncoding() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
get shouldKeepAlive() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
get useChunkedEncodingByDefault() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
get sendDate() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
setTimeout() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
addTrailers() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
setHeaders() {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
||||
function createRequestResponseMocks({ url, headers = {}, method = 'GET', bodyReadable, resWriter, socket = null }) {
|
||||
return {
|
||||
req: new MockedRequest({
|
||||
url,
|
||||
headers,
|
||||
method,
|
||||
socket,
|
||||
readable: bodyReadable
|
||||
}),
|
||||
res: new MockedResponse({
|
||||
socket,
|
||||
resWriter
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
//# sourceMappingURL=mock-request.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* Loads a given module for a given ID.
|
||||
*/
|
||||
export interface ModuleLoader {
|
||||
load<M = any>(id: string): Promise<M>;
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Loads a given module for a given ID.
|
||||
*/ "use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
|
||||
//# sourceMappingURL=module-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/module-loader/module-loader.ts"],"sourcesContent":["/**\n * Loads a given module for a given ID.\n */\nexport interface ModuleLoader {\n load<M = any>(id: string): Promise<M>\n}\n"],"names":[],"mappings":"AAAA;;CAEC"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import type { ModuleLoader } from './module-loader';
|
||||
/**
|
||||
* Loads a module using `await require(id)`.
|
||||
*/
|
||||
export declare class NodeModuleLoader implements ModuleLoader {
|
||||
load<M>(id: string): Promise<M>;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "NodeModuleLoader", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return NodeModuleLoader;
|
||||
}
|
||||
});
|
||||
class NodeModuleLoader {
|
||||
async load(id) {
|
||||
if (process.env.NEXT_RUNTIME !== 'edge') {
|
||||
// Need to `await` to cover the case that route is marked ESM modules by ESM escalation.
|
||||
return await (process.env.NEXT_MINIMAL ? __non_webpack_require__(id) : require(id));
|
||||
}
|
||||
throw new Error('NodeModuleLoader is not supported in edge runtime.');
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=node-module-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/module-loader/node-module-loader.ts"],"sourcesContent":["import type { ModuleLoader } from './module-loader'\n\n/**\n * Loads a module using `await require(id)`.\n */\nexport class NodeModuleLoader implements ModuleLoader {\n public async load<M>(id: string): Promise<M> {\n if (process.env.NEXT_RUNTIME !== 'edge') {\n // Need to `await` to cover the case that route is marked ESM modules by ESM escalation.\n return await (process.env.NEXT_MINIMAL\n ? // @ts-ignore\n __non_webpack_require__(id)\n : require(id))\n }\n\n throw new Error('NodeModuleLoader is not supported in edge runtime.')\n }\n}\n"],"names":["NodeModuleLoader","load","id","process","env","NEXT_RUNTIME","NEXT_MINIMAL","__non_webpack_require__","require","Error"],"mappings":";;;;+BAKaA;;;eAAAA;;;AAAN,MAAMA;IACX,MAAaC,KAAQC,EAAU,EAAc;QAC3C,IAAIC,QAAQC,GAAG,CAACC,YAAY,KAAK,QAAQ;YACvC,wFAAwF;YACxF,OAAO,MAAOF,CAAAA,QAAQC,GAAG,CAACE,YAAY,GAElCC,wBAAwBL,MACxBM,QAAQN,GAAE;QAChB;QAEA,MAAM,IAAIO,MAAM;IAClB;AACF"}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import type { RouteModule } from '../../route-modules/route-module';
|
||||
import type { ModuleLoader } from './module-loader';
|
||||
export interface AppLoaderModule<M extends RouteModule = RouteModule> {
|
||||
routeModule: M;
|
||||
}
|
||||
export declare class RouteModuleLoader {
|
||||
static load<M extends RouteModule>(id: string, loader?: ModuleLoader): Promise<M>;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "RouteModuleLoader", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return RouteModuleLoader;
|
||||
}
|
||||
});
|
||||
const _nodemoduleloader = require("./node-module-loader");
|
||||
class RouteModuleLoader {
|
||||
static async load(id, loader = new _nodemoduleloader.NodeModuleLoader()) {
|
||||
const module = await loader.load(id);
|
||||
if ('routeModule' in module) {
|
||||
return module.routeModule;
|
||||
}
|
||||
throw new Error(`Module "${id}" does not export a routeModule.`);
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=route-module-loader.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../../src/server/lib/module-loader/route-module-loader.ts"],"sourcesContent":["import type { RouteModule } from '../../route-modules/route-module'\nimport type { ModuleLoader } from './module-loader'\n\nimport { NodeModuleLoader } from './node-module-loader'\n\nexport interface AppLoaderModule<M extends RouteModule = RouteModule> {\n routeModule: M\n}\n\nexport class RouteModuleLoader {\n static async load<M extends RouteModule>(\n id: string,\n loader: ModuleLoader = new NodeModuleLoader()\n ): Promise<M> {\n const module: AppLoaderModule<M> = await loader.load(id)\n if ('routeModule' in module) {\n return module.routeModule\n }\n\n throw new Error(`Module \"${id}\" does not export a routeModule.`)\n }\n}\n"],"names":["RouteModuleLoader","load","id","loader","NodeModuleLoader","module","routeModule","Error"],"mappings":";;;;+BASaA;;;eAAAA;;;kCANoB;AAM1B,MAAMA;IACX,aAAaC,KACXC,EAAU,EACVC,SAAuB,IAAIC,kCAAgB,EAAE,EACjC;QACZ,MAAMC,SAA6B,MAAMF,OAAOF,IAAI,CAACC;QACrD,IAAI,iBAAiBG,QAAQ;YAC3B,OAAOA,OAAOC,WAAW;QAC3B;QAEA,MAAM,IAAIC,MAAM,CAAC,QAAQ,EAAEL,GAAG,gCAAgC,CAAC;IACjE;AACF"}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
import type { CacheFs } from '../../shared/lib/utils';
|
||||
export declare const nodeFs: CacheFs;
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
Object.defineProperty(exports, "nodeFs", {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return nodeFs;
|
||||
}
|
||||
});
|
||||
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
|
||||
function _interop_require_default(obj) {
|
||||
return obj && obj.__esModule ? obj : {
|
||||
default: obj
|
||||
};
|
||||
}
|
||||
const nodeFs = {
|
||||
existsSync: _fs.default.existsSync,
|
||||
readFile: _fs.default.promises.readFile,
|
||||
readFileSync: _fs.default.readFileSync,
|
||||
writeFile: (f, d)=>_fs.default.promises.writeFile(f, d),
|
||||
mkdir: (dir)=>_fs.default.promises.mkdir(dir, {
|
||||
recursive: true
|
||||
}),
|
||||
stat: (f)=>_fs.default.promises.stat(f)
|
||||
};
|
||||
|
||||
//# sourceMappingURL=node-fs-methods.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/server/lib/node-fs-methods.ts"],"sourcesContent":["import type { CacheFs } from '../../shared/lib/utils'\n\nimport fs from 'fs'\n\nexport const nodeFs: CacheFs = {\n existsSync: fs.existsSync,\n readFile: fs.promises.readFile,\n readFileSync: fs.readFileSync,\n writeFile: (f, d) => fs.promises.writeFile(f, d),\n mkdir: (dir) => fs.promises.mkdir(dir, { recursive: true }),\n stat: (f) => fs.promises.stat(f),\n}\n"],"names":["nodeFs","existsSync","fs","readFile","promises","readFileSync","writeFile","f","d","mkdir","dir","recursive","stat"],"mappings":";;;;+BAIaA;;;eAAAA;;;2DAFE;;;;;;AAER,MAAMA,SAAkB;IAC7BC,YAAYC,WAAE,CAACD,UAAU;IACzBE,UAAUD,WAAE,CAACE,QAAQ,CAACD,QAAQ;IAC9BE,cAAcH,WAAE,CAACG,YAAY;IAC7BC,WAAW,CAACC,GAAGC,IAAMN,WAAE,CAACE,QAAQ,CAACE,SAAS,CAACC,GAAGC;IAC9CC,OAAO,CAACC,MAAQR,WAAE,CAACE,QAAQ,CAACK,KAAK,CAACC,KAAK;YAAEC,WAAW;QAAK;IACzDC,MAAM,CAACL,IAAML,WAAE,CAACE,QAAQ,CAACQ,IAAI,CAACL;AAChC"}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import type { WorkAsyncStorage } from '../app-render/work-async-storage.external';
|
||||
import type { WorkUnitAsyncStorage } from '../app-render/work-unit-async-storage.external';
|
||||
type Fetcher = typeof fetch;
|
||||
type PatchedFetcher = Fetcher & {
|
||||
readonly __nextPatched: true;
|
||||
readonly __nextGetStaticStore: () => WorkAsyncStorage;
|
||||
readonly _nextOriginalFetch: Fetcher;
|
||||
};
|
||||
export declare const NEXT_PATCH_SYMBOL: unique symbol;
|
||||
export declare function validateRevalidate(revalidateVal: unknown, route: string): undefined | number;
|
||||
export declare function validateTags(tags: any[], description: string): string[];
|
||||
interface PatchableModule {
|
||||
workAsyncStorage: WorkAsyncStorage;
|
||||
workUnitAsyncStorage: WorkUnitAsyncStorage;
|
||||
}
|
||||
export declare function createPatchedFetcher(originFetch: Fetcher, { workAsyncStorage, workUnitAsyncStorage }: PatchableModule): PatchedFetcher;
|
||||
export declare function patchFetch(options: PatchableModule): void;
|
||||
export {};
|
||||
+714
@@ -0,0 +1,714 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", {
|
||||
value: true
|
||||
});
|
||||
0 && (module.exports = {
|
||||
NEXT_PATCH_SYMBOL: null,
|
||||
createPatchedFetcher: null,
|
||||
patchFetch: null,
|
||||
validateRevalidate: null,
|
||||
validateTags: null
|
||||
});
|
||||
function _export(target, all) {
|
||||
for(var name in all)Object.defineProperty(target, name, {
|
||||
enumerable: true,
|
||||
get: all[name]
|
||||
});
|
||||
}
|
||||
_export(exports, {
|
||||
NEXT_PATCH_SYMBOL: function() {
|
||||
return NEXT_PATCH_SYMBOL;
|
||||
},
|
||||
createPatchedFetcher: function() {
|
||||
return createPatchedFetcher;
|
||||
},
|
||||
patchFetch: function() {
|
||||
return patchFetch;
|
||||
},
|
||||
validateRevalidate: function() {
|
||||
return validateRevalidate;
|
||||
},
|
||||
validateTags: function() {
|
||||
return validateTags;
|
||||
}
|
||||
});
|
||||
const _constants = require("./trace/constants");
|
||||
const _tracer = require("./trace/tracer");
|
||||
const _constants1 = require("../../lib/constants");
|
||||
const _dynamicrendering = require("../app-render/dynamic-rendering");
|
||||
const _dynamicrenderingutils = require("../dynamic-rendering-utils");
|
||||
const _dedupefetch = require("./dedupe-fetch");
|
||||
const _responsecache = require("../response-cache");
|
||||
const _scheduler = require("../../lib/scheduler");
|
||||
const _cloneresponse = require("./clone-response");
|
||||
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge';
|
||||
const NEXT_PATCH_SYMBOL = Symbol.for('next-patch');
|
||||
function isFetchPatched() {
|
||||
return globalThis[NEXT_PATCH_SYMBOL] === true;
|
||||
}
|
||||
function validateRevalidate(revalidateVal, route) {
|
||||
try {
|
||||
let normalizedRevalidate = undefined;
|
||||
if (revalidateVal === false) {
|
||||
normalizedRevalidate = _constants1.INFINITE_CACHE;
|
||||
} else if (typeof revalidateVal === 'number' && !isNaN(revalidateVal) && revalidateVal > -1) {
|
||||
normalizedRevalidate = revalidateVal;
|
||||
} else if (typeof revalidateVal !== 'undefined') {
|
||||
throw new Error(`Invalid revalidate value "${revalidateVal}" on "${route}", must be a non-negative number or false`);
|
||||
}
|
||||
return normalizedRevalidate;
|
||||
} catch (err) {
|
||||
// handle client component error from attempting to check revalidate value
|
||||
if (err instanceof Error && err.message.includes('Invalid revalidate')) {
|
||||
throw err;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
function validateTags(tags, description) {
|
||||
const validTags = [];
|
||||
const invalidTags = [];
|
||||
for(let i = 0; i < tags.length; i++){
|
||||
const tag = tags[i];
|
||||
if (typeof tag !== 'string') {
|
||||
invalidTags.push({
|
||||
tag,
|
||||
reason: 'invalid type, must be a string'
|
||||
});
|
||||
} else if (tag.length > _constants1.NEXT_CACHE_TAG_MAX_LENGTH) {
|
||||
invalidTags.push({
|
||||
tag,
|
||||
reason: `exceeded max length of ${_constants1.NEXT_CACHE_TAG_MAX_LENGTH}`
|
||||
});
|
||||
} else {
|
||||
validTags.push(tag);
|
||||
}
|
||||
if (validTags.length > _constants1.NEXT_CACHE_TAG_MAX_ITEMS) {
|
||||
console.warn(`Warning: exceeded max tag count for ${description}, dropped tags:`, tags.slice(i).join(', '));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (invalidTags.length > 0) {
|
||||
console.warn(`Warning: invalid tags passed to ${description}: `);
|
||||
for (const { tag, reason } of invalidTags){
|
||||
console.log(`tag: "${tag}" ${reason}`);
|
||||
}
|
||||
}
|
||||
return validTags;
|
||||
}
|
||||
function trackFetchMetric(workStore, ctx) {
|
||||
var _workStore_requestEndedState;
|
||||
// If the static generation store is not available, we can't track the fetch
|
||||
if (!workStore) return;
|
||||
if ((_workStore_requestEndedState = workStore.requestEndedState) == null ? void 0 : _workStore_requestEndedState.ended) return;
|
||||
const isDebugBuild = (!!process.env.NEXT_DEBUG_BUILD || process.env.NEXT_SSG_FETCH_METRICS === '1') && workStore.isStaticGeneration;
|
||||
const isDevelopment = process.env.NODE_ENV === 'development';
|
||||
if (// The only time we want to track fetch metrics outside of development is when
|
||||
// we are performing a static generation & we are in debug mode.
|
||||
!isDebugBuild && !isDevelopment) {
|
||||
return;
|
||||
}
|
||||
workStore.fetchMetrics ??= [];
|
||||
workStore.fetchMetrics.push({
|
||||
...ctx,
|
||||
end: performance.timeOrigin + performance.now(),
|
||||
idx: workStore.nextFetchId || 0
|
||||
});
|
||||
}
|
||||
function createPatchedFetcher(originFetch, { workAsyncStorage, workUnitAsyncStorage }) {
|
||||
// Create the patched fetch function. We don't set the type here, as it's
|
||||
// verified as the return value of this function.
|
||||
const patched = async (input, init)=>{
|
||||
var _init_method, _init_next;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(input instanceof Request ? input.url : input);
|
||||
url.username = '';
|
||||
url.password = '';
|
||||
} catch {
|
||||
// Error caused by malformed URL should be handled by native fetch
|
||||
url = undefined;
|
||||
}
|
||||
const fetchUrl = (url == null ? void 0 : url.href) ?? '';
|
||||
const method = (init == null ? void 0 : (_init_method = init.method) == null ? void 0 : _init_method.toUpperCase()) || 'GET';
|
||||
// Do create a new span trace for internal fetches in the
|
||||
// non-verbose mode.
|
||||
const isInternal = (init == null ? void 0 : (_init_next = init.next) == null ? void 0 : _init_next.internal) === true;
|
||||
const hideSpan = process.env.NEXT_OTEL_FETCH_DISABLED === '1';
|
||||
// We don't track fetch metrics for internal fetches
|
||||
// so it's not critical that we have a start time, as it won't be recorded.
|
||||
// This is to workaround a flaky issue where performance APIs might
|
||||
// not be available and will require follow-up investigation.
|
||||
const fetchStart = isInternal ? undefined : performance.timeOrigin + performance.now();
|
||||
const workStore = workAsyncStorage.getStore();
|
||||
const workUnitStore = workUnitAsyncStorage.getStore();
|
||||
// During static generation we track cache reads so we can reason about when they fill
|
||||
let cacheSignal = workUnitStore && workUnitStore.type === 'prerender' ? workUnitStore.cacheSignal : null;
|
||||
if (cacheSignal) {
|
||||
cacheSignal.beginRead();
|
||||
}
|
||||
const result = (0, _tracer.getTracer)().trace(isInternal ? _constants.NextNodeServerSpan.internalFetch : _constants.AppRenderSpan.fetch, {
|
||||
hideSpan,
|
||||
kind: _tracer.SpanKind.CLIENT,
|
||||
spanName: [
|
||||
'fetch',
|
||||
method,
|
||||
fetchUrl
|
||||
].filter(Boolean).join(' '),
|
||||
attributes: {
|
||||
'http.url': fetchUrl,
|
||||
'http.method': method,
|
||||
'net.peer.name': url == null ? void 0 : url.hostname,
|
||||
'net.peer.port': (url == null ? void 0 : url.port) || undefined
|
||||
}
|
||||
}, async ()=>{
|
||||
var _getRequestMeta;
|
||||
// If this is an internal fetch, we should not do any special treatment.
|
||||
if (isInternal) {
|
||||
return originFetch(input, init);
|
||||
}
|
||||
// If the workStore is not available, we can't do any
|
||||
// special treatment of fetch, therefore fallback to the original
|
||||
// fetch implementation.
|
||||
if (!workStore) {
|
||||
return originFetch(input, init);
|
||||
}
|
||||
// We should also fallback to the original fetch implementation if we
|
||||
// are in draft mode, it does not constitute a static generation.
|
||||
if (workStore.isDraftMode) {
|
||||
return originFetch(input, init);
|
||||
}
|
||||
const isRequestInput = input && typeof input === 'object' && typeof input.method === 'string';
|
||||
const getRequestMeta = (field)=>{
|
||||
// If request input is present but init is not, retrieve from input first.
|
||||
const value = init == null ? void 0 : init[field];
|
||||
return value || (isRequestInput ? input[field] : null);
|
||||
};
|
||||
let finalRevalidate = undefined;
|
||||
const getNextField = (field)=>{
|
||||
var _init_next, _init_next1, _input_next;
|
||||
return typeof (init == null ? void 0 : (_init_next = init.next) == null ? void 0 : _init_next[field]) !== 'undefined' ? init == null ? void 0 : (_init_next1 = init.next) == null ? void 0 : _init_next1[field] : isRequestInput ? (_input_next = input.next) == null ? void 0 : _input_next[field] : undefined;
|
||||
};
|
||||
// RequestInit doesn't keep extra fields e.g. next so it's
|
||||
// only available if init is used separate
|
||||
let currentFetchRevalidate = getNextField('revalidate');
|
||||
const tags = validateTags(getNextField('tags') || [], `fetch ${input.toString()}`);
|
||||
const revalidateStore = workUnitStore && (workUnitStore.type === 'cache' || workUnitStore.type === 'prerender' || workUnitStore.type === 'prerender-ppr' || workUnitStore.type === 'prerender-legacy') ? workUnitStore : undefined;
|
||||
if (revalidateStore) {
|
||||
if (Array.isArray(tags)) {
|
||||
// Collect tags onto parent caches or parent prerenders.
|
||||
const collectedTags = revalidateStore.tags ?? (revalidateStore.tags = []);
|
||||
for (const tag of tags){
|
||||
if (!collectedTags.includes(tag)) {
|
||||
collectedTags.push(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const implicitTags = !workUnitStore || workUnitStore.type === 'unstable-cache' ? [] : workUnitStore.implicitTags;
|
||||
// Inside unstable-cache we treat it the same as force-no-store on the
|
||||
// page.
|
||||
const pageFetchCacheMode = workUnitStore && workUnitStore.type === 'unstable-cache' ? 'force-no-store' : workStore.fetchCache;
|
||||
const isUsingNoStore = !!workStore.isUnstableNoStore;
|
||||
let currentFetchCacheConfig = getRequestMeta('cache');
|
||||
let cacheReason = '';
|
||||
let cacheWarning;
|
||||
if (typeof currentFetchCacheConfig === 'string' && typeof currentFetchRevalidate !== 'undefined') {
|
||||
// If the revalidate value conflicts with the cache value, we should warn the user and unset the conflicting values.
|
||||
const isConflictingRevalidate = // revalidate: 0 and cache: force-cache
|
||||
currentFetchCacheConfig === 'force-cache' && currentFetchRevalidate === 0 || // revalidate: >0 or revalidate: false and cache: no-store
|
||||
currentFetchCacheConfig === 'no-store' && (currentFetchRevalidate > 0 || currentFetchRevalidate === false);
|
||||
if (isConflictingRevalidate) {
|
||||
cacheWarning = `Specified "cache: ${currentFetchCacheConfig}" and "revalidate: ${currentFetchRevalidate}", only one should be specified.`;
|
||||
currentFetchCacheConfig = undefined;
|
||||
currentFetchRevalidate = undefined;
|
||||
}
|
||||
}
|
||||
const hasExplicitFetchCacheOptOut = // fetch config itself signals not to cache
|
||||
currentFetchCacheConfig === 'no-cache' || currentFetchCacheConfig === 'no-store' || // the fetch isn't explicitly caching and the segment level cache config signals not to cache
|
||||
// note: `pageFetchCacheMode` is also set by being in an unstable_cache context.
|
||||
pageFetchCacheMode === 'force-no-store' || pageFetchCacheMode === 'only-no-store';
|
||||
// If no explicit fetch cache mode is set, but dynamic = `force-dynamic` is set,
|
||||
// we shouldn't consider caching the fetch. This is because the `dynamic` cache
|
||||
// is considered a "top-level" cache mode, whereas something like `fetchCache` is more
|
||||
// fine-grained. Top-level modes are responsible for setting reasonable defaults for the
|
||||
// other configurations.
|
||||
const noFetchConfigAndForceDynamic = !pageFetchCacheMode && !currentFetchCacheConfig && !currentFetchRevalidate && workStore.forceDynamic;
|
||||
if (// force-cache was specified without a revalidate value. We set the revalidate value to false
|
||||
// which will signal the cache to not revalidate
|
||||
currentFetchCacheConfig === 'force-cache' && typeof currentFetchRevalidate === 'undefined') {
|
||||
currentFetchRevalidate = false;
|
||||
} else if (// if we are inside of "use cache"/"unstable_cache"
|
||||
// we shouldn't set the revalidate to 0 as it's overridden
|
||||
// by the cache context
|
||||
(workUnitStore == null ? void 0 : workUnitStore.type) !== 'cache' && (hasExplicitFetchCacheOptOut || noFetchConfigAndForceDynamic)) {
|
||||
currentFetchRevalidate = 0;
|
||||
}
|
||||
if (currentFetchCacheConfig === 'no-cache' || currentFetchCacheConfig === 'no-store') {
|
||||
cacheReason = `cache: ${currentFetchCacheConfig}`;
|
||||
}
|
||||
finalRevalidate = validateRevalidate(currentFetchRevalidate, workStore.route);
|
||||
const _headers = getRequestMeta('headers');
|
||||
const initHeaders = typeof (_headers == null ? void 0 : _headers.get) === 'function' ? _headers : new Headers(_headers || {});
|
||||
const hasUnCacheableHeader = initHeaders.get('authorization') || initHeaders.get('cookie');
|
||||
const isUnCacheableMethod = ![
|
||||
'get',
|
||||
'head'
|
||||
].includes(((_getRequestMeta = getRequestMeta('method')) == null ? void 0 : _getRequestMeta.toLowerCase()) || 'get');
|
||||
/**
|
||||
* We automatically disable fetch caching under the following conditions:
|
||||
* - Fetch cache configs are not set. Specifically:
|
||||
* - A page fetch cache mode is not set (export const fetchCache=...)
|
||||
* - A fetch cache mode is not set in the fetch call (fetch(url, { cache: ... }))
|
||||
* or the fetch cache mode is set to 'default'
|
||||
* - A fetch revalidate value is not set in the fetch call (fetch(url, { revalidate: ... }))
|
||||
* - OR the fetch comes after a configuration that triggered dynamic rendering (e.g., reading cookies())
|
||||
* and the fetch was considered uncacheable (e.g., POST method or has authorization headers)
|
||||
*/ const hasNoExplicitCacheConfig = // eslint-disable-next-line eqeqeq
|
||||
pageFetchCacheMode == undefined && // eslint-disable-next-line eqeqeq
|
||||
(currentFetchCacheConfig == undefined || // when considering whether to opt into the default "no-cache" fetch semantics,
|
||||
// a "default" cache config should be treated the same as no cache config
|
||||
currentFetchCacheConfig === 'default') && // eslint-disable-next-line eqeqeq
|
||||
currentFetchRevalidate == undefined;
|
||||
const autoNoCache = // this condition is hit for null/undefined
|
||||
// eslint-disable-next-line eqeqeq
|
||||
hasNoExplicitCacheConfig && // we disable automatic no caching behavior during build time SSG so that we can still
|
||||
// leverage the fetch cache between SSG workers
|
||||
!workStore.isPrerendering || (hasUnCacheableHeader || isUnCacheableMethod) && revalidateStore && revalidateStore.revalidate === 0;
|
||||
if (hasNoExplicitCacheConfig && workUnitStore !== undefined && workUnitStore.type === 'prerender') {
|
||||
// If we have no cache config, and we're in Dynamic I/O prerendering, it'll be a dynamic call.
|
||||
// We don't have to issue that dynamic call.
|
||||
if (cacheSignal) {
|
||||
cacheSignal.endRead();
|
||||
cacheSignal = null;
|
||||
}
|
||||
return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, 'fetch()');
|
||||
}
|
||||
switch(pageFetchCacheMode){
|
||||
case 'force-no-store':
|
||||
{
|
||||
cacheReason = 'fetchCache = force-no-store';
|
||||
break;
|
||||
}
|
||||
case 'only-no-store':
|
||||
{
|
||||
if (currentFetchCacheConfig === 'force-cache' || typeof finalRevalidate !== 'undefined' && finalRevalidate > 0) {
|
||||
throw new Error(`cache: 'force-cache' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-no-store'`);
|
||||
}
|
||||
cacheReason = 'fetchCache = only-no-store';
|
||||
break;
|
||||
}
|
||||
case 'only-cache':
|
||||
{
|
||||
if (currentFetchCacheConfig === 'no-store') {
|
||||
throw new Error(`cache: 'no-store' used on fetch for ${fetchUrl} with 'export const fetchCache = 'only-cache'`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'force-cache':
|
||||
{
|
||||
if (typeof currentFetchRevalidate === 'undefined' || currentFetchRevalidate === 0) {
|
||||
cacheReason = 'fetchCache = force-cache';
|
||||
finalRevalidate = _constants1.INFINITE_CACHE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
}
|
||||
if (typeof finalRevalidate === 'undefined') {
|
||||
if (pageFetchCacheMode === 'default-cache' && !isUsingNoStore) {
|
||||
finalRevalidate = _constants1.INFINITE_CACHE;
|
||||
cacheReason = 'fetchCache = default-cache';
|
||||
} else if (pageFetchCacheMode === 'default-no-store') {
|
||||
finalRevalidate = 0;
|
||||
cacheReason = 'fetchCache = default-no-store';
|
||||
} else if (isUsingNoStore) {
|
||||
finalRevalidate = 0;
|
||||
cacheReason = 'noStore call';
|
||||
} else if (autoNoCache) {
|
||||
finalRevalidate = 0;
|
||||
cacheReason = 'auto no cache';
|
||||
} else {
|
||||
// TODO: should we consider this case an invariant?
|
||||
cacheReason = 'auto cache';
|
||||
finalRevalidate = revalidateStore ? revalidateStore.revalidate : _constants1.INFINITE_CACHE;
|
||||
}
|
||||
} else if (!cacheReason) {
|
||||
cacheReason = `revalidate: ${finalRevalidate}`;
|
||||
}
|
||||
if (// when force static is configured we don't bail from
|
||||
// `revalidate: 0` values
|
||||
!(workStore.forceStatic && finalRevalidate === 0) && // we don't consider autoNoCache to switch to dynamic for ISR
|
||||
!autoNoCache && // If the revalidate value isn't currently set or the value is less
|
||||
// than the current revalidate value, we should update the revalidate
|
||||
// value.
|
||||
revalidateStore && finalRevalidate < revalidateStore.revalidate) {
|
||||
// If we were setting the revalidate value to 0, we should try to
|
||||
// postpone instead first.
|
||||
if (finalRevalidate === 0) {
|
||||
if (workUnitStore && workUnitStore.type === 'prerender') {
|
||||
if (cacheSignal) {
|
||||
cacheSignal.endRead();
|
||||
cacheSignal = null;
|
||||
}
|
||||
return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, 'fetch()');
|
||||
} else {
|
||||
(0, _dynamicrendering.markCurrentScopeAsDynamic)(workStore, workUnitStore, `revalidate: 0 fetch ${input} ${workStore.route}`);
|
||||
}
|
||||
}
|
||||
// We only want to set the revalidate store's revalidate time if it
|
||||
// was explicitly set for the fetch call, i.e. currentFetchRevalidate.
|
||||
if (revalidateStore && currentFetchRevalidate === finalRevalidate) {
|
||||
revalidateStore.revalidate = finalRevalidate;
|
||||
}
|
||||
}
|
||||
const isCacheableRevalidate = typeof finalRevalidate === 'number' && finalRevalidate > 0;
|
||||
let cacheKey;
|
||||
const { incrementalCache } = workStore;
|
||||
const requestStore = workUnitStore !== undefined && workUnitStore.type === 'request' ? workUnitStore : undefined;
|
||||
if (incrementalCache && (isCacheableRevalidate || (requestStore == null ? void 0 : requestStore.serverComponentsHmrCache))) {
|
||||
try {
|
||||
cacheKey = await incrementalCache.generateCacheKey(fetchUrl, isRequestInput ? input : init);
|
||||
} catch (err) {
|
||||
console.error(`Failed to generate cache key for`, input);
|
||||
}
|
||||
}
|
||||
const fetchIdx = workStore.nextFetchId ?? 1;
|
||||
workStore.nextFetchId = fetchIdx + 1;
|
||||
let handleUnlock = ()=>Promise.resolve();
|
||||
const doOriginalFetch = async (isStale, cacheReasonOverride)=>{
|
||||
const requestInputFields = [
|
||||
'cache',
|
||||
'credentials',
|
||||
'headers',
|
||||
'integrity',
|
||||
'keepalive',
|
||||
'method',
|
||||
'mode',
|
||||
'redirect',
|
||||
'referrer',
|
||||
'referrerPolicy',
|
||||
'window',
|
||||
'duplex',
|
||||
// don't pass through signal when revalidating
|
||||
...isStale ? [] : [
|
||||
'signal'
|
||||
]
|
||||
];
|
||||
if (isRequestInput) {
|
||||
const reqInput = input;
|
||||
const reqOptions = {
|
||||
body: reqInput._ogBody || reqInput.body
|
||||
};
|
||||
for (const field of requestInputFields){
|
||||
// @ts-expect-error custom fields
|
||||
reqOptions[field] = reqInput[field];
|
||||
}
|
||||
input = new Request(reqInput.url, reqOptions);
|
||||
} else if (init) {
|
||||
const { _ogBody, body, signal, ...otherInput } = init;
|
||||
init = {
|
||||
...otherInput,
|
||||
body: _ogBody || body,
|
||||
signal: isStale ? undefined : signal
|
||||
};
|
||||
}
|
||||
// add metadata to init without editing the original
|
||||
const clonedInit = {
|
||||
...init,
|
||||
next: {
|
||||
...init == null ? void 0 : init.next,
|
||||
fetchType: 'origin',
|
||||
fetchIdx
|
||||
}
|
||||
};
|
||||
return originFetch(input, clonedInit).then(async (res)=>{
|
||||
if (!isStale && fetchStart) {
|
||||
trackFetchMetric(workStore, {
|
||||
start: fetchStart,
|
||||
url: fetchUrl,
|
||||
cacheReason: cacheReasonOverride || cacheReason,
|
||||
cacheStatus: finalRevalidate === 0 || cacheReasonOverride ? 'skip' : 'miss',
|
||||
cacheWarning,
|
||||
status: res.status,
|
||||
method: clonedInit.method || 'GET'
|
||||
});
|
||||
}
|
||||
if (res.status === 200 && incrementalCache && cacheKey && (isCacheableRevalidate || (requestStore == null ? void 0 : requestStore.serverComponentsHmrCache))) {
|
||||
const normalizedRevalidate = finalRevalidate >= _constants1.INFINITE_CACHE ? _constants1.CACHE_ONE_YEAR : finalRevalidate;
|
||||
const externalRevalidate = finalRevalidate >= _constants1.INFINITE_CACHE ? false : finalRevalidate;
|
||||
if (workUnitStore && workUnitStore.type === 'prerender') {
|
||||
// We are prerendering at build time or revalidate time with dynamicIO so we need to
|
||||
// buffer the response so we can guarantee it can be read in a microtask
|
||||
const bodyBuffer = await res.arrayBuffer();
|
||||
const fetchedData = {
|
||||
headers: Object.fromEntries(res.headers.entries()),
|
||||
body: Buffer.from(bodyBuffer).toString('base64'),
|
||||
status: res.status,
|
||||
url: res.url
|
||||
};
|
||||
// We can skip checking the serverComponentsHmrCache because we aren't in
|
||||
// dev mode.
|
||||
await incrementalCache.set(cacheKey, {
|
||||
kind: _responsecache.CachedRouteKind.FETCH,
|
||||
data: fetchedData,
|
||||
revalidate: normalizedRevalidate
|
||||
}, {
|
||||
fetchCache: true,
|
||||
revalidate: externalRevalidate,
|
||||
fetchUrl,
|
||||
fetchIdx,
|
||||
tags
|
||||
});
|
||||
await handleUnlock();
|
||||
// We we return a new Response to the caller.
|
||||
return new Response(bodyBuffer, {
|
||||
headers: res.headers,
|
||||
status: res.status,
|
||||
statusText: res.statusText
|
||||
});
|
||||
} else {
|
||||
// We're cloning the response using this utility because there
|
||||
// exists a bug in the undici library around response cloning.
|
||||
// See the following pull request for more details:
|
||||
// https://github.com/vercel/next.js/pull/73274
|
||||
const [cloned1, cloned2] = (0, _cloneresponse.cloneResponse)(res);
|
||||
// We are dynamically rendering including dev mode. We want to return
|
||||
// the response to the caller as soon as possible because it might stream
|
||||
// over a very long time.
|
||||
cloned1.arrayBuffer().then(async (arrayBuffer)=>{
|
||||
var _requestStore_serverComponentsHmrCache;
|
||||
const bodyBuffer = Buffer.from(arrayBuffer);
|
||||
const fetchedData = {
|
||||
headers: Object.fromEntries(cloned1.headers.entries()),
|
||||
body: bodyBuffer.toString('base64'),
|
||||
status: cloned1.status,
|
||||
url: cloned1.url
|
||||
};
|
||||
requestStore == null ? void 0 : (_requestStore_serverComponentsHmrCache = requestStore.serverComponentsHmrCache) == null ? void 0 : _requestStore_serverComponentsHmrCache.set(cacheKey, fetchedData);
|
||||
if (isCacheableRevalidate) {
|
||||
await incrementalCache.set(cacheKey, {
|
||||
kind: _responsecache.CachedRouteKind.FETCH,
|
||||
data: fetchedData,
|
||||
revalidate: normalizedRevalidate
|
||||
}, {
|
||||
fetchCache: true,
|
||||
revalidate: externalRevalidate,
|
||||
fetchUrl,
|
||||
fetchIdx,
|
||||
tags
|
||||
});
|
||||
}
|
||||
}).catch((error)=>console.warn(`Failed to set fetch cache`, input, error)).finally(handleUnlock);
|
||||
return cloned2;
|
||||
}
|
||||
}
|
||||
// we had response that we determined shouldn't be cached so we return it
|
||||
// and don't cache it. This also needs to unlock the cache lock we acquired.
|
||||
await handleUnlock();
|
||||
return res;
|
||||
});
|
||||
};
|
||||
let cacheReasonOverride;
|
||||
let isForegroundRevalidate = false;
|
||||
let isHmrRefreshCache = false;
|
||||
if (cacheKey && incrementalCache) {
|
||||
let cachedFetchData;
|
||||
if ((requestStore == null ? void 0 : requestStore.isHmrRefresh) && requestStore.serverComponentsHmrCache) {
|
||||
cachedFetchData = requestStore.serverComponentsHmrCache.get(cacheKey);
|
||||
isHmrRefreshCache = true;
|
||||
}
|
||||
if (isCacheableRevalidate && !cachedFetchData) {
|
||||
handleUnlock = await incrementalCache.lock(cacheKey);
|
||||
const entry = workStore.isOnDemandRevalidate ? null : await incrementalCache.get(cacheKey, {
|
||||
kind: _responsecache.IncrementalCacheKind.FETCH,
|
||||
revalidate: finalRevalidate,
|
||||
fetchUrl,
|
||||
fetchIdx,
|
||||
tags,
|
||||
softTags: implicitTags,
|
||||
isFallback: false
|
||||
});
|
||||
if (hasNoExplicitCacheConfig) {
|
||||
// We sometimes use the cache to dedupe fetches that do not specify a cache configuration
|
||||
// In these cases we want to make sure we still exclude them from prerenders if dynamicIO is on
|
||||
// so we introduce an artificial Task boundary here.
|
||||
if (workUnitStore && workUnitStore.type === 'prerender') {
|
||||
await (0, _scheduler.waitAtLeastOneReactRenderTask)();
|
||||
}
|
||||
}
|
||||
if (entry) {
|
||||
await handleUnlock();
|
||||
} else {
|
||||
// in dev, incremental cache response will be null in case the browser adds `cache-control: no-cache` in the request headers
|
||||
cacheReasonOverride = 'cache-control: no-cache (hard refresh)';
|
||||
}
|
||||
if ((entry == null ? void 0 : entry.value) && entry.value.kind === _responsecache.CachedRouteKind.FETCH) {
|
||||
// when stale and is revalidating we wait for fresh data
|
||||
// so the revalidated entry has the updated data
|
||||
if (workStore.isRevalidate && entry.isStale) {
|
||||
isForegroundRevalidate = true;
|
||||
} else {
|
||||
if (entry.isStale) {
|
||||
workStore.pendingRevalidates ??= {};
|
||||
if (!workStore.pendingRevalidates[cacheKey]) {
|
||||
const pendingRevalidate = doOriginalFetch(true).then(async (response)=>({
|
||||
body: await response.arrayBuffer(),
|
||||
headers: response.headers,
|
||||
status: response.status,
|
||||
statusText: response.statusText
|
||||
})).finally(()=>{
|
||||
workStore.pendingRevalidates ??= {};
|
||||
delete workStore.pendingRevalidates[cacheKey || ''];
|
||||
});
|
||||
// Attach the empty catch here so we don't get a "unhandled
|
||||
// promise rejection" warning.
|
||||
pendingRevalidate.catch(console.error);
|
||||
workStore.pendingRevalidates[cacheKey] = pendingRevalidate;
|
||||
}
|
||||
}
|
||||
cachedFetchData = entry.value.data;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cachedFetchData) {
|
||||
if (fetchStart) {
|
||||
trackFetchMetric(workStore, {
|
||||
start: fetchStart,
|
||||
url: fetchUrl,
|
||||
cacheReason,
|
||||
cacheStatus: isHmrRefreshCache ? 'hmr' : 'hit',
|
||||
cacheWarning,
|
||||
status: cachedFetchData.status || 200,
|
||||
method: (init == null ? void 0 : init.method) || 'GET'
|
||||
});
|
||||
}
|
||||
const response = new Response(Buffer.from(cachedFetchData.body, 'base64'), {
|
||||
headers: cachedFetchData.headers,
|
||||
status: cachedFetchData.status
|
||||
});
|
||||
Object.defineProperty(response, 'url', {
|
||||
value: cachedFetchData.url
|
||||
});
|
||||
return response;
|
||||
}
|
||||
}
|
||||
if (workStore.isStaticGeneration && init && typeof init === 'object') {
|
||||
const { cache } = init;
|
||||
// Delete `cache` property as Cloudflare Workers will throw an error
|
||||
if (isEdgeRuntime) delete init.cache;
|
||||
if (cache === 'no-store') {
|
||||
// If enabled, we should bail out of static generation.
|
||||
if (workUnitStore && workUnitStore.type === 'prerender') {
|
||||
if (cacheSignal) {
|
||||
cacheSignal.endRead();
|
||||
cacheSignal = null;
|
||||
}
|
||||
return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, 'fetch()');
|
||||
} else {
|
||||
(0, _dynamicrendering.markCurrentScopeAsDynamic)(workStore, workUnitStore, `no-store fetch ${input} ${workStore.route}`);
|
||||
}
|
||||
}
|
||||
const hasNextConfig = 'next' in init;
|
||||
const { next = {} } = init;
|
||||
if (typeof next.revalidate === 'number' && revalidateStore && next.revalidate < revalidateStore.revalidate) {
|
||||
if (next.revalidate === 0) {
|
||||
// If enabled, we should bail out of static generation.
|
||||
if (workUnitStore && workUnitStore.type === 'prerender') {
|
||||
return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, 'fetch()');
|
||||
} else {
|
||||
(0, _dynamicrendering.markCurrentScopeAsDynamic)(workStore, workUnitStore, `revalidate: 0 fetch ${input} ${workStore.route}`);
|
||||
}
|
||||
}
|
||||
if (!workStore.forceStatic || next.revalidate !== 0) {
|
||||
revalidateStore.revalidate = next.revalidate;
|
||||
}
|
||||
}
|
||||
if (hasNextConfig) delete init.next;
|
||||
}
|
||||
// if we are revalidating the whole page via time or on-demand and
|
||||
// the fetch cache entry is stale we should still de-dupe the
|
||||
// origin hit if it's a cache-able entry
|
||||
if (cacheKey && isForegroundRevalidate) {
|
||||
const pendingRevalidateKey = cacheKey;
|
||||
workStore.pendingRevalidates ??= {};
|
||||
let pendingRevalidate = workStore.pendingRevalidates[pendingRevalidateKey];
|
||||
if (pendingRevalidate) {
|
||||
const revalidatedResult = await pendingRevalidate;
|
||||
return new Response(revalidatedResult.body, {
|
||||
headers: revalidatedResult.headers,
|
||||
status: revalidatedResult.status,
|
||||
statusText: revalidatedResult.statusText
|
||||
});
|
||||
}
|
||||
// We used to just resolve the Response and clone it however for
|
||||
// static generation with dynamicIO we need the response to be able to
|
||||
// be resolved in a microtask and cloning the response will never have
|
||||
// a body that can resolve in a microtask in node (as observed through
|
||||
// experimentation) So instead we await the body and then when it is
|
||||
// available we construct manually cloned Response objects with the
|
||||
// body as an ArrayBuffer. This will be resolvable in a microtask
|
||||
// making it compatible with dynamicIO.
|
||||
const pendingResponse = doOriginalFetch(true, cacheReasonOverride)// We're cloning the response using this utility because there
|
||||
// exists a bug in the undici library around response cloning.
|
||||
// See the following pull request for more details:
|
||||
// https://github.com/vercel/next.js/pull/73274
|
||||
.then(_cloneresponse.cloneResponse);
|
||||
pendingRevalidate = pendingResponse.then(async (responses)=>{
|
||||
const response = responses[0];
|
||||
return {
|
||||
body: await response.arrayBuffer(),
|
||||
headers: response.headers,
|
||||
status: response.status,
|
||||
statusText: response.statusText
|
||||
};
|
||||
}).finally(()=>{
|
||||
var _workStore_pendingRevalidates;
|
||||
// If the pending revalidate is not present in the store, then
|
||||
// we have nothing to delete.
|
||||
if (!((_workStore_pendingRevalidates = workStore.pendingRevalidates) == null ? void 0 : _workStore_pendingRevalidates[pendingRevalidateKey])) {
|
||||
return;
|
||||
}
|
||||
delete workStore.pendingRevalidates[pendingRevalidateKey];
|
||||
});
|
||||
// Attach the empty catch here so we don't get a "unhandled promise
|
||||
// rejection" warning
|
||||
pendingRevalidate.catch(()=>{});
|
||||
workStore.pendingRevalidates[pendingRevalidateKey] = pendingRevalidate;
|
||||
return pendingResponse.then((responses)=>responses[1]);
|
||||
} else {
|
||||
return doOriginalFetch(false, cacheReasonOverride);
|
||||
}
|
||||
});
|
||||
if (cacheSignal) {
|
||||
try {
|
||||
return await result;
|
||||
} finally{
|
||||
if (cacheSignal) {
|
||||
cacheSignal.endRead();
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// Attach the necessary properties to the patched fetch function.
|
||||
// We don't use this to determine if the fetch function has been patched,
|
||||
// but for external consumers to determine if the fetch function has been
|
||||
// patched.
|
||||
patched.__nextPatched = true;
|
||||
patched.__nextGetStaticStore = ()=>workAsyncStorage;
|
||||
patched._nextOriginalFetch = originFetch;
|
||||
globalThis[NEXT_PATCH_SYMBOL] = true;
|
||||
return patched;
|
||||
}
|
||||
function patchFetch(options) {
|
||||
// If we've already patched fetch, we should not patch it again.
|
||||
if (isFetchPatched()) return;
|
||||
// Grab the original fetch function. We'll attach this so we can use it in
|
||||
// the patched fetch function.
|
||||
const original = (0, _dedupefetch.createDedupeFetch)(globalThis.fetch);
|
||||
// Set the global fetch to the patched fetch.
|
||||
globalThis.fetch = createPatchedFetcher(original, options);
|
||||
}
|
||||
|
||||
//# sourceMappingURL=patch-fetch.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import { type NextIncomingMessage } from '../request-meta';
|
||||
type PatchableResponse = {
|
||||
setHeader(key: string, value: string | string[]): PatchableResponse;
|
||||
};
|
||||
/**
|
||||
* Ensure cookies set in middleware are merged and not overridden by API
|
||||
* routes/getServerSideProps.
|
||||
*
|
||||
* @param req Incoming request
|
||||
* @param res Outgoing response
|
||||
*/
|
||||
export declare function patchSetHeaderWithCookieSupport(req: NextIncomingMessage, res: PatchableResponse): void;
|
||||
export {};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user