| self.__BUILD_MANIFEST = { | ||
| "__rewrites": { | ||
| "afterFiles": [], | ||
| "beforeFiles": [], | ||
| "fallback": [] | ||
| }, | ||
| "sortedPages": [ | ||
| "/_app", | ||
| "/_error" | ||
| ] | ||
| };self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB() |
| self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() |
| self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() |
| (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,35718,(__turbopack_context__,module,exports)=>{"use strict";var React=__turbopack_context__.r(41976);function formatProdErrorMessage(code){var url="https://react.dev/errors/"+code;if(1<arguments.length){url+="?args[]="+encodeURIComponent(arguments[1]);for(var i=2;i<arguments.length;i++)url+="&args[]="+encodeURIComponent(arguments[i])}return"Minified React error #"+code+"; visit "+url+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function noop(){}var Internals={d:{f:noop,r:function(){throw Error(formatProdErrorMessage(522))},D:noop,C:noop,L:noop,m:noop,X:noop,S:noop,M:noop},p:0,findDOMNode:null},REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_OPTIMISTIC_KEY=Symbol.for("react.optimistic_key");function createPortal$1(children,containerInfo,implementation){var key=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:REACT_PORTAL_TYPE,key:null==key?null:key===REACT_OPTIMISTIC_KEY?REACT_OPTIMISTIC_KEY:""+key,children:children,containerInfo:containerInfo,implementation:implementation}}var ReactSharedInternals=React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function getCrossOriginStringAs(as,input){return"font"===as?"":"string"==typeof input?"use-credentials"===input?input:"":void 0}exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Internals,exports.createPortal=function(children,container){var key=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!container||1!==container.nodeType&&9!==container.nodeType&&11!==container.nodeType)throw Error(formatProdErrorMessage(299));return createPortal$1(children,container,null,key)},exports.flushSync=function(fn){var previousTransition=ReactSharedInternals.T,previousUpdatePriority=Internals.p;try{if(ReactSharedInternals.T=null,Internals.p=2,fn)return fn()}finally{ReactSharedInternals.T=previousTransition,Internals.p=previousUpdatePriority,Internals.d.f()}},exports.preconnect=function(href,options){"string"==typeof href&&(options=options?"string"==typeof(options=options.crossOrigin)?"use-credentials"===options?options:"":void 0:null,Internals.d.C(href,options))},exports.prefetchDNS=function(href){"string"==typeof href&&Internals.d.D(href)},exports.preinit=function(href,options){if("string"==typeof href&&options&&"string"==typeof options.as){var as=options.as,crossOrigin=getCrossOriginStringAs(as,options.crossOrigin),integrity="string"==typeof options.integrity?options.integrity:void 0,fetchPriority="string"==typeof options.fetchPriority?options.fetchPriority:void 0;"style"===as?Internals.d.S(href,"string"==typeof options.precedence?options.precedence:void 0,{crossOrigin:crossOrigin,integrity:integrity,fetchPriority:fetchPriority}):"script"===as&&Internals.d.X(href,{crossOrigin:crossOrigin,integrity:integrity,fetchPriority:fetchPriority,nonce:"string"==typeof options.nonce?options.nonce:void 0})}},exports.preinitModule=function(href,options){if("string"==typeof href)if("object"==typeof options&&null!==options){if(null==options.as||"script"===options.as){var crossOrigin=getCrossOriginStringAs(options.as,options.crossOrigin);Internals.d.M(href,{crossOrigin:crossOrigin,integrity:"string"==typeof options.integrity?options.integrity:void 0,nonce:"string"==typeof options.nonce?options.nonce:void 0})}}else null==options&&Internals.d.M(href)},exports.preload=function(href,options){if("string"==typeof href&&"object"==typeof options&&null!==options&&"string"==typeof options.as){var as=options.as,crossOrigin=getCrossOriginStringAs(as,options.crossOrigin);Internals.d.L(href,as,{crossOrigin:crossOrigin,integrity:"string"==typeof options.integrity?options.integrity:void 0,nonce:"string"==typeof options.nonce?options.nonce:void 0,type:"string"==typeof options.type?options.type:void 0,fetchPriority:"string"==typeof options.fetchPriority?options.fetchPriority:void 0,referrerPolicy:"string"==typeof options.referrerPolicy?options.referrerPolicy:void 0,imageSrcSet:"string"==typeof options.imageSrcSet?options.imageSrcSet:void 0,imageSizes:"string"==typeof options.imageSizes?options.imageSizes:void 0,media:"string"==typeof options.media?options.media:void 0})}},exports.preloadModule=function(href,options){if("string"==typeof href)if(options){var crossOrigin=getCrossOriginStringAs(options.as,options.crossOrigin);Internals.d.m(href,{as:"string"==typeof options.as&&"script"!==options.as?options.as:void 0,crossOrigin:crossOrigin,integrity:"string"==typeof options.integrity?options.integrity:void 0})}else Internals.d.m(href)},exports.requestFormReset=function(form){Internals.d.r(form)},exports.unstable_batchedUpdates=function(fn,a){return fn(a)},exports.useFormState=function(action,initialState,permalink){return ReactSharedInternals.H.useFormState(action,initialState,permalink)},exports.useFormStatus=function(){return ReactSharedInternals.H.useHostTransitionStatus()},exports.version="19.3.0-canary-3f0b9e61-20260317"},10702,(__turbopack_context__,module,exports)=>{"use strict";function checkDCE(){if("u">typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(err){console.error(err)}}checkDCE(),module.exports=__turbopack_context__.r(35718)},35949,(__turbopack_context__,module,exports)=>{var e={229:function(e){var r,n,u,t=e.exports={};function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}try{r="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){r=defaultSetTimout}try{n="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){n=defaultClearTimeout}function runTimeout(e){if(r===setTimeout)return setTimeout(e,0);if((r===defaultSetTimout||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function runClearTimeout(e){if(n===clearTimeout)return clearTimeout(e);if((n===defaultClearTimeout||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{return n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}var i=[],o=!1,a=-1;function cleanUpNextTick(){o&&u&&(o=!1,u.length?i=u.concat(i):a=-1,i.length&&drainQueue())}function drainQueue(){if(!o){var e=runTimeout(cleanUpNextTick);o=!0;for(var t=i.length;t;){for(u=i,i=[];++a<t;)u&&u[a].run();a=-1,t=i.length}u=null,o=!1,runClearTimeout(e)}}function Item(e,t){this.fun=e,this.array=t}function noop(){}t.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];i.push(new Item(e,t)),1!==i.length||o||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={},t.on=noop,t.addListener=noop,t.once=noop,t.off=noop,t.removeListener=noop,t.removeAllListeners=noop,t.emit=noop,t.prependListener=noop,t.prependOnceListener=noop,t.listeners=function(e){return[]},t.binding=function(e){throw Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(e){throw Error("process.chdir is not supported")},t.umask=function(){return 0}}},t={};function __nccwpck_require__(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}},o=!0;try{e[r](i,i.exports,__nccwpck_require__),o=!1}finally{o&&delete t[r]}return i.exports}__nccwpck_require__.ab="/ROOT/node_modules/.pnpm/next@16.2.3_@babel+core@7.26.10_@opentelemetry+api@1.9.0_@playwright+test@1.61.0_babel-_a0373bce20e7e6e63aa4926485689d89/node_modules/next/dist/compiled/process/",module.exports=__nccwpck_require__(229)},3818,(__turbopack_context__,module,exports)=>{"use strict";var _global_process,_global_process1;module.exports=(null==(_global_process=__turbopack_context__.g.process)?void 0:_global_process.env)&&"object"==typeof(null==(_global_process1=__turbopack_context__.g.process)?void 0:_global_process1.env)?__turbopack_context__.g.process:__turbopack_context__.r(35949)},45948,(__turbopack_context__,module,exports)=>{"use strict";var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element");function jsxProd(type,config,maybeKey){var key=null;if(void 0!==maybeKey&&(key=""+maybeKey),void 0!==config.key&&(key=""+config.key),"key"in config)for(var propName in maybeKey={},config)"key"!==propName&&(maybeKey[propName]=config[propName]);else maybeKey=config;return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:key,ref:void 0!==(config=maybeKey.ref)?config:null,props:maybeKey}}exports.Fragment=Symbol.for("react.fragment"),exports.jsx=jsxProd,exports.jsxs=jsxProd},74018,(__turbopack_context__,module,exports)=>{"use strict";module.exports=__turbopack_context__.r(45948)},4532,(__turbopack_context__,module,exports)=>{"use strict";var __TURBOPACK__imported__module__3818__=__turbopack_context__.i(3818),REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment"),REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode"),REACT_PROFILER_TYPE=Symbol.for("react.profiler"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_SUSPENSE_TYPE=Symbol.for("react.suspense"),REACT_MEMO_TYPE=Symbol.for("react.memo"),REACT_LAZY_TYPE=Symbol.for("react.lazy"),REACT_ACTIVITY_TYPE=Symbol.for("react.activity"),REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition"),MAYBE_ITERATOR_SYMBOL=Symbol.iterator;function getIteratorFn(maybeIterable){return null===maybeIterable||"object"!=typeof maybeIterable?null:"function"==typeof(maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"])?maybeIterable:null}var ReactNoopUpdateQueue={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},assign=Object.assign,emptyObject={};function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}Component.prototype.isReactComponent={},Component.prototype.setState=function(partialState,callback){if("object"!=typeof partialState&&"function"!=typeof partialState&&null!=partialState)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,partialState,callback,"setState")},Component.prototype.forceUpdate=function(callback){this.updater.enqueueForceUpdate(this,callback,"forceUpdate")},ComponentDummy.prototype=Component.prototype;var pureComponentPrototype=PureComponent.prototype=new ComponentDummy;pureComponentPrototype.constructor=PureComponent,assign(pureComponentPrototype,Component.prototype),pureComponentPrototype.isPureReactComponent=!0;var isArrayImpl=Array.isArray;function noop(){}var ReactSharedInternals={H:null,A:null,T:null,S:null},hasOwnProperty=Object.prototype.hasOwnProperty;function ReactElement(type,key,props){var refProp=props.ref;return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:key,ref:void 0!==refProp?refProp:null,props:props}}function cloneAndReplaceKey(oldElement,newKey){return ReactElement(oldElement.type,newKey,oldElement.props)}function isValidElement(object){return"object"==typeof object&&null!==object&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}var userProvidedKeyEscapeRegex=/\/+/g;function getElementKey(element,index){return"object"==typeof element&&null!==element&&null!=element.key?escape(""+element.key):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch("string"==typeof thenable.status?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){"pending"===thenable.status&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){"pending"===thenable.status&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;("undefined"===type||"boolean"===type)&&(children=null);var invokeCallback=!1;if(null===children)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return mapIntoArray((invokeCallback=children._init)(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback)return callback=callback(children),invokeCallback=""===nameSoFar?"."+getElementKey(children,0):nameSoFar,isArrayImpl(callback)?(escapedPrefix="",null!=invokeCallback&&(escapedPrefix=invokeCallback.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):null!=callback&&(isValidElement(callback)&&(callback=cloneAndReplaceKey(callback,escapedPrefix+(null==callback.key||children&&children.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+invokeCallback)),array.push(callback)),1;invokeCallback=0;var nextNamePrefix=""===nameSoFar?".":nameSoFar+":";if(isArrayImpl(children))for(var i=0;i<children.length;i++)type=nextNamePrefix+getElementKey(nameSoFar=children[i],i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if("function"==typeof(i=getIteratorFn(children)))for(children=i.call(children),i=0;!(nameSoFar=children.next()).done;)type=nextNamePrefix+getElementKey(nameSoFar=nameSoFar.value,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if("object"===type){if("function"==typeof children.then)return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw Error("Objects are not valid as a React child (found: "+("[object Object]"===(array=String(children))?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(null==children)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(-1===payload._status){var thenable=(0,payload._result)();thenable.then(function(moduleObject){(0===payload._status||-1===payload._status)&&(payload._status=1,payload._result=moduleObject,void 0===thenable.status&&(thenable.status="fulfilled",thenable.value=moduleObject))},function(error){(0===payload._status||-1===payload._status)&&(payload._status=2,payload._result=error,void 0===thenable.status&&(thenable.status="rejected",thenable.reason=error))}),-1===payload._status&&(payload._status=0,payload._result=thenable)}if(1===payload._status)return payload._result.default;throw payload._result}var reportGlobalError="function"==typeof reportError?reportError:function(error){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var event=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof error&&null!==error&&"string"==typeof error.message?String(error.message):String(error),error:error});if(!window.dispatchEvent(event))return}else if("object"==typeof __TURBOPACK__imported__module__3818__.default&&"function"==typeof __TURBOPACK__imported__module__3818__.default.emit)return void __TURBOPACK__imported__module__3818__.default.emit("uncaughtException",error);console.error(error)};function startTransition(scope){var prevTransition=ReactSharedInternals.T,currentTransition={};currentTransition.types=null!==prevTransition?prevTransition.types:null,ReactSharedInternals.T=currentTransition;try{var returnValue=scope(),onStartTransitionFinish=ReactSharedInternals.S;null!==onStartTransitionFinish&&onStartTransitionFinish(currentTransition,returnValue),"object"==typeof returnValue&&null!==returnValue&&"function"==typeof returnValue.then&&returnValue.then(noop,reportGlobalError)}catch(error){reportGlobalError(error)}finally{null!==prevTransition&&null!==currentTransition.types&&(prevTransition.types=currentTransition.types),ReactSharedInternals.T=prevTransition}}function addTransitionType(type){var transition=ReactSharedInternals.T;if(null!==transition){var transitionTypes=transition.types;null===transitionTypes?transition.types=[type]:-1===transitionTypes.indexOf(type)&&transitionTypes.push(type)}else startTransition(addTransitionType.bind(null,type))}exports.Activity=REACT_ACTIVITY_TYPE,exports.Children={map:mapChildren,forEach:function(children,forEachFunc,forEachContext){mapChildren(children,function(){forEachFunc.apply(this,arguments)},forEachContext)},count:function(children){var n=0;return mapChildren(children,function(){n++}),n},toArray:function(children){return mapChildren(children,function(child){return child})||[]},only:function(children){if(!isValidElement(children))throw Error("React.Children.only expected to receive a single React element child.");return children}},exports.Component=Component,exports.Fragment=REACT_FRAGMENT_TYPE,exports.Profiler=REACT_PROFILER_TYPE,exports.PureComponent=PureComponent,exports.StrictMode=REACT_STRICT_MODE_TYPE,exports.Suspense=REACT_SUSPENSE_TYPE,exports.ViewTransition=REACT_VIEW_TRANSITION_TYPE,exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ReactSharedInternals,exports.__COMPILER_RUNTIME={__proto__:null,c:function(size){return ReactSharedInternals.H.useMemoCache(size)}},exports.addTransitionType=addTransitionType,exports.cache=function(fn){return function(){return fn.apply(null,arguments)}},exports.cacheSignal=function(){return null},exports.cloneElement=function(element,config,children){if(null==element)throw Error("The argument must be a React element, but you passed "+element+".");var props=assign({},element.props),key=element.key;if(null!=config)for(propName in void 0!==config.key&&(key=""+config.key),config)hasOwnProperty.call(config,propName)&&"key"!==propName&&"__self"!==propName&&"__source"!==propName&&("ref"!==propName||void 0!==config.ref)&&(props[propName]=config[propName]);var propName=arguments.length-2;if(1===propName)props.children=children;else if(1<propName){for(var childArray=Array(propName),i=0;i<propName;i++)childArray[i]=arguments[i+2];props.children=childArray}return ReactElement(element.type,key,props)},exports.createContext=function(defaultValue){return(defaultValue={$$typeof:REACT_CONTEXT_TYPE,_currentValue:defaultValue,_currentValue2:defaultValue,_threadCount:0,Provider:null,Consumer:null}).Provider=defaultValue,defaultValue.Consumer={$$typeof:REACT_CONSUMER_TYPE,_context:defaultValue},defaultValue},exports.createElement=function(type,config,children){var propName,props={},key=null;if(null!=config)for(propName in void 0!==config.key&&(key=""+config.key),config)hasOwnProperty.call(config,propName)&&"key"!==propName&&"__self"!==propName&&"__source"!==propName&&(props[propName]=config[propName]);var childrenLength=arguments.length-2;if(1===childrenLength)props.children=children;else if(1<childrenLength){for(var childArray=Array(childrenLength),i=0;i<childrenLength;i++)childArray[i]=arguments[i+2];props.children=childArray}if(type&&type.defaultProps)for(propName in childrenLength=type.defaultProps)void 0===props[propName]&&(props[propName]=childrenLength[propName]);return ReactElement(type,key,props)},exports.createRef=function(){return{current:null}},exports.forwardRef=function(render){return{$$typeof:REACT_FORWARD_REF_TYPE,render:render}},exports.isValidElement=isValidElement,exports.lazy=function(ctor){return{$$typeof:REACT_LAZY_TYPE,_payload:{_status:-1,_result:ctor},_init:lazyInitializer}},exports.memo=function(type,compare){return{$$typeof:REACT_MEMO_TYPE,type:type,compare:void 0===compare?null:compare}},exports.startTransition=startTransition,exports.unstable_useCacheRefresh=function(){return ReactSharedInternals.H.useCacheRefresh()},exports.use=function(usable){return ReactSharedInternals.H.use(usable)},exports.useActionState=function(action,initialState,permalink){return ReactSharedInternals.H.useActionState(action,initialState,permalink)},exports.useCallback=function(callback,deps){return ReactSharedInternals.H.useCallback(callback,deps)},exports.useContext=function(Context){return ReactSharedInternals.H.useContext(Context)},exports.useDebugValue=function(){},exports.useDeferredValue=function(value,initialValue){return ReactSharedInternals.H.useDeferredValue(value,initialValue)},exports.useEffect=function(create,deps){return ReactSharedInternals.H.useEffect(create,deps)},exports.useEffectEvent=function(callback){return ReactSharedInternals.H.useEffectEvent(callback)},exports.useId=function(){return ReactSharedInternals.H.useId()},exports.useImperativeHandle=function(ref,create,deps){return ReactSharedInternals.H.useImperativeHandle(ref,create,deps)},exports.useInsertionEffect=function(create,deps){return ReactSharedInternals.H.useInsertionEffect(create,deps)},exports.useLayoutEffect=function(create,deps){return ReactSharedInternals.H.useLayoutEffect(create,deps)},exports.useMemo=function(create,deps){return ReactSharedInternals.H.useMemo(create,deps)},exports.useOptimistic=function(passthrough,reducer){return ReactSharedInternals.H.useOptimistic(passthrough,reducer)},exports.useReducer=function(reducer,initialArg,init){return ReactSharedInternals.H.useReducer(reducer,initialArg,init)},exports.useRef=function(initialValue){return ReactSharedInternals.H.useRef(initialValue)},exports.useState=function(initialState){return ReactSharedInternals.H.useState(initialState)},exports.useSyncExternalStore=function(subscribe,getSnapshot,getServerSnapshot){return ReactSharedInternals.H.useSyncExternalStore(subscribe,getSnapshot,getServerSnapshot)},exports.useTransition=function(){return ReactSharedInternals.H.useTransition()},exports.version="19.3.0-canary-3f0b9e61-20260317"},41976,(__turbopack_context__,module,exports)=>{"use strict";module.exports=__turbopack_context__.r(4532)},81258,(__turbopack_context__,module,exports)=>{"use strict";exports._=function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}},99308,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:!0,get:all[name]})}(exports,{bindSnapshot:function(){return bindSnapshot},createAsyncLocalStorage:function(){return createAsyncLocalStorage},createSnapshot:function(){return createSnapshot}});let sharedAsyncLocalStorageNotAvailableError=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class FakeAsyncLocalStorage{disable(){throw sharedAsyncLocalStorageNotAvailableError}getStore(){}run(){throw sharedAsyncLocalStorageNotAvailableError}exit(){throw sharedAsyncLocalStorageNotAvailableError}enterWith(){throw sharedAsyncLocalStorageNotAvailableError}static bind(fn){return fn}}let maybeGlobalAsyncLocalStorage="u">typeof globalThis&&globalThis.AsyncLocalStorage;function createAsyncLocalStorage(){return maybeGlobalAsyncLocalStorage?new maybeGlobalAsyncLocalStorage:new FakeAsyncLocalStorage}function bindSnapshot(fn){return maybeGlobalAsyncLocalStorage?maybeGlobalAsyncLocalStorage.bind(fn):FakeAsyncLocalStorage.bind(fn)}function createSnapshot(){return maybeGlobalAsyncLocalStorage?maybeGlobalAsyncLocalStorage.snapshot():function(fn,...args){return fn(...args)}}},29799,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"workAsyncStorageInstance",{enumerable:!0,get:function(){return workAsyncStorageInstance}});let workAsyncStorageInstance=(0,__turbopack_context__.r(99308).createAsyncLocalStorage)()},16462,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"workAsyncStorage",{enumerable:!0,get:function(){return _workasyncstorageinstance.workAsyncStorageInstance}});let _workasyncstorageinstance=__turbopack_context__.r(29799)},58293,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"handleISRError",{enumerable:!0,get:function(){return handleISRError}});let workAsyncStorage="u"<typeof window?__turbopack_context__.r(16462).workAsyncStorage:void 0;function handleISRError({error}){if(workAsyncStorage){let store=workAsyncStorage.getStore();if(store?.isStaticGeneration)throw error&&console.error(error),error}}("function"==typeof exports.default||"object"==typeof exports.default&&null!==exports.default)&&void 0===exports.default.__esModule&&(Object.defineProperty(exports.default,"__esModule",{value:!0}),Object.assign(exports.default,exports),module.exports=exports.default)},70644,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:!0,get:all[name]})}(exports,{WarningIcon:function(){return WarningIcon},errorStyles:function(){return errorStyles},errorThemeCss:function(){return errorThemeCss}}),__turbopack_context__.r(81258);let _jsxruntime=__turbopack_context__.r(74018);__turbopack_context__.r(41976);let errorStyles={container:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",display:"flex",alignItems:"center",justifyContent:"center"},card:{marginTop:"-32px",maxWidth:"325px",padding:"32px 28px",textAlign:"left"},icon:{marginBottom:"24px"},title:{fontSize:"24px",fontWeight:500,letterSpacing:"-0.02em",lineHeight:"32px",margin:"0 0 12px 0",color:"var(--next-error-title)"},message:{fontSize:"14px",fontWeight:400,lineHeight:"21px",margin:"0 0 20px 0",color:"var(--next-error-message)"},form:{margin:0},buttonGroup:{display:"flex",gap:"8px",alignItems:"center"},button:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:"32px",padding:"0 12px",fontSize:"14px",fontWeight:500,lineHeight:"20px",borderRadius:"6px",cursor:"pointer",color:"var(--next-error-btn-text)",background:"var(--next-error-btn-bg)",border:"var(--next-error-btn-border)"},buttonSecondary:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:"32px",padding:"0 12px",fontSize:"14px",fontWeight:500,lineHeight:"20px",borderRadius:"6px",cursor:"pointer",color:"var(--next-error-btn-secondary-text)",background:"var(--next-error-btn-secondary-bg)",border:"var(--next-error-btn-secondary-border)"},digestFooter:{position:"fixed",bottom:"32px",left:"0",right:"0",textAlign:"center",fontFamily:'ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace',fontSize:"12px",lineHeight:"18px",fontWeight:400,margin:"0",color:"var(--next-error-digest)"}},errorThemeCss=` | ||
| :root { | ||
| --next-error-bg: #fff; | ||
| --next-error-text: #171717; | ||
| --next-error-title: #171717; | ||
| --next-error-message: #171717; | ||
| --next-error-digest: #666666; | ||
| --next-error-btn-text: #fff; | ||
| --next-error-btn-bg: #171717; | ||
| --next-error-btn-border: none; | ||
| --next-error-btn-secondary-text: #171717; | ||
| --next-error-btn-secondary-bg: transparent; | ||
| --next-error-btn-secondary-border: 1px solid rgba(0,0,0,0.08); | ||
| } | ||
| @media (prefers-color-scheme: dark) { | ||
| :root { | ||
| --next-error-bg: #0a0a0a; | ||
| --next-error-text: #ededed; | ||
| --next-error-title: #ededed; | ||
| --next-error-message: #ededed; | ||
| --next-error-digest: #a0a0a0; | ||
| --next-error-btn-text: #0a0a0a; | ||
| --next-error-btn-bg: #ededed; | ||
| --next-error-btn-border: none; | ||
| --next-error-btn-secondary-text: #ededed; | ||
| --next-error-btn-secondary-bg: transparent; | ||
| --next-error-btn-secondary-border: 1px solid rgba(255,255,255,0.14); | ||
| } | ||
| } | ||
| body { margin: 0; color: var(--next-error-text); background: var(--next-error-bg); } | ||
| `.replace(/\n\s*/g,"");function WarningIcon(){return(0,_jsxruntime.jsx)("svg",{width:"32",height:"32",viewBox:"-0.2 -1.5 32 32",fill:"none",style:errorStyles.icon,children:(0,_jsxruntime.jsx)("path",{d:"M16.9328 0C18.0839 0.000116771 19.1334 0.658832 19.634 1.69531L31.4299 26.1309C32.0708 27.4588 31.1036 28.9999 29.6291 29H2.00215C0.527541 29 -0.439628 27.4588 0.201371 26.1309L11.9973 1.69531C12.4979 0.658823 13.5474 7.75066e-05 14.6984 0H16.9328ZM3.59493 26H28.0363L16.9328 3H14.6984L3.59493 26ZM15.8156 19C16.9202 19.0001 17.8156 19.8955 17.8156 21C17.8156 22.1045 16.9202 22.9999 15.8156 23C14.7111 23 13.8156 22.1046 13.8156 21C13.8156 19.8954 14.7111 19 15.8156 19ZM17.3156 16.5H14.3156V8.5H17.3156V16.5Z",fill:"var(--next-error-title)"})})}("function"==typeof exports.default||"object"==typeof exports.default&&null!==exports.default)&&void 0===exports.default.__esModule&&(Object.defineProperty(exports.default,"__esModule",{value:!0}),Object.assign(exports.default,exports),module.exports=exports.default)},20558,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _default}}),__turbopack_context__.r(81258);let _jsxruntime=__turbopack_context__.r(74018);__turbopack_context__.r(41976);let _handleisrerror=__turbopack_context__.r(58293),_errorstyles=__turbopack_context__.r(70644),_default=function DefaultGlobalError({error}){let digest=error?.digest,isServerError=!!digest;return(0,_handleisrerror.handleISRError)({error}),(0,_jsxruntime.jsxs)("html",{id:"__next_error__",children:[(0,_jsxruntime.jsx)("head",{children:(0,_jsxruntime.jsx)("style",{dangerouslySetInnerHTML:{__html:_errorstyles.errorThemeCss}})}),(0,_jsxruntime.jsxs)("body",{children:[(0,_jsxruntime.jsx)("div",{style:_errorstyles.errorStyles.container,children:(0,_jsxruntime.jsxs)("div",{style:_errorstyles.errorStyles.card,children:[(0,_jsxruntime.jsx)(_errorstyles.WarningIcon,{}),(0,_jsxruntime.jsx)("h1",{style:_errorstyles.errorStyles.title,children:"This page couldn’t load"}),(0,_jsxruntime.jsx)("p",{style:_errorstyles.errorStyles.message,children:isServerError?"A server error occurred. Reload to try again.":"Reload to try again, or go back."}),(0,_jsxruntime.jsxs)("div",{style:_errorstyles.errorStyles.buttonGroup,children:[(0,_jsxruntime.jsx)("form",{style:_errorstyles.errorStyles.form,children:(0,_jsxruntime.jsx)("button",{type:"submit",style:_errorstyles.errorStyles.button,children:"Reload"})}),!isServerError&&(0,_jsxruntime.jsx)("button",{type:"button",style:_errorstyles.errorStyles.buttonSecondary,onClick:()=>{window.history.length>1?window.history.back():window.location.href="/"},children:"Back"})]})]})}),digest&&(0,_jsxruntime.jsxs)("p",{style:_errorstyles.errorStyles.digestFooter,children:["ERROR ",digest]})]})]})};("function"==typeof exports.default||"object"==typeof exports.default&&null!==exports.default)&&void 0===exports.default.__esModule&&(Object.defineProperty(exports.default,"__esModule",{value:!0}),Object.assign(exports.default,exports),module.exports=exports.default)}]); |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,{otherChunks:["static/chunks/0_853fpryox2z.js","static/chunks/0cdeg.livuop2.js","static/chunks/0rp--m6md0lzz.js"],runtimeModuleIds:[17778]}]),(()=>{let BACKEND;if(!Array.isArray(globalThis.TURBOPACK))return;let CHUNK_BASE_PATH="/_next/",ASSET_SUFFIX=getAssetSuffixFromScriptSrc(),WORKER_FORWARDED_GLOBALS=["NEXT_DEPLOYMENT_ID","NEXT_CLIENT_ASSET_SUFFIX"];var SourceType,SourceType1=((SourceType=SourceType1||{})[SourceType.Runtime=0]="Runtime",SourceType[SourceType.Parent=1]="Parent",SourceType[SourceType.Update=2]="Update",SourceType);let REEXPORTED_OBJECTS=new WeakMap;function Context(module,exports){this.m=module,this.e=exports}let contextPrototype=Context.prototype,hasOwnProperty=Object.prototype.hasOwnProperty,toStringTag="u">typeof Symbol&&Symbol.toStringTag;function defineProp(obj,name,options){hasOwnProperty.call(obj,name)||Object.defineProperty(obj,name,options)}function getOverwrittenModule(moduleCache,id){let module=moduleCache[id];return module||(module=createModuleObject(id),moduleCache[id]=module),module}function createModuleObject(id){return{exports:{},error:void 0,id,namespaceObject:void 0}}function esm(exports,bindings){defineProp(exports,"__esModule",{value:!0}),toStringTag&&defineProp(exports,toStringTag,{value:"Module"});let i=0;for(;i<bindings.length;){let propName=bindings[i++],tagOrFunction=bindings[i++];if("number"==typeof tagOrFunction)if(0===tagOrFunction)defineProp(exports,propName,{value:bindings[i++],enumerable:!0,writable:!1});else throw Error(`unexpected tag: ${tagOrFunction}`);else"function"==typeof bindings[i]?defineProp(exports,propName,{get:tagOrFunction,set:bindings[i++],enumerable:!0}):defineProp(exports,propName,{get:tagOrFunction,enumerable:!0})}Object.seal(exports)}function ensureDynamicExports(module,exports){let reexportedObjects=REEXPORTED_OBJECTS.get(module);return reexportedObjects||(REEXPORTED_OBJECTS.set(module,reexportedObjects=[]),module.exports=module.namespaceObject=new Proxy(exports,{get(target,prop){if(hasOwnProperty.call(target,prop)||"default"===prop||"__esModule"===prop)return Reflect.get(target,prop);for(let obj of reexportedObjects){let value=Reflect.get(obj,prop);if(void 0!==value)return value}},ownKeys(target){let keys=Reflect.ownKeys(target);for(let obj of reexportedObjects)for(let key of Reflect.ownKeys(obj))"default"===key||keys.includes(key)||keys.push(key);return keys}})),reexportedObjects}function exportValue(value,id){(null!=id?getOverwrittenModule(this.c,id):this.m).exports=value}function createGetter(obj,key){return()=>obj[key]}contextPrototype.s=function esmExport(bindings,id){let module,exports;null!=id?exports=(module=getOverwrittenModule(this.c,id)).exports:(module=this.m,exports=this.e),module.namespaceObject=exports,esm(exports,bindings)},contextPrototype.j=function dynamicExport(object,id){let module,exports;null!=id?exports=(module=getOverwrittenModule(this.c,id)).exports:(module=this.m,exports=this.e);let reexportedObjects=ensureDynamicExports(module,exports);"object"==typeof object&&null!==object&&reexportedObjects.push(object)},contextPrototype.v=exportValue,contextPrototype.n=function exportNamespace(namespace,id){let module;(module=null!=id?getOverwrittenModule(this.c,id):this.m).exports=module.namespaceObject=namespace};let getProto=Object.getPrototypeOf?obj=>Object.getPrototypeOf(obj):obj=>obj.__proto__,LEAF_PROTOTYPES=[null,getProto({}),getProto([]),getProto(getProto)];function interopEsm(raw,ns,allowExportDefault){let bindings=[],defaultLocation=-1;for(let current=raw;("object"==typeof current||"function"==typeof current)&&!LEAF_PROTOTYPES.includes(current);current=getProto(current))for(let key of Object.getOwnPropertyNames(current))bindings.push(key,createGetter(raw,key)),-1===defaultLocation&&"default"===key&&(defaultLocation=bindings.length-1);return allowExportDefault&&defaultLocation>=0||(defaultLocation>=0?bindings.splice(defaultLocation,1,0,raw):bindings.push("default",0,raw)),esm(ns,bindings),ns}function createNS(raw){return"function"==typeof raw?function(...args){return raw.apply(this,args)}:Object.create(null)}function esmImport(id){let module=getOrInstantiateModuleFromParent(id,this.m);if(module.namespaceObject)return module.namespaceObject;let raw=module.exports;return module.namespaceObject=interopEsm(raw,createNS(raw),raw&&raw.__esModule)}function parseRequest(request){let hashIndex=request.indexOf("#");-1!==hashIndex&&(request=request.substring(0,hashIndex));let queryIndex=request.indexOf("?");return -1!==queryIndex&&(request=request.substring(0,queryIndex)),request}function getChunkPath(chunkData){return"string"==typeof chunkData?chunkData:chunkData.path}function isPromise(maybePromise){return null!=maybePromise&&"object"==typeof maybePromise&&"then"in maybePromise&&"function"==typeof maybePromise.then}function isAsyncModuleExt(obj){return turbopackQueues in obj}function createPromise(){let resolve,reject;return{promise:new Promise((res,rej)=>{reject=rej,resolve=res}),resolve:resolve,reject:reject}}function installCompressedModuleFactories(chunkModules,offset,moduleFactories,newModuleId){let i=offset;for(;i<chunkModules.length;){let existingGroupFactory,end=i+1;for(;end<chunkModules.length&&"function"!=typeof chunkModules[end];)end++;if(end===chunkModules.length)throw Error("malformed chunk format, expected a factory function");let moduleFactoryFn=chunkModules[end];for(let j=i;j<end;j++){let id=chunkModules[j],existingFactory=moduleFactories.get(id);if(existingFactory){existingGroupFactory=existingFactory;break}}let factoryToInstall=existingGroupFactory??moduleFactoryFn,didInstallFactory=!1;for(let j=i;j<end;j++){let id=chunkModules[j];moduleFactories.has(id)||(didInstallFactory||(factoryToInstall===moduleFactoryFn&&applyModuleFactoryName(moduleFactoryFn),didInstallFactory=!0),moduleFactories.set(id,factoryToInstall),newModuleId?.(id))}i=end+1}}contextPrototype.i=esmImport,contextPrototype.A=function asyncLoader(moduleId){return this.r(moduleId)(esmImport.bind(this))},contextPrototype.t="function"==typeof require?require:function require1(){throw Error("Unexpected use of runtime require")},contextPrototype.r=function commonJsRequire(id){return getOrInstantiateModuleFromParent(id,this.m).exports},contextPrototype.f=function moduleContext(map){function moduleContext(id){if(id=parseRequest(id),hasOwnProperty.call(map,id))return map[id].module();let e=Error(`Cannot find module '${id}'`);throw e.code="MODULE_NOT_FOUND",e}return moduleContext.keys=()=>Object.keys(map),moduleContext.resolve=id=>{if(id=parseRequest(id),hasOwnProperty.call(map,id))return map[id].id();let e=Error(`Cannot find module '${id}'`);throw e.code="MODULE_NOT_FOUND",e},moduleContext.import=async id=>await moduleContext(id),moduleContext};let turbopackQueues=Symbol("turbopack queues"),turbopackExports=Symbol("turbopack exports"),turbopackError=Symbol("turbopack error");function resolveQueue(queue){queue&&1!==queue.status&&(queue.status=1,queue.forEach(fn=>fn.queueCount--),queue.forEach(fn=>fn.queueCount--?fn.queueCount++:fn()))}function wrapDeps(deps){return deps.map(dep=>{if(null!==dep&&"object"==typeof dep){if(isAsyncModuleExt(dep))return dep;if(isPromise(dep)){let queue=Object.assign([],{status:0}),obj={[turbopackExports]:{},[turbopackQueues]:fn=>fn(queue)};return dep.then(res=>{obj[turbopackExports]=res,resolveQueue(queue)},err=>{obj[turbopackError]=err,resolveQueue(queue)}),obj}}return{[turbopackExports]:dep,[turbopackQueues]:()=>{}}})}contextPrototype.a=function asyncModule(body,hasAwait){let module=this.m,queue=hasAwait?Object.assign([],{status:-1}):void 0,depQueues=new Set,{resolve,reject,promise:rawPromise}=createPromise(),promise=Object.assign(rawPromise,{[turbopackExports]:module.exports,[turbopackQueues]:fn=>{queue&&fn(queue),depQueues.forEach(fn),promise.catch(()=>{})}}),attributes={get:()=>promise,set(v){v!==promise&&(promise[turbopackExports]=v)}};Object.defineProperty(module,"exports",attributes),Object.defineProperty(module,"namespaceObject",attributes),body(function handleAsyncDependencies(deps){let currentDeps=wrapDeps(deps),getResult=()=>currentDeps.map(d=>{if(d[turbopackError])throw d[turbopackError];return d[turbopackExports]}),{promise,resolve}=createPromise(),fn=Object.assign(()=>resolve(getResult),{queueCount:0});function fnQueue(q){q!==queue&&!depQueues.has(q)&&(depQueues.add(q),q&&0===q.status&&(fn.queueCount++,q.push(fn)))}return currentDeps.map(dep=>dep[turbopackQueues](fnQueue)),fn.queueCount?promise:getResult()},function asyncResult(err){err?reject(promise[turbopackError]=err):resolve(promise[turbopackExports]),resolveQueue(queue)}),queue&&-1===queue.status&&(queue.status=0)};let relativeURL=function relativeURL(inputUrl){let realUrl=new URL(inputUrl,"x:/"),values={};for(let key in realUrl)values[key]=realUrl[key];for(let key in values.href=inputUrl,values.pathname=inputUrl.replace(/[?#].*/,""),values.origin=values.protocol="",values.toString=values.toJSON=(..._args)=>inputUrl,values)Object.defineProperty(this,key,{enumerable:!0,configurable:!0,value:values[key]})};function invariant(never,computeMessage){throw Error(`Invariant: ${computeMessage(never)}`)}function factoryNotAvailableMessage(moduleId,sourceType,sourceData){let instantiationReason;switch(sourceType){case 0:instantiationReason=`as a runtime entry of chunk ${sourceData}`;break;case 1:instantiationReason=`because it was required from module ${sourceData}`;break;case 2:instantiationReason="because of an HMR update";break;default:invariant(sourceType,sourceType=>`Unknown source type: ${sourceType}`)}return`Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`}function applyModuleFactoryName(factory){Object.defineProperty(factory,"name",{value:"module evaluation"})}relativeURL.prototype=URL.prototype,contextPrototype.U=relativeURL,contextPrototype.z=function requireStub(_moduleId){throw Error("dynamic usage of require is not supported")},contextPrototype.g=globalThis;let browserContextPrototype=Context.prototype,moduleFactories=new Map;contextPrototype.M=moduleFactories;let availableModules=new Map,availableModuleChunks=new Map;function loadInitialChunk(chunkPath,chunkData){return loadChunkInternal(SourceType1.Runtime,chunkPath,chunkData)}async function loadChunkInternal(sourceType,sourceData,chunkData){let promise;if("string"==typeof chunkData)return loadChunkByUrlInternal(sourceType,sourceData,getChunkRelativeUrl(chunkData));let includedList=chunkData.included||[],modulesPromises=includedList.map(included=>!!moduleFactories.has(included)||availableModules.get(included));if(modulesPromises.length>0&&modulesPromises.every(p=>p))return void await Promise.all(modulesPromises);let includedModuleChunksList=chunkData.moduleChunks||[],moduleChunksPromises=includedModuleChunksList.map(included=>availableModuleChunks.get(included)).filter(p=>p);if(moduleChunksPromises.length>0){if(moduleChunksPromises.length===includedModuleChunksList.length)return void await Promise.all(moduleChunksPromises);let moduleChunksToLoad=new Set;for(let moduleChunk of includedModuleChunksList)availableModuleChunks.has(moduleChunk)||moduleChunksToLoad.add(moduleChunk);for(let moduleChunkToLoad of moduleChunksToLoad){let promise=loadChunkByUrlInternal(sourceType,sourceData,getChunkRelativeUrl(moduleChunkToLoad));availableModuleChunks.set(moduleChunkToLoad,promise),moduleChunksPromises.push(promise)}promise=Promise.all(moduleChunksPromises)}else{for(let includedModuleChunk of(promise=loadChunkByUrlInternal(sourceType,sourceData,getChunkRelativeUrl(chunkData.path)),includedModuleChunksList))availableModuleChunks.has(includedModuleChunk)||availableModuleChunks.set(includedModuleChunk,promise)}for(let included of includedList)availableModules.has(included)||availableModules.set(included,promise);await promise}browserContextPrototype.l=function loadChunk(chunkData){return loadChunkInternal(SourceType1.Parent,this.m.id,chunkData)};let loadedChunk=Promise.resolve(void 0),instrumentedBackendLoadChunks=new WeakMap;function loadChunkByUrlInternal(sourceType,sourceData,chunkUrl){let thenable=BACKEND.loadChunkCached(sourceType,chunkUrl),entry=instrumentedBackendLoadChunks.get(thenable);if(void 0===entry){let resolve=instrumentedBackendLoadChunks.set.bind(instrumentedBackendLoadChunks,thenable,loadedChunk);entry=thenable.then(resolve).catch(cause=>{let loadReason;switch(sourceType){case SourceType1.Runtime:loadReason=`as a runtime dependency of chunk ${sourceData}`;break;case SourceType1.Parent:loadReason=`from module ${sourceData}`;break;case SourceType1.Update:loadReason="from an HMR update";break;default:invariant(sourceType,sourceType=>`Unknown source type: ${sourceType}`)}let error=Error(`Failed to load chunk ${chunkUrl} ${loadReason}${cause?`: ${cause}`:""}`,cause?{cause}:void 0);throw error.name="ChunkLoadError",error}),instrumentedBackendLoadChunks.set(thenable,entry)}return entry}function getChunkRelativeUrl(chunkPath){return`${CHUNK_BASE_PATH}${chunkPath.split("/").map(p=>encodeURIComponent(p)).join("/")}${ASSET_SUFFIX}`}function getPathFromScript(chunkScript){if("string"==typeof chunkScript)return chunkScript;let src=decodeURIComponent(chunkScript.src.replace(/[?#].*$/,""));return src.startsWith(CHUNK_BASE_PATH)?src.slice(CHUNK_BASE_PATH.length):src}function getUrlFromScript(chunk){return"string"==typeof chunk?getChunkRelativeUrl(chunk):chunk.src}function getChunkFromRegistration(chunk){if("string"==typeof chunk)return chunk;if(chunk)return{src:chunk.getAttribute("src")};if("u">typeof TURBOPACK_NEXT_CHUNK_URLS)return{src:TURBOPACK_NEXT_CHUNK_URLS.pop()};throw Error("chunk path empty but not in a worker")}browserContextPrototype.L=function loadChunkByUrl(chunkUrl){return loadChunkByUrlInternal(SourceType1.Parent,this.m.id,chunkUrl)},browserContextPrototype.R=function resolvePathFromModule(moduleId){let exported=this.r(moduleId);return exported?.default??exported},browserContextPrototype.P=function resolveAbsolutePath(modulePath){return`/ROOT/${modulePath??""}`},browserContextPrototype.q=function exportUrl(url,id){exportValue.call(this,`${url}${ASSET_SUFFIX}`,id)},browserContextPrototype.b=function createWorker(WorkerConstructor,entrypoint,moduleChunks,workerOptions){let isSharedWorker="SharedWorker"===WorkerConstructor.name,params=[moduleChunks.map(chunk=>getChunkRelativeUrl(chunk)).reverse(),ASSET_SUFFIX];for(let globalName of WORKER_FORWARDED_GLOBALS)params.push(globalThis[globalName]);let url=new URL(getChunkRelativeUrl(entrypoint),location.origin),paramsJson=JSON.stringify(params);return isSharedWorker?url.searchParams.set("params",paramsJson):url.hash="#params="+encodeURIComponent(paramsJson),new WorkerConstructor(url,workerOptions?{...workerOptions,type:void 0}:void 0)};let regexJsUrl=/\.js(?:\?[^#]*)?(?:#.*)?$/,regexCssUrl=/\.css(?:\?[^#]*)?(?:#.*)?$/;function isCss(chunkUrl){return regexCssUrl.test(chunkUrl)}contextPrototype.w=function loadWebAssembly(chunkPath,edgeModule,importsObj){return BACKEND.loadWebAssembly(SourceType1.Parent,this.m.id,chunkPath,edgeModule,importsObj)},contextPrototype.u=function loadWebAssemblyModule(chunkPath,edgeModule){return BACKEND.loadWebAssemblyModule(SourceType1.Parent,this.m.id,chunkPath,edgeModule)};let moduleCache={};function getOrInstantiateRuntimeModule(chunkPath,moduleId){let module=moduleCache[moduleId];if(module){if(module.error)throw module.error;return module}return instantiateModule(moduleId,SourceType1.Runtime,chunkPath)}contextPrototype.c=moduleCache;let getOrInstantiateModuleFromParent=(id,sourceModule)=>{let module=moduleCache[id];if(module){if(module.error)throw module.error;return module}return instantiateModule(id,SourceType1.Parent,sourceModule.id)};function instantiateModule(id,sourceType,sourceData){let moduleFactory=moduleFactories.get(id);if("function"!=typeof moduleFactory)throw Error(factoryNotAvailableMessage(id,sourceType,sourceData));let module=createModuleObject(id),exports=module.exports;moduleCache[id]=module;let context=new Context(module,exports);try{moduleFactory(context,module,exports)}catch(error){throw module.error=error,error}return module.namespaceObject&&module.exports!==module.namespaceObject&&interopEsm(module.exports,module.namespaceObject),module}function registerChunk(registration){let runtimeParams,chunk=getChunkFromRegistration(registration[0]);return 2===registration.length?runtimeParams=registration[1]:(runtimeParams=void 0,installCompressedModuleFactories(registration,1,moduleFactories)),BACKEND.registerChunk(chunk,runtimeParams)}function getAssetSuffixFromScriptSrc(){if(null!=self.TURBOPACK_ASSET_SUFFIX)return self.TURBOPACK_ASSET_SUFFIX;let src=document?.currentScript?.getAttribute?.("src")??"",qi=src.indexOf("?");return qi>=0?src.slice(qi):""}let chunkResolvers=new Map;function getOrCreateResolver(chunkUrl){let resolver=chunkResolvers.get(chunkUrl);if(!resolver){let resolve,reject;resolver={resolved:!1,loadingStarted:!1,promise:new Promise((innerResolve,innerReject)=>{resolve=innerResolve,reject=innerReject}),resolve:()=>{resolver.resolved=!0,resolve()},reject:reject},chunkResolvers.set(chunkUrl,resolver)}return resolver}function doLoadChunk(sourceType,chunkUrl){let resolver=getOrCreateResolver(chunkUrl);if(resolver.loadingStarted)return resolver.promise;if(sourceType===SourceType1.Runtime)return resolver.loadingStarted=!0,isCss(chunkUrl)&&resolver.resolve(),resolver.promise;if("function"==typeof importScripts)if(isCss(chunkUrl));else if(regexJsUrl.test(chunkUrl))self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl),importScripts(chunkUrl);else throw Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);else{let decodedChunkUrl=decodeURI(chunkUrl);if(isCss(chunkUrl))if(document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`).length>0)resolver.resolve();else{let link=document.createElement("link");link.rel="stylesheet",link.href=chunkUrl,link.onerror=()=>{resolver.reject()},link.onload=()=>{resolver.resolve()},document.head.appendChild(link)}else if(regexJsUrl.test(chunkUrl)){let previousScripts=document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);if(previousScripts.length>0)for(let script of Array.from(previousScripts))script.addEventListener("error",()=>{resolver.reject()});else{let script=document.createElement("script");script.src=chunkUrl,script.onerror=()=>{resolver.reject()},document.head.appendChild(script)}}else throw Error(`can't infer type of chunk from URL ${chunkUrl}`)}return resolver.loadingStarted=!0,resolver.promise}BACKEND={async registerChunk(chunk,params){let chunkPath=getPathFromScript(chunk);if(getOrCreateResolver(getUrlFromScript(chunk)).resolve(),null!=params){for(let otherChunkData of params.otherChunks)getOrCreateResolver(getChunkRelativeUrl(getChunkPath(otherChunkData)));if(await Promise.all(params.otherChunks.map(otherChunkData=>loadInitialChunk(chunkPath,otherChunkData))),params.runtimeModuleIds.length>0)for(let moduleId of params.runtimeModuleIds)getOrInstantiateRuntimeModule(chunkPath,moduleId)}},loadChunkCached:(sourceType,chunkUrl)=>doLoadChunk(sourceType,chunkUrl),async loadWebAssembly(_sourceType,_sourceData,wasmChunkPath,_edgeModule,importsObj){let req=fetch(getChunkRelativeUrl(wasmChunkPath)),{instance}=await WebAssembly.instantiateStreaming(req,importsObj);return instance.exports},async loadWebAssemblyModule(_sourceType,_sourceData,wasmChunkPath,_edgeModule){let req=fetch(getChunkRelativeUrl(wasmChunkPath));return await WebAssembly.compileStreaming(req)}};let chunksToRegister=globalThis.TURBOPACK;globalThis.TURBOPACK={push:registerChunk},chunksToRegister.forEach(registerChunk)})(); |
Sorry, the diff of this file is not supported yet
| (()=>{var e={691:(e,t,r)=>{e.exports=r(498)},498:(e,t,r)=>{"use strict";r.r(t);r.d(t,{ProxyServer:()=>_,createProxyServer:()=>createProxyServer,proxyFetch:()=>proxyFetch,proxyUpgrade:()=>proxyUpgrade});const o=require("node:http");const s=require("node:https");const n=require("node:http2");const i=require("node:events");const a=require("node:net");const c=require("node:stream");const f=/(^|,)\s*upgrade\s*($|,)/i;const d=/(^|,)\s*transfer-encoding\s*($|,)/i;const u={http:new o.Agent({keepAlive:true,maxSockets:256,maxFreeSockets:64}),https:new s.Agent({keepAlive:true,maxSockets:256,maxFreeSockets:64})};const h=/^https|wss/;function forceConnectionCloseForTransferEncoding(e){let t=false;for(const r in e)if(e[r]!==void 0&&r.toLowerCase()==="transfer-encoding"){t=true;break}const r=e.connection;const o=typeof r==="string"&&d.test(r);if(t||o)e.connection="close"}const p=[":method",":path",":scheme",":authority"];function setupOutgoing(e,t,r,o){e.port=t[o||"target"].port||(h.test(t[o||"target"].protocol??"http")?443:80);for(const r of["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"]){const s=t[o||"target"][r];if(s!==void 0)e[r]=s}if(e.host===void 0&&typeof e.hostname==="string"){const t=e.hostname.includes(":")&&!e.hostname.startsWith("[")?`[${e.hostname}]`:e.hostname;e.host=e.port?`${t}:${e.port}`:t}e.method=t.method||r.method;e.headers={...r.headers};if(r.headers?.[":authority"])e.headers.host=r.headers[":authority"];if(t.headers)for(const r of Object.keys(t.headers))e.headers[r]=t.headers[r];if(r.httpVersionMajor>1)for(const t of p)delete e.headers[t];if(t.auth)e.auth=t.auth;if(t.ca)e.ca=t.ca;if(h.test(t[o||"target"].protocol??"http"))e.rejectUnauthorized=t.secure===void 0?true:t.secure;if(t.agent!==void 0)e.agent=t.agent||false;else if(r.httpVersionMajor>1||f.test(r.headers.connection||""))e.agent=false;else{const r=t[o||"target"].protocol??"http";e.agent=h.test(r)?u.https:u.http}e.localAddress=t.localAddress;if(!e.agent){e.headers=e.headers||{};if(typeof e.headers.connection!=="string"||!f.test(e.headers.connection))e.headers.connection="close"}e.headers=e.headers||{};forceConnectionCloseForTransferEncoding(e.headers);const s=t[o||"target"];const n=s&&t.prependPath!==false?s.pathname||"":"";const i=s instanceof URL&&t.prependPath!==false?s.search||"":"";const a=r.url||"";const c=a.indexOf("?");const d=c===-1?a:a.slice(0,c);const l=c===-1?"":a.slice(c);const w=d?d[0]==="/"?d:"/"+d:"/";let g=t.toProxy?"/"+a:w+l;g=t.ignorePath?"":g;let y=joinURL(n,g);if(i)y=y.includes("?")?y.replace("?",i+"&"):y+i;e.path=y;if(t.changeOrigin)e.headers.host=requiresPort(e.port,t[o||"target"].protocol)&&!hasPort(e.host)?e.host+":"+e.port:e.host??void 0;return e}function joinURL(e,t){if(!e||e==="/")return t||"/";if(!t||t==="/")return e||"/";const r=e[e.length-1]==="/";const o=t[0]==="/";if(r&&o)return e+t.slice(1);if(!r&&!o)return e+"/"+t;return e+t}function setupSocket(e){e.setTimeout(0);e.setNoDelay(true);e.setKeepAlive(true,0);return e}function getPort(e){const t=e.headers[":authority"]||e.headers.host;const r=t?t.match(/:(\d+)/):"";if(r)return r[1];return hasEncryptedConnection(e)?"443":"80"}function hasEncryptedConnection(e){const t=e.socket;return!!t&&"encrypted"in t&&t.encrypted}function rewriteCookieProperty(e,t,r){if(Array.isArray(e))return e.map((function(e){return rewriteCookieProperty(e,t,r)}));return e.replace(new RegExp(String.raw`(;\s*`+r+"=)([^;]+)","i"),(function(e,r,o){let s;if(o in t)s=t[o];else if("*"in t)s=t["*"];else return e;return s?r+s:""}))}function parseAddr(e){if(typeof e==="string"){if(e.startsWith("unix:"))return{socketPath:e.slice(5)};const t=new URL(e);return{host:t.hostname,port:Number(t.port)||(h.test(t.protocol)?443:80)}}if(!e.socketPath&&!e.port)throw new Error("ProxyAddr must have either `port` or `socketPath`");return e}function hasPort(e){return e?!!~e.indexOf(":"):false}function requiresPort(e,t){const r=t?.split(":")[0];const o=+e;if(!o)return false;switch(r){case"http":case"ws":return o!==80;case"https":case"wss":return o!==443;case"ftp":return o!==21;case"gopher":return o!==70;case"file":return false}return o!==0}function defineProxyMiddleware(e){return e}function defineProxyOutgoingMiddleware(e){return e}const l=/^201|30([12378])$/;const w=[defineProxyOutgoingMiddleware(((e,t,r)=>{if(e.httpVersion==="1.0"||e.httpVersionMajor>=2||r.statusCode===204||r.statusCode===304)delete r.headers["transfer-encoding"]})),defineProxyOutgoingMiddleware(((e,t,r)=>{if(e.httpVersion==="1.0")r.headers.connection=e.headers.connection||"close";else if(e.httpVersionMajor<2&&!r.headers.connection)r.headers.connection=e.headers.connection||"keep-alive";else if(e.httpVersionMajor>=2)delete r.headers.connection})),defineProxyOutgoingMiddleware(((e,t,r,o)=>{if((o.hostRewrite||o.autoRewrite||o.protocolRewrite)&&r.headers.location&&l.test(String(r.statusCode))){const t=_toURL(o.target);const s=r.headers.location.startsWith("//")&&!o.protocolRewrite;const n=new URL(r.headers.location,t);if(t.host!==n.host)return;if(o.hostRewrite)n.host=o.hostRewrite;else if(o.autoRewrite){if(e.headers[":authority"])n.host=e.headers[":authority"];else if(e.headers.host)n.host=e.headers.host}if(o.protocolRewrite)n.protocol=o.protocolRewrite;r.headers.location=s?n.href.slice(n.protocol.length):n.href}})),defineProxyOutgoingMiddleware(((e,t,r,o)=>{const s=typeof o.cookieDomainRewrite==="string"?{"*":o.cookieDomainRewrite}:o.cookieDomainRewrite;const n=typeof o.cookiePathRewrite==="string"?{"*":o.cookiePathRewrite}:o.cookiePathRewrite;const i=o.preserveHeaderKeyCase;let a;const setHeader=function(e,r){if(r===void 0||!String(e).trim())return;if(s&&e.toLowerCase()==="set-cookie")r=rewriteCookieProperty(r,s,"domain");if(n&&e.toLowerCase()==="set-cookie")r=rewriteCookieProperty(r,n,"path");try{t.setHeader(String(e).trim(),r)}catch{}};if(i&&r.rawHeaders!==void 0){a={};for(let e=0;e<r.rawHeaders.length;e+=2){const t=r.rawHeaders[e];a[t.toLowerCase()]=t}}for(let e of Object.keys(r.headers)){const t=r.headers[e];if(i&&a)e=a[e]||e;setHeader(e,t)}})),defineProxyOutgoingMiddleware(((e,t,r)=>{t.statusCode=r.statusCode;if(r.statusMessage&&e.httpVersionMajor<2)t.statusMessage=r.statusMessage}))];function _toURL(e){if(e instanceof URL)return e;if(typeof e==="string")return new URL(e);const t=e.protocol||"http:";const r=e.host||e.hostname||"localhost";const o=e.port;return new URL(`${t}//${r}${o?":"+o:""}`)}const g={http:o,https:s};const y=new Set([301,302,303,307,308]);const m=[defineProxyMiddleware((e=>{if((e.method==="DELETE"||e.method==="OPTIONS")&&!e.headers["content-length"]&&!e.headers["transfer-encoding"])e.headers["content-length"]="0"})),defineProxyMiddleware(((e,t,r)=>{if(r.timeout)e.socket.setTimeout(r.timeout,(()=>{e.socket.destroy()}))})),defineProxyMiddleware(((e,t,r)=>{if(!r.xfwd)return;const o=e.isSpdy||hasEncryptedConnection(e);const s={for:e.connection.remoteAddress||e.socket.remoteAddress,port:getPort(e),proto:o?"https":"http"};for(const t of["for","port","proto"]){const r="x-forwarded-"+t;if(!e.headers[r]&&s[t]!==void 0)e.headers[r]=s[t]}e.headers["x-forwarded-host"]=e.headers["x-forwarded-host"]||e.headers[":authority"]||e.headers.host||""})),defineProxyMiddleware(((e,t,r,o,s,n)=>{o.emit("start",e,t,r.target||r.forward);const i=g.http;const a=g.https;const c=typeof r.followRedirects==="number"?r.followRedirects:r.followRedirects?5:0;if(r.forward){const o=(h.test(r.forward.protocol||"http")?a:i).request(setupOutgoing(r.ssl||{},r,e,"forward"));const s=createErrorHandler(o,r.forward);e.on("error",s);o.on("error",s);(r.buffer||e).pipe(o);if(!r.target){t.end();return}}const f=(h.test(r.target.protocol||"http")?a:i).request(setupOutgoing(r.ssl||{},r,e));f.on("socket",(s=>{if(o&&!f.getHeader("expect"))o.emit("proxyReq",f,e,t,r)}));if(r.proxyTimeout)f.setTimeout(r.proxyTimeout,(function(){f.destroy()}));t.on("close",(function(){if(!t.writableFinished)f.destroy()}));const d=createErrorHandler(f,r.target);e.on("error",d);f.on("error",d);function createErrorHandler(r,s){return function proxyError(i){if(!e.socket?.writable&&i.code==="ECONNRESET"){o.emit("econnreset",i,e,t,s);return r.destroy()}if(n)n(i,e,t,s);else o.emit("error",i,e,t,s)}}let u;if(c>0){const t=[];const o=r.buffer||e;o.on("data",(e=>{t.push(typeof e==="string"?Buffer.from(e):e);f.write(e)}));o.on("end",(()=>{u=Buffer.concat(t);f.end()}));o.on("error",(e=>{f.destroy(e)}))}else f.on("socket",(t=>{if(t.pending)t.on("connect",(()=>(r.buffer||e).pipe(f)));else(r.buffer||e).pipe(f)}));function handleResponse(s,n,f){const d=s.statusCode;if(c>0&&y.has(d)&&n<c&&s.headers.location){s.resume();const c=new URL(s.headers.location,f);const p=d===307||d===308;const l=p?e.method||"GET":"GET";const w=h.test(c.protocol);const g=w?a:i;const y={...e.headers};if(r.headers)Object.assign(y,r.headers);y.host=c.host;if(c.host!==f.host){delete y.authorization;delete y.cookie}if(!p){delete y["content-length"];delete y["content-type"];delete y["transfer-encoding"]}forceConnectionCloseForTransferEncoding(y);const m={hostname:c.hostname,port:c.port||(w?443:80),path:c.pathname+c.search,method:l,headers:y,agent:r.agent||false};if(w)m.rejectUnauthorized=r.secure===void 0?true:r.secure;const x=g.request(m);if(o&&!x.getHeader("expect"))o.emit("proxyReq",x,e,t,r);if(r.proxyTimeout)x.setTimeout(r.proxyTimeout,(()=>{x.destroy()}));const _=createErrorHandler(x,c);x.on("error",_);x.on("response",(e=>{handleResponse(e,n+1,c)}));if(p&&u&&u.length>0)x.end(u);else x.end();return}if(o)o.emit("proxyRes",s,e,t);if(!t.headersSent&&!r.selfHandleResponse){for(const o of w)if(o(e,t,s,r))break}if(t.finished){if(o)o.emit("end",e,t,s)}else{t.on("close",(function(){s.destroy()}));s.on("close",(function(){if(!s.complete&&!t.destroyed)t.destroy()}));s.on("error",(function(r){if(!t.destroyed)t.destroy(r);if(o.listenerCount("error")>0)o.emit("error",r,e,t,f)}));s.on("end",(function(){if(o)o.emit("end",e,t,s)}));if(!r.selfHandleResponse)s.pipe(t)}}f.on("response",(function(e){handleResponse(e,0,r.target)}))}))];const x=[defineProxyMiddleware(((e,t)=>{if(e.method!=="GET"||!e.headers.upgrade){t.destroy();return true}if(e.headers.upgrade.toLowerCase()!=="websocket"){t.destroy();return true}})),defineProxyMiddleware(((e,t,r)=>{if(!r.xfwd)return;const o={for:e.connection.remoteAddress||e.socket.remoteAddress,port:getPort(e),proto:hasEncryptedConnection(e)?"wss":"ws"};for(const t of["for","port","proto"]){const r="x-forwarded-"+t;if(!e.headers[r]&&o[t]!==void 0)e.headers[r]=o[t]}})),defineProxyMiddleware(((e,t,r,n,i,a)=>{const createHttpHeader=function(e,t){return Object.keys(t).reduce((function(e,r){const o=t[r];if(!Array.isArray(o)){e.push(r+": "+o);return e}for(const t of o)e.push(r+": "+t);return e}),[e]).join("\r\n")+"\r\n\r\n"};setupSocket(t);if(i&&i.length>0)t.unshift(i);t.on("error",onSocketError);const c=(h.test(r.target.protocol||"http")?s:o).request(setupOutgoing(r.ssl||{},r,e));if(n)n.emit("proxyReqWs",c,e,t,r,i);c.on("error",onOutgoingError);c.on("response",(function(e){if(!e.upgrade)if(!t.destroyed&&t.writable){t.write(createHttpHeader("HTTP/"+e.httpVersion+" "+e.statusCode+" "+e.statusMessage,e.headers));e.on("error",onOutgoingError);e.pipe(t)}else e.resume()}));c.on("upgrade",(function(e,r,o){r.on("error",onOutgoingError);r.on("end",(function(){n.emit("close",e,r,o)}));t.removeListener("error",onSocketError);t.on("error",(function(){r.end()}));setupSocket(r);if(o&&o.length>0)r.unshift(o);t.write(createHttpHeader("HTTP/1.1 101 Switching Protocols",e.headers));r.pipe(t).pipe(r);n.emit("open",r);n.emit("proxySocket",r)}));c.end();function onSocketError(r){if(a)a(r,e,t);else n.emit("error",r,e,t);c.destroy()}function onOutgoingError(r){if(a)a(r,e,t);else n.emit("error",r,e,t);t.end()}}))];var _=class extends i.EventEmitter{_server;_webPasses=[...m];_wsPasses=[...x];options;web;ws;constructor(e={}){super();this.options=e||{};this.options.prependPath=e.prependPath!==false;this.web=_createProxyFn("web",this);this.ws=_createProxyFn("ws",this)}listen(e,t,r){const closure=(e,t)=>this.web(e,t);if(this.options.http2){if(!this.options.ssl)throw new Error("HTTP/2 requires ssl option");this._server=n.createSecureServer({...this.options.ssl,allowHTTP1:true},closure)}else if(this.options.ssl)this._server=s.createServer(this.options.ssl,closure);else this._server=o.createServer(closure);if(this.options.ws)this._server.on("upgrade",((e,t,r)=>{this.ws(e,t,this.options,r).catch((()=>{}))}));this._server.listen(e,t,r);return this}close(e){if(this._server)this._server.close(((...t)=>{this._server=void 0;if(e)Reflect.apply(e,void 0,t)}))}before(e,t,r){if(e!=="ws"&&e!=="web")throw new Error("type must be `web` or `ws`");const o=this._getPasses(e);let s=false;for(const[e,r]of o.entries())if(r.name===t)s=e;if(s===false)throw new Error("No such pass");o.splice(s,0,r)}after(e,t,r){if(e!=="ws"&&e!=="web")throw new Error("type must be `web` or `ws`");const o=this._getPasses(e);let s=false;for(const[e,r]of o.entries())if(r.name===t)s=e;if(s===false)throw new Error("No such pass");o.splice(s++,0,r)}_getPasses(e){return e==="ws"?this._wsPasses:this._webPasses}};function createProxyServer(e={}){return new _(e)}function _createProxyFn(e,t){return function(r,o,s,n){const i={...s,...t.options};for(const e of["target","forward"])if(typeof i[e]==="string")i[e]=new URL(i[e]);if(!i.target&&!i.forward){this.emit("error",new Error("Must provide a proper URL as target"));return Promise.resolve()}let a;let c;const f=new Promise(((e,t)=>{a=e;c=t}));o.on("close",(()=>{a()}));o.on("error",(e=>{c(e)}));for(const s of t._getPasses(e)){let e;try{e=s(r,o,i,t,n,((e,s,n,i)=>{if(t.listenerCount("error")>0){t.emit("error",e,r,o,i);a()}else c(e)}))}catch(e){if(t.listenerCount("error")>0){t.emit("error",e,r,o,i.target||i.forward);a()}else c(e);break}if(e){a();break}}return f}}async function proxyFetch(e,t,r,n){const i=parseAddr(e);let a=false;let f="";if(typeof e==="string"&&!e.startsWith("unix:")){const t=new URL(e);a=h.test(t.protocol);if(t.pathname&&t.pathname!=="/")f=t.pathname}let d;let p;if(t instanceof Request){d=new URL(t.url);p={...toInit(t),...toInit(r)}}else{d=new URL(t);p=toInit(r)}p={redirect:"manual",...p};if(p.body)p.duplex="half";const l=d.pathname+d.search;const w=f?joinURL(f,l):l;const g={};if(p.headers)if(!(p.headers instanceof Headers)&&!Array.isArray(p.headers))Object.assign(g,p.headers);else for(const[e,t]of p.headers){const r=g[e];if(r===void 0)g[e]=t;else g[e]=Array.isArray(r)?[...r,t]:[r,t]}if(n?.xfwd){if(!g["x-forwarded-for"])g["x-forwarded-for"]=d.hostname;if(!g["x-forwarded-port"])g["x-forwarded-port"]=d.port||(d.protocol==="https:"?"443":"80");if(!g["x-forwarded-proto"])g["x-forwarded-proto"]=d.protocol.replace(":","");if(!g["x-forwarded-host"])g["x-forwarded-host"]=d.host}if(n?.changeOrigin)if(i.socketPath)g.host="localhost";else{const e=i.host||"localhost";const t=i.port;g.host=t&&t!==(a?443:80)?`${e}:${t}`:e}const y=typeof n?.followRedirects==="number"?n.followRedirects:n?.followRedirects?5:0;const m=y>0?await _bufferBody(p.body):_toNodeStream(p.body);const x=n?.agent!==void 0?n.agent||false:a?u.https:u.http;const _=await _sendRequest(a?s.request:o.request,p.method||"GET",w,g,i,m,{signal:p.signal||void 0,agent:x,timeout:n?.timeout,ssl:n?.ssl,maxRedirects:y,redirectCount:0,originalHeaders:g});const P=[];const b=_.rawHeaders;for(let e=0;e<b.length;e+=2){const t=b[e];const r=t.toLowerCase();if(r==="transfer-encoding"||r==="keep-alive"||r==="connection")continue;P.push([t,b[e+1]])}const k=_.statusCode!==204&&_.statusCode!==304;return new Response(k?c.Readable.toWeb(_):null,{status:_.statusCode,statusText:_.statusMessage,headers:P})}function toInit(e){if(!e)return;if(e instanceof Request)return{method:e.method,headers:e.headers,body:e.body,duplex:e.body?"half":void 0};return e}function _toNodeStream(e){if(!e)return;if(typeof e==="string")return Buffer.from(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Buffer.from(e);if(e instanceof ReadableStream)return c.Readable.fromWeb(e);if(e instanceof Blob)return c.Readable.fromWeb(e.stream());return Buffer.from(String(e))}async function _bufferBody(e){if(!e)return;if(typeof e==="string")return Buffer.from(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return Buffer.from(e);if(e instanceof ReadableStream){const t=c.Readable.fromWeb(e);const r=[];for await(const e of t)r.push(typeof e==="string"?Buffer.from(e):e);return Buffer.concat(r)}if(e instanceof Blob)return Buffer.from(await e.arrayBuffer());return Buffer.from(String(e))}const P=new Set([301,302,303,307,308]);function _sendRequest(e,t,r,n,i,a,f){forceConnectionCloseForTransferEncoding(n);return new Promise(((d,u)=>{const p={method:t,path:r,headers:n,agent:f.agent};if(i.socketPath)p.socketPath=i.socketPath;else{p.hostname=i.host||"localhost";p.port=i.port}if(f.signal)p.signal=f.signal;if(f.ssl)Object.assign(p,f.ssl);const l=e(p,(e=>{const n=e.statusCode;if(f.maxRedirects>0&&P.has(n)&&f.redirectCount<f.maxRedirects&&e.headers.location){e.resume();const c=new URL(r,`http://${i.host||"localhost"}:${i.port||80}`);const p=new URL(e.headers.location,c);const l=h.test(p.protocol);const w=n===307||n===308;const g=w?t:"GET";const y={...f.originalHeaders};y.host=p.host;if(p.host!==c.host){delete y.authorization;delete y.cookie}if(!w){delete y["content-length"];delete y["content-type"];delete y["transfer-encoding"]}_sendRequest(l?s.request:o.request,g,p.pathname+p.search,y,{host:p.hostname,port:Number(p.port)||(l?443:80)},w?a:void 0,{...f,redirectCount:f.redirectCount+1}).then(d,u);return}d(e)}));l.on("error",u);if(f.timeout)l.setTimeout(f.timeout,(()=>{l.destroy(new Error("Proxy request timed out"))}));if(a instanceof c.Readable){a.on("error",(e=>{l.destroy(e);u(e)}));a.pipe(l)}else if(a)l.end(a);else l.end()}))}function proxyUpgrade(e,t,r,n,i){const a=parseAddr(e);let c=false;if(typeof e==="string"&&!e.startsWith("unix:"))c=h.test(new URL(e).protocol);if(t.method!=="GET"||t.headers.upgrade?.toLowerCase()!=="websocket"){r.destroy();return Promise.reject(new Error("Not a valid WebSocket upgrade request"))}if(i?.xfwd!==false){const e=t.headers["x-forwarded-for"];const r=t.headers["x-forwarded-port"];const o=t.headers["x-forwarded-proto"];t.headers["x-forwarded-for"]=`${e?`${e},`:""}${t.socket?.remoteAddress}`;t.headers["x-forwarded-port"]=`${r?`${r},`:""}${getPort(t)}`;t.headers["x-forwarded-proto"]=`${o?`${o},`:""}${hasEncryptedConnection(t)?"wss":"ws"}`}const f=_buildTargetURL(a,c);const d={...i,target:f,prependPath:i?.prependPath!==false};const u=setupOutgoing(d.ssl||{},d,t);const p=r;return new Promise(((e,t)=>{let r=false;setupSocket(p);if(n&&n.length>0)p.unshift(n);p.once("error",onSocketError);const i=(h.test(f.protocol)?s.request:o.request)(u);i.once("error",onOutgoingError);i.once("response",(e=>{if(!e.upgrade){if(!p.destroyed&&p.writable){p.write(_createHttpHeader(`HTTP/${e.httpVersion} ${e.statusCode} ${e.statusMessage}`,e.headers));e.on("error",onOutgoingError);e.pipe(p)}else e.resume();if(!r){r=true;t(new Error("Upstream server did not upgrade the connection"))}}}));i.once("upgrade",((t,o,s)=>{o.once("error",onOutgoingError);p.removeListener("error",onSocketError);p.once("error",(()=>{o.end()}));setupSocket(o);if(s&&s.length>0)o.unshift(s);p.write(_createHttpHeader("HTTP/1.1 101 Switching Protocols",t.headers));o.pipe(p).pipe(o);r=true;e(o)}));i.end();function onSocketError(e){i.destroy();if(!r){r=true;t(e)}}function onOutgoingError(e){p.end();if(!r){r=true;t(e)}}}))}function _buildTargetURL(e,t=false){const r=t?"https":"http";if(e.socketPath){const t=new URL(`${r}://unix`);t.socketPath=e.socketPath;return t}return new URL(`${r}://${e.host||"localhost"}${e.port?`:${e.port}`:""}`)}function _createHttpHeader(e,t){let r=e;for(const e of Object.keys(t)){const o=t[e];if(o===void 0)continue;if(Array.isArray(o))for(const t of o)r+=`\r\n${e}: ${t}`;else r+=`\r\n${e}: ${o}`}return`${r}\r\n\r\n`}}};var t={};function __nccwpck_require__(r){var o=t[r];if(o!==undefined){return o.exports}var s=t[r]={exports:{}};var n=true;try{e[r](s,s.exports,__nccwpck_require__);n=false}finally{if(n)delete t[r]}return s.exports}(()=>{__nccwpck_require__.d=(e,t)=>{for(var r in t){if(__nccwpck_require__.o(t,r)&&!__nccwpck_require__.o(e,r)){Object.defineProperty(e,r,{enumerable:true,get:t[r]})}}}})();(()=>{__nccwpck_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)})();(()=>{__nccwpck_require__.r=e=>{if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}})();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(691);module.exports=r})(); |
| MIT License | ||
| Copyright (c) Pooya Parsa <pooya@pi0.io> | ||
| 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. | ||
| ---- | ||
| Based on http-party/node-http-proxy (9b96cd7) | ||
| Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the 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. |
| {"name":"httpxy","main":"index.js","license":"MIT"} |
| export function getRequestInsightKind(insight) { | ||
| return insight.kind ?? 'request'; | ||
| } | ||
| export function getRequestInsightKey(insight) { | ||
| return `${getRequestInsightKind(insight)}:${insight.requestId}`; | ||
| } | ||
| //# sourceMappingURL=request-insights.js.map |
| {"version":3,"sources":["../../../../src/shared/lib/request-insights.ts"],"sourcesContent":["export type RequestInsightKind = 'request' | 'instant-insights'\n\nexport type RequestInsightIdentity = {\n requestId: string\n kind?: RequestInsightKind\n}\n\nexport function getRequestInsightKind(\n insight: Pick<RequestInsightIdentity, 'kind'>\n): RequestInsightKind {\n return insight.kind ?? 'request'\n}\n\nexport function getRequestInsightKey(insight: RequestInsightIdentity): string {\n return `${getRequestInsightKind(insight)}:${insight.requestId}`\n}\n"],"names":["getRequestInsightKind","insight","kind","getRequestInsightKey","requestId"],"mappings":"AAOA,OAAO,SAASA,sBACdC,OAA6C;IAE7C,OAAOA,QAAQC,IAAI,IAAI;AACzB;AAEA,OAAO,SAASC,qBAAqBF,OAA+B;IAClE,OAAO,GAAGD,sBAAsBC,SAAS,CAAC,EAAEA,QAAQG,SAAS,EAAE;AACjE","ignoreList":[0]} |
| export type RequestInsightKind = 'request' | 'instant-insights'; | ||
| export type RequestInsightIdentity = { | ||
| requestId: string; | ||
| kind?: RequestInsightKind; | ||
| }; | ||
| export declare function getRequestInsightKind(insight: Pick<RequestInsightIdentity, 'kind'>): RequestInsightKind; | ||
| export declare function getRequestInsightKey(insight: RequestInsightIdentity): string; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { | ||
| value: true | ||
| }); | ||
| 0 && (module.exports = { | ||
| getRequestInsightKey: null, | ||
| getRequestInsightKind: null | ||
| }); | ||
| function _export(target, all) { | ||
| for(var name in all)Object.defineProperty(target, name, { | ||
| enumerable: true, | ||
| get: all[name] | ||
| }); | ||
| } | ||
| _export(exports, { | ||
| getRequestInsightKey: function() { | ||
| return getRequestInsightKey; | ||
| }, | ||
| getRequestInsightKind: function() { | ||
| return getRequestInsightKind; | ||
| } | ||
| }); | ||
| function getRequestInsightKind(insight) { | ||
| return insight.kind ?? 'request'; | ||
| } | ||
| function getRequestInsightKey(insight) { | ||
| return `${getRequestInsightKind(insight)}:${insight.requestId}`; | ||
| } | ||
| //# sourceMappingURL=request-insights.js.map |
| {"version":3,"sources":["../../../src/shared/lib/request-insights.ts"],"sourcesContent":["export type RequestInsightKind = 'request' | 'instant-insights'\n\nexport type RequestInsightIdentity = {\n requestId: string\n kind?: RequestInsightKind\n}\n\nexport function getRequestInsightKind(\n insight: Pick<RequestInsightIdentity, 'kind'>\n): RequestInsightKind {\n return insight.kind ?? 'request'\n}\n\nexport function getRequestInsightKey(insight: RequestInsightIdentity): string {\n return `${getRequestInsightKind(insight)}:${insight.requestId}`\n}\n"],"names":["getRequestInsightKey","getRequestInsightKind","insight","kind","requestId"],"mappings":";;;;;;;;;;;;;;;IAagBA,oBAAoB;eAApBA;;IANAC,qBAAqB;eAArBA;;;AAAT,SAASA,sBACdC,OAA6C;IAE7C,OAAOA,QAAQC,IAAI,IAAI;AACzB;AAEO,SAASH,qBAAqBE,OAA+B;IAClE,OAAO,GAAGD,sBAAsBC,SAAS,CAAC,EAAEA,QAAQE,SAAS,EAAE;AACjE","ignoreList":[0]} |
@@ -200,2 +200,9 @@ // Import cpu-profile to start profiling early if enabled | ||
| '**/next/dist/server/lib/route-resolver*', | ||
| // The testmode interceptors bundle reads its HTTP parser WASM with a | ||
| // dynamic path, making nft trace the bundle's whole directory. Test | ||
| // proxying is not supported in standalone output, so keep the parser | ||
| // asset (and the license file picked up by the directory glob) out of | ||
| // production traces. | ||
| '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/LICENSE', | ||
| '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/llhttp/**/*', | ||
| 'next/dist/compiled/semver/semver/**/*.js', | ||
@@ -202,0 +209,0 @@ ..._ciinfo.hasNextSupport ? [ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/build/collect-build-traces.ts"],"sourcesContent":["// Import cpu-profile to start profiling early if enabled\nimport '../server/lib/cpu-profile'\nimport { Span } from '../trace'\nimport type { NextConfigComplete } from '../server/config-shared'\n\nimport {\n TRACE_IGNORES,\n type BuildTraceContext,\n getFilesMapFromReasons,\n} from './webpack/plugins/next-trace-entrypoints-plugin'\n\nimport path from 'path'\nimport { resolveCacheHandlerPathToFilesystem } from '../lib/format-dynamic-import-path'\nimport fs from 'fs/promises'\nimport { nonNullable } from '../lib/non-nullable'\nimport * as ciEnvironment from '../server/ci-info'\nimport debugOriginal from 'next/dist/compiled/debug'\nimport picomatch from 'next/dist/compiled/picomatch'\nimport { defaultOverrides } from '../server/require-hook'\nimport { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport isError from '../lib/is-error'\nimport type { NodeFileTraceReasons } from '@vercel/nft'\nimport type { RoutesUsingEdgeRuntime } from './utils'\n\nconst debug = debugOriginal('next:build:build-traces')\n\nexport const makeIgnoreFn = (root: string, ignores: string[]) => {\n // pre compile the ignore globs\n const isMatch = picomatch(ignores, {\n contains: true,\n dot: true,\n })\n\n return (pathname: string) => {\n if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {\n return true\n }\n\n return isMatch(pathname)\n }\n}\n\nfunction shouldIgnore(\n file: string,\n serverIgnoreFn: (file: string) => boolean,\n reasons: NodeFileTraceReasons,\n cachedIgnoreFiles: Map<string, boolean>,\n children: Set<string> = new Set()\n) {\n if (cachedIgnoreFiles.has(file)) {\n return cachedIgnoreFiles.get(file)\n }\n\n if (serverIgnoreFn(file)) {\n cachedIgnoreFiles.set(file, true)\n return true\n }\n children.add(file)\n\n const reason = reasons.get(file)\n if (!reason || reason.parents.size === 0 || reason.type.includes('initial')) {\n cachedIgnoreFiles.set(file, false)\n return false\n }\n\n // if all parents are ignored the child file\n // should be ignored as well\n let allParentsIgnored = true\n\n for (const parent of reason.parents.values()) {\n if (!children.has(parent)) {\n children.add(parent)\n if (\n !shouldIgnore(\n parent,\n serverIgnoreFn,\n reasons,\n cachedIgnoreFiles,\n children\n )\n ) {\n allParentsIgnored = false\n break\n }\n }\n }\n\n cachedIgnoreFiles.set(file, allParentsIgnored)\n return allParentsIgnored\n}\n\nexport async function collectBuildTraces({\n dir,\n config,\n distDir,\n edgeRuntimeRoutes,\n staticPages,\n nextBuildSpan = new Span({ name: 'build' }),\n buildTraceContext,\n outputFileTracingRoot,\n}: {\n dir: string\n distDir: string\n staticPages: string[]\n outputFileTracingRoot: string\n // pageInfos is serialized when this function runs in a worker.\n edgeRuntimeRoutes: RoutesUsingEdgeRuntime\n nextBuildSpan?: Span\n config: NextConfigComplete\n buildTraceContext?: BuildTraceContext\n}) {\n const startTime = Date.now()\n debug('starting build traces')\n\n const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } =\n config\n const excludeGlobKeys = Object.keys(outputFileTracingExcludes)\n const includeGlobKeys = Object.keys(outputFileTracingIncludes)\n\n await nextBuildSpan\n .traceChild('node-file-trace-build', {\n isTurbotrace: 'false', // TODO(arlyon): remove this\n })\n .traceAsyncFn(async () => {\n const nextServerTraceOutput = path.join(\n distDir,\n 'next-server.js.nft.json'\n )\n const nextMinimalTraceOutput = path.join(\n distDir,\n 'next-minimal-server.js.nft.json'\n )\n const root = outputFileTracingRoot\n\n // Under standalone mode, we need to trace the extra IPC server and\n // worker files.\n const isStandalone = config.output === 'standalone'\n const sharedEntriesSet = Object.keys(defaultOverrides).map((value) =>\n require.resolve(value, {\n paths: [require.resolve('next/dist/server/require-hook')],\n })\n )\n\n const { cacheHandler, cacheHandlers } = config\n\n // ensure we trace any dependencies needed for custom\n // incremental cache handler\n if (cacheHandler) {\n const resolvedPath = resolveCacheHandlerPathToFilesystem(cacheHandler)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n\n // Under standalone mode, we need to ensure that the cache entry debug\n // handler is traced so it can be copied. This is only used for testing,\n // and is not used in production.\n if (\n process.env.__NEXT_TEST_MODE &&\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n ) {\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS)\n ? process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n : path.join(\n dir,\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n )\n )\n )\n }\n\n if (cacheHandlers) {\n for (const handlerPath of Object.values(cacheHandlers)) {\n if (handlerPath) {\n const resolvedPath =\n resolveCacheHandlerPathToFilesystem(handlerPath)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n }\n }\n\n const serverEntries = [\n ...sharedEntriesSet,\n ...(isStandalone\n ? [\n require.resolve('next/dist/server/lib/start-server'),\n require.resolve('next/dist/server/next'),\n require.resolve('next/dist/server/require-hook'),\n ]\n : []),\n require.resolve('next/dist/server/next-server'),\n ].filter(Boolean) as string[]\n\n const minimalServerEntries = [\n ...sharedEntriesSet,\n require.resolve('next/dist/compiled/next-server/server.runtime.prod'),\n ].filter(Boolean)\n\n const additionalIgnores = new Set<string>()\n\n for (const glob of excludeGlobKeys) {\n if (picomatch(glob)('next-server')) {\n outputFileTracingExcludes[glob].forEach((exclude) => {\n additionalIgnores.add(exclude)\n })\n }\n }\n\n const sharedIgnores = [\n '**/next/dist/compiled/next-server/**/*.dev.js',\n ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']),\n '**/next/dist/compiled/webpack/*',\n '**/node_modules/webpack5/**/*',\n '**/next/dist/server/lib/route-resolver*',\n 'next/dist/compiled/semver/semver/**/*.js',\n\n ...(ciEnvironment.hasNextSupport\n ? [\n // only ignore image-optimizer code when\n // this is being handled outside of next-server\n '**/next/dist/server/image-optimizer.js',\n ]\n : []),\n\n ...(isStandalone ? [] : TRACE_IGNORES),\n ...additionalIgnores,\n ]\n\n const sharedIgnoresFn = makeIgnoreFn(root, sharedIgnores)\n\n const serverIgnores = [\n ...sharedIgnores,\n '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',\n '**/*.d.ts',\n '**/*.map',\n '**/next/dist/pages/**/*',\n ...(ciEnvironment.hasNextSupport\n ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']\n : []),\n ].filter(nonNullable)\n const serverIgnoreFn = makeIgnoreFn(root, serverIgnores)\n\n const minimalServerIgnores = [\n ...serverIgnores,\n '**/next/dist/compiled/edge-runtime/**/*',\n '**/next/dist/server/web/sandbox/**/*',\n '**/next/dist/server/post-process.js',\n ]\n const minimalServerIgnoreFn = makeIgnoreFn(root, minimalServerIgnores)\n\n const routesIgnores = [\n ...sharedIgnores,\n // server chunks are provided via next-trace-entrypoints-plugin plugin\n // as otherwise all chunks are traced here and included for all pages\n // whether they are needed or not\n '**/.next/server/chunks/**',\n '**/next/dist/server/post-process.js',\n ].filter(nonNullable)\n\n const routeIgnoreFn = makeIgnoreFn(root, routesIgnores)\n\n const serverTracedFiles = new Set<string>()\n const minimalServerTracedFiles = new Set<string>()\n\n function addToTracedFiles(base: string, file: string, dest: Set<string>) {\n dest.add(\n path.relative(distDir, path.join(base, file)).replace(/\\\\/g, '/')\n )\n }\n\n if (isStandalone) {\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/processChild'),\n serverTracedFiles\n )\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/threadChild'),\n serverTracedFiles\n )\n }\n\n {\n const chunksToTrace: string[] = [\n ...(buildTraceContext?.chunksTrace?.action.input || []),\n ...serverEntries,\n ...minimalServerEntries,\n ]\n const result = await nodeFileTrace(chunksToTrace, {\n base: outputFileTracingRoot,\n processCwd: dir,\n mixedModules: true,\n moduleSyncCatchall: true,\n async readFile(p) {\n try {\n return await fs.readFile(p, 'utf8')\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'EISDIR')) {\n // since tracing runs in parallel with static generation server\n // files might be removed from that step so tolerate ENOENT\n // errors gracefully\n return ''\n }\n throw e\n }\n },\n async readlink(p) {\n try {\n return await fs.readlink(p)\n } catch (e) {\n if (\n isError(e) &&\n (e.code === 'EINVAL' ||\n e.code === 'ENOENT' ||\n e.code === 'UNKNOWN')\n ) {\n return null\n }\n throw e\n }\n },\n async stat(p) {\n try {\n return await fs.stat(p)\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) {\n return null\n }\n throw e\n }\n },\n // handle shared ignores at top-level as it\n // avoids over-tracing when we don't need to\n // and speeds up total trace time\n ignore(p) {\n if (sharedIgnoresFn(p)) {\n return true\n }\n\n // if a chunk is attempting to be traced that isn't\n // in our initial list we need to ignore it to prevent\n // over tracing as webpack needs to be the source of\n // truth for which chunks should be included for each entry\n if (\n p.includes('.next/server/chunks') &&\n !chunksToTrace.includes(path.join(outputFileTracingRoot, p))\n ) {\n return true\n }\n return false\n },\n })\n const reasons = result.reasons\n const fileList = result.fileList\n for (const file of result.esmFileList) {\n fileList.add(file)\n }\n\n const parentFilesMap = getFilesMapFromReasons(fileList, reasons)\n const cachedLookupIgnore = new Map<string, boolean>()\n const cachedLookupIgnoreMinimal = new Map<string, boolean>()\n\n for (const [entries, tracedFiles] of [\n [serverEntries, serverTracedFiles],\n [minimalServerEntries, minimalServerTracedFiles],\n ] as Array<[string[], Set<string>]>) {\n for (const file of entries) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n tracedFiles.add(path.relative(distDir, file).replace(/\\\\/g, '/'))\n\n for (const curFile of curFiles || []) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n\n if (\n !shouldIgnore(\n curFile,\n tracedFiles === minimalServerTracedFiles\n ? minimalServerIgnoreFn\n : serverIgnoreFn,\n reasons,\n tracedFiles === minimalServerTracedFiles\n ? cachedLookupIgnoreMinimal\n : cachedLookupIgnore\n )\n ) {\n tracedFiles.add(\n path.relative(distDir, filePath).replace(/\\\\/g, '/')\n )\n }\n }\n }\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n const cachedLookupIgnoreRoutes = new Map<string, boolean>()\n\n await Promise.all(\n [\n ...(entryNameFilesMap\n ? Object.entries(entryNameFilesMap)\n : new Map()),\n ].map(async ([entryName, entryNameFiles]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(route.substring('app'.length))\n }\n if (isPages) {\n route = normalizePagePath(route.substring('pages'.length))\n }\n\n // we don't need to trace for automatically statically optimized\n // pages as they don't have server bundles, note there is\n // the caveat with flying shuttle mode as it needs this for\n // detecting changed entries\n if (staticPages.includes(route)) {\n return\n }\n const entryOutputPath = path.join(\n distDir,\n 'server',\n `${entryName}.js`\n )\n const traceOutputPath = `${entryOutputPath}.nft.json`\n const existingTrace = JSON.parse(\n await fs.readFile(traceOutputPath, 'utf8')\n ) as {\n version: number\n files: string[]\n fileHashes: Record<string, string>\n }\n const traceOutputDir = path.dirname(traceOutputPath)\n const curTracedFiles = new Set<string>()\n\n for (const file of [...entryNameFiles, entryOutputPath]) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n for (const curFile of curFiles || []) {\n if (\n !shouldIgnore(\n curFile,\n routeIgnoreFn,\n reasons,\n cachedLookupIgnoreRoutes\n )\n ) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n const outputFile = path\n .relative(traceOutputDir, filePath)\n .replace(/\\\\/g, '/')\n curTracedFiles.add(outputFile)\n }\n }\n }\n\n for (const file of existingTrace.files || []) {\n curTracedFiles.add(file)\n }\n\n await fs.writeFile(\n traceOutputPath,\n JSON.stringify({\n ...existingTrace,\n files: [...curTracedFiles].sort(),\n })\n )\n })\n )\n }\n\n const moduleTypes = ['app-page', 'pages']\n\n for (const type of moduleTypes) {\n const modulePath = require.resolve(\n `next/dist/server/route-modules/${type}/module.compiled`\n )\n const relativeModulePath = path.relative(root, modulePath)\n\n const contextDir = path.join(\n path.dirname(modulePath),\n 'vendored',\n 'contexts'\n )\n\n for (const item of await fs.readdir(contextDir)) {\n const itemPath = path.relative(root, path.join(contextDir, item))\n if (!serverIgnoreFn(itemPath)) {\n addToTracedFiles(root, itemPath, serverTracedFiles)\n addToTracedFiles(root, itemPath, minimalServerTracedFiles)\n }\n }\n addToTracedFiles(root, relativeModulePath, serverTracedFiles)\n addToTracedFiles(root, relativeModulePath, minimalServerTracedFiles)\n }\n\n const serverTracedFilesSorted = Array.from(serverTracedFiles)\n serverTracedFilesSorted.sort()\n const minimalServerTracedFilesSorted = Array.from(\n minimalServerTracedFiles\n )\n minimalServerTracedFilesSorted.sort()\n\n await Promise.all([\n fs.writeFile(\n nextServerTraceOutput,\n JSON.stringify({\n version: 1,\n files: serverTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n fs.writeFile(\n nextMinimalTraceOutput,\n JSON.stringify({\n version: 1,\n files: minimalServerTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n ])\n })\n\n // apply outputFileTracingIncludes/outputFileTracingExcludes after runTurbotrace\n const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes')\n await includeExcludeSpan.traceAsyncFn(async () => {\n const globOrig =\n require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')\n const glob = (pattern: string): Promise<string[]> => {\n return new Promise((resolve, reject) => {\n globOrig(\n pattern,\n { cwd: dir, nodir: true, dot: true },\n (err, files) => {\n if (err) {\n return reject(err)\n }\n resolve(files)\n }\n )\n })\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n await Promise.all(\n [\n ...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),\n ].map(async ([entryName]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(entryName)\n }\n if (isPages) {\n route = normalizePagePath(entryName)\n }\n\n if (staticPages.includes(route)) {\n return\n }\n\n // edge routes have no trace files\n if (edgeRuntimeRoutes.hasOwnProperty(route)) {\n return\n }\n\n const combinedIncludes = new Set<string>()\n const combinedExcludes = new Set<string>()\n for (const curGlob of includeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const include of outputFileTracingIncludes[curGlob]) {\n combinedIncludes.add(include.replace(/\\\\/g, '/'))\n }\n }\n }\n\n for (const curGlob of excludeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const exclude of outputFileTracingExcludes[curGlob]) {\n combinedExcludes.add(exclude)\n }\n }\n }\n\n if (!combinedIncludes?.size && !combinedExcludes?.size) {\n return\n }\n\n const traceFile = path.join(\n distDir,\n `server`,\n `${entryName}.js.nft.json`\n )\n const pageDir = path.dirname(traceFile)\n const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8'))\n const includes: string[] = []\n const resolvedTraceIncludes = new Map<string, string[]>()\n\n if (combinedIncludes?.size) {\n await Promise.all(\n [...combinedIncludes].map(async (includeGlob) => {\n const results = await glob(includeGlob)\n const resolvedInclude = resolvedTraceIncludes.get(\n includeGlob\n ) || [\n ...results.map((file) => {\n return path.relative(pageDir, path.join(dir, file))\n }),\n ]\n includes.push(...resolvedInclude)\n resolvedTraceIncludes.set(includeGlob, resolvedInclude)\n })\n )\n }\n const combined = new Set([...traceContent.files, ...includes])\n\n if (combinedExcludes?.size) {\n const resolvedGlobs = [...combinedExcludes].map((exclude) =>\n path.join(dir, exclude)\n )\n\n // pre compile before forEach\n const isMatch = picomatch(resolvedGlobs, {\n dot: true,\n contains: true,\n })\n\n combined.forEach((file) => {\n if (isMatch(path.join(pageDir, file))) {\n combined.delete(file)\n }\n })\n }\n\n // overwrite trace file with custom includes/excludes\n await fs.writeFile(\n traceFile,\n JSON.stringify({\n version: traceContent.version,\n files: [...combined],\n })\n )\n })\n )\n })\n\n debug(`finished build tracing ${Date.now() - startTime}ms`)\n}\n"],"names":["collectBuildTraces","makeIgnoreFn","debug","debugOriginal","root","ignores","isMatch","picomatch","contains","dot","pathname","path","isAbsolute","startsWith","shouldIgnore","file","serverIgnoreFn","reasons","cachedIgnoreFiles","children","Set","has","get","set","add","reason","parents","size","type","includes","allParentsIgnored","parent","values","dir","config","distDir","edgeRuntimeRoutes","staticPages","nextBuildSpan","Span","name","buildTraceContext","outputFileTracingRoot","startTime","Date","now","outputFileTracingIncludes","outputFileTracingExcludes","excludeGlobKeys","Object","keys","includeGlobKeys","traceChild","isTurbotrace","traceAsyncFn","nextServerTraceOutput","join","nextMinimalTraceOutput","isStandalone","output","sharedEntriesSet","defaultOverrides","map","value","require","resolve","paths","cacheHandler","cacheHandlers","resolvedPath","resolveCacheHandlerPathToFilesystem","push","process","env","__NEXT_TEST_MODE","NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS","handlerPath","serverEntries","filter","Boolean","minimalServerEntries","additionalIgnores","glob","forEach","exclude","sharedIgnores","ciEnvironment","hasNextSupport","TRACE_IGNORES","sharedIgnoresFn","serverIgnores","nonNullable","minimalServerIgnores","minimalServerIgnoreFn","routesIgnores","routeIgnoreFn","serverTracedFiles","minimalServerTracedFiles","addToTracedFiles","base","dest","relative","replace","chunksToTrace","chunksTrace","action","input","result","nodeFileTrace","processCwd","mixedModules","moduleSyncCatchall","readFile","p","fs","e","isError","code","readlink","stat","ignore","fileList","esmFileList","parentFilesMap","getFilesMapFromReasons","cachedLookupIgnore","Map","cachedLookupIgnoreMinimal","entries","tracedFiles","curFiles","curFile","filePath","entryNameFilesMap","cachedLookupIgnoreRoutes","Promise","all","entryName","entryNameFiles","isApp","isPages","route","normalizeAppPath","substring","length","normalizePagePath","entryOutputPath","traceOutputPath","existingTrace","JSON","parse","traceOutputDir","dirname","curTracedFiles","outputFile","files","writeFile","stringify","sort","moduleTypes","modulePath","relativeModulePath","contextDir","item","readdir","itemPath","serverTracedFilesSorted","Array","from","minimalServerTracedFilesSorted","version","includeExcludeSpan","globOrig","pattern","reject","cwd","nodir","err","hasOwnProperty","combinedIncludes","combinedExcludes","curGlob","include","traceFile","pageDir","traceContent","resolvedTraceIncludes","includeGlob","results","resolvedInclude","combined","resolvedGlobs","delete"],"mappings":"AAAA,yDAAyD;;;;;;;;;;;;;;;;IA6FnCA,kBAAkB;eAAlBA;;IAjETC,YAAY;eAAZA;;;QA3BN;uBACc;4CAOd;6DAEU;yCACmC;iEACrC;6BACa;gEACG;8DACL;kEACJ;6BACW;qBACH;mCACI;0BACD;gEACb;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIpB,MAAMC,QAAQC,IAAAA,cAAa,EAAC;AAErB,MAAMF,eAAe,CAACG,MAAcC;IACzC,+BAA+B;IAC/B,MAAMC,UAAUC,IAAAA,kBAAS,EAACF,SAAS;QACjCG,UAAU;QACVC,KAAK;IACP;IAEA,OA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AS,EAACwL,eAAe;oBACvCtL,KAAK;oBACLD,UAAU;gBACZ;gBAEAsL,SAAS3G,OAAO,CAAC,CAACpE;oBAChB,IAAIT,QAAQK,aAAI,CAAC6C,IAAI,CAACgI,SAASzK,QAAQ;wBACrC+K,SAASE,MAAM,CAACjL;oBAClB;gBACF;YACF;YAEA,qDAAqD;YACrD,MAAMmG,iBAAE,CAAC0C,SAAS,CAChB2B,WACAlC,KAAKQ,SAAS,CAAC;gBACba,SAASe,aAAaf,OAAO;gBAC7Bf,OAAO;uBAAImC;iBAAS;YACtB;QAEJ;IAEJ;IAEA5L,MAAM,CAAC,uBAAuB,EAAE0C,KAAKC,GAAG,KAAKF,UAAU,EAAE,CAAC;AAC5D","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/build/collect-build-traces.ts"],"sourcesContent":["// Import cpu-profile to start profiling early if enabled\nimport '../server/lib/cpu-profile'\nimport { Span } from '../trace'\nimport type { NextConfigComplete } from '../server/config-shared'\n\nimport {\n TRACE_IGNORES,\n type BuildTraceContext,\n getFilesMapFromReasons,\n} from './webpack/plugins/next-trace-entrypoints-plugin'\n\nimport path from 'path'\nimport { resolveCacheHandlerPathToFilesystem } from '../lib/format-dynamic-import-path'\nimport fs from 'fs/promises'\nimport { nonNullable } from '../lib/non-nullable'\nimport * as ciEnvironment from '../server/ci-info'\nimport debugOriginal from 'next/dist/compiled/debug'\nimport picomatch from 'next/dist/compiled/picomatch'\nimport { defaultOverrides } from '../server/require-hook'\nimport { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport isError from '../lib/is-error'\nimport type { NodeFileTraceReasons } from '@vercel/nft'\nimport type { RoutesUsingEdgeRuntime } from './utils'\n\nconst debug = debugOriginal('next:build:build-traces')\n\nexport const makeIgnoreFn = (root: string, ignores: string[]) => {\n // pre compile the ignore globs\n const isMatch = picomatch(ignores, {\n contains: true,\n dot: true,\n })\n\n return (pathname: string) => {\n if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {\n return true\n }\n\n return isMatch(pathname)\n }\n}\n\nfunction shouldIgnore(\n file: string,\n serverIgnoreFn: (file: string) => boolean,\n reasons: NodeFileTraceReasons,\n cachedIgnoreFiles: Map<string, boolean>,\n children: Set<string> = new Set()\n) {\n if (cachedIgnoreFiles.has(file)) {\n return cachedIgnoreFiles.get(file)\n }\n\n if (serverIgnoreFn(file)) {\n cachedIgnoreFiles.set(file, true)\n return true\n }\n children.add(file)\n\n const reason = reasons.get(file)\n if (!reason || reason.parents.size === 0 || reason.type.includes('initial')) {\n cachedIgnoreFiles.set(file, false)\n return false\n }\n\n // if all parents are ignored the child file\n // should be ignored as well\n let allParentsIgnored = true\n\n for (const parent of reason.parents.values()) {\n if (!children.has(parent)) {\n children.add(parent)\n if (\n !shouldIgnore(\n parent,\n serverIgnoreFn,\n reasons,\n cachedIgnoreFiles,\n children\n )\n ) {\n allParentsIgnored = false\n break\n }\n }\n }\n\n cachedIgnoreFiles.set(file, allParentsIgnored)\n return allParentsIgnored\n}\n\nexport async function collectBuildTraces({\n dir,\n config,\n distDir,\n edgeRuntimeRoutes,\n staticPages,\n nextBuildSpan = new Span({ name: 'build' }),\n buildTraceContext,\n outputFileTracingRoot,\n}: {\n dir: string\n distDir: string\n staticPages: string[]\n outputFileTracingRoot: string\n // pageInfos is serialized when this function runs in a worker.\n edgeRuntimeRoutes: RoutesUsingEdgeRuntime\n nextBuildSpan?: Span\n config: NextConfigComplete\n buildTraceContext?: BuildTraceContext\n}) {\n const startTime = Date.now()\n debug('starting build traces')\n\n const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } =\n config\n const excludeGlobKeys = Object.keys(outputFileTracingExcludes)\n const includeGlobKeys = Object.keys(outputFileTracingIncludes)\n\n await nextBuildSpan\n .traceChild('node-file-trace-build', {\n isTurbotrace: 'false', // TODO(arlyon): remove this\n })\n .traceAsyncFn(async () => {\n const nextServerTraceOutput = path.join(\n distDir,\n 'next-server.js.nft.json'\n )\n const nextMinimalTraceOutput = path.join(\n distDir,\n 'next-minimal-server.js.nft.json'\n )\n const root = outputFileTracingRoot\n\n // Under standalone mode, we need to trace the extra IPC server and\n // worker files.\n const isStandalone = config.output === 'standalone'\n const sharedEntriesSet = Object.keys(defaultOverrides).map((value) =>\n require.resolve(value, {\n paths: [require.resolve('next/dist/server/require-hook')],\n })\n )\n\n const { cacheHandler, cacheHandlers } = config\n\n // ensure we trace any dependencies needed for custom\n // incremental cache handler\n if (cacheHandler) {\n const resolvedPath = resolveCacheHandlerPathToFilesystem(cacheHandler)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n\n // Under standalone mode, we need to ensure that the cache entry debug\n // handler is traced so it can be copied. This is only used for testing,\n // and is not used in production.\n if (\n process.env.__NEXT_TEST_MODE &&\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n ) {\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS)\n ? process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n : path.join(\n dir,\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n )\n )\n )\n }\n\n if (cacheHandlers) {\n for (const handlerPath of Object.values(cacheHandlers)) {\n if (handlerPath) {\n const resolvedPath =\n resolveCacheHandlerPathToFilesystem(handlerPath)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n }\n }\n\n const serverEntries = [\n ...sharedEntriesSet,\n ...(isStandalone\n ? [\n require.resolve('next/dist/server/lib/start-server'),\n require.resolve('next/dist/server/next'),\n require.resolve('next/dist/server/require-hook'),\n ]\n : []),\n require.resolve('next/dist/server/next-server'),\n ].filter(Boolean) as string[]\n\n const minimalServerEntries = [\n ...sharedEntriesSet,\n require.resolve('next/dist/compiled/next-server/server.runtime.prod'),\n ].filter(Boolean)\n\n const additionalIgnores = new Set<string>()\n\n for (const glob of excludeGlobKeys) {\n if (picomatch(glob)('next-server')) {\n outputFileTracingExcludes[glob].forEach((exclude) => {\n additionalIgnores.add(exclude)\n })\n }\n }\n\n const sharedIgnores = [\n '**/next/dist/compiled/next-server/**/*.dev.js',\n ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']),\n '**/next/dist/compiled/webpack/*',\n '**/node_modules/webpack5/**/*',\n '**/next/dist/server/lib/route-resolver*',\n // The testmode interceptors bundle reads its HTTP parser WASM with a\n // dynamic path, making nft trace the bundle's whole directory. Test\n // proxying is not supported in standalone output, so keep the parser\n // asset (and the license file picked up by the directory glob) out of\n // production traces.\n '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/LICENSE',\n '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/llhttp/**/*',\n 'next/dist/compiled/semver/semver/**/*.js',\n\n ...(ciEnvironment.hasNextSupport\n ? [\n // only ignore image-optimizer code when\n // this is being handled outside of next-server\n '**/next/dist/server/image-optimizer.js',\n ]\n : []),\n\n ...(isStandalone ? [] : TRACE_IGNORES),\n ...additionalIgnores,\n ]\n\n const sharedIgnoresFn = makeIgnoreFn(root, sharedIgnores)\n\n const serverIgnores = [\n ...sharedIgnores,\n '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',\n '**/*.d.ts',\n '**/*.map',\n '**/next/dist/pages/**/*',\n ...(ciEnvironment.hasNextSupport\n ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']\n : []),\n ].filter(nonNullable)\n const serverIgnoreFn = makeIgnoreFn(root, serverIgnores)\n\n const minimalServerIgnores = [\n ...serverIgnores,\n '**/next/dist/compiled/edge-runtime/**/*',\n '**/next/dist/server/web/sandbox/**/*',\n '**/next/dist/server/post-process.js',\n ]\n const minimalServerIgnoreFn = makeIgnoreFn(root, minimalServerIgnores)\n\n const routesIgnores = [\n ...sharedIgnores,\n // server chunks are provided via next-trace-entrypoints-plugin plugin\n // as otherwise all chunks are traced here and included for all pages\n // whether they are needed or not\n '**/.next/server/chunks/**',\n '**/next/dist/server/post-process.js',\n ].filter(nonNullable)\n\n const routeIgnoreFn = makeIgnoreFn(root, routesIgnores)\n\n const serverTracedFiles = new Set<string>()\n const minimalServerTracedFiles = new Set<string>()\n\n function addToTracedFiles(base: string, file: string, dest: Set<string>) {\n dest.add(\n path.relative(distDir, path.join(base, file)).replace(/\\\\/g, '/')\n )\n }\n\n if (isStandalone) {\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/processChild'),\n serverTracedFiles\n )\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/threadChild'),\n serverTracedFiles\n )\n }\n\n {\n const chunksToTrace: string[] = [\n ...(buildTraceContext?.chunksTrace?.action.input || []),\n ...serverEntries,\n ...minimalServerEntries,\n ]\n const result = await nodeFileTrace(chunksToTrace, {\n base: outputFileTracingRoot,\n processCwd: dir,\n mixedModules: true,\n moduleSyncCatchall: true,\n async readFile(p) {\n try {\n return await fs.readFile(p, 'utf8')\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'EISDIR')) {\n // since tracing runs in parallel with static generation server\n // files might be removed from that step so tolerate ENOENT\n // errors gracefully\n return ''\n }\n throw e\n }\n },\n async readlink(p) {\n try {\n return await fs.readlink(p)\n } catch (e) {\n if (\n isError(e) &&\n (e.code === 'EINVAL' ||\n e.code === 'ENOENT' ||\n e.code === 'UNKNOWN')\n ) {\n return null\n }\n throw e\n }\n },\n async stat(p) {\n try {\n return await fs.stat(p)\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) {\n return null\n }\n throw e\n }\n },\n // handle shared ignores at top-level as it\n // avoids over-tracing when we don't need to\n // and speeds up total trace time\n ignore(p) {\n if (sharedIgnoresFn(p)) {\n return true\n }\n\n // if a chunk is attempting to be traced that isn't\n // in our initial list we need to ignore it to prevent\n // over tracing as webpack needs to be the source of\n // truth for which chunks should be included for each entry\n if (\n p.includes('.next/server/chunks') &&\n !chunksToTrace.includes(path.join(outputFileTracingRoot, p))\n ) {\n return true\n }\n return false\n },\n })\n const reasons = result.reasons\n const fileList = result.fileList\n for (const file of result.esmFileList) {\n fileList.add(file)\n }\n\n const parentFilesMap = getFilesMapFromReasons(fileList, reasons)\n const cachedLookupIgnore = new Map<string, boolean>()\n const cachedLookupIgnoreMinimal = new Map<string, boolean>()\n\n for (const [entries, tracedFiles] of [\n [serverEntries, serverTracedFiles],\n [minimalServerEntries, minimalServerTracedFiles],\n ] as Array<[string[], Set<string>]>) {\n for (const file of entries) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n tracedFiles.add(path.relative(distDir, file).replace(/\\\\/g, '/'))\n\n for (const curFile of curFiles || []) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n\n if (\n !shouldIgnore(\n curFile,\n tracedFiles === minimalServerTracedFiles\n ? minimalServerIgnoreFn\n : serverIgnoreFn,\n reasons,\n tracedFiles === minimalServerTracedFiles\n ? cachedLookupIgnoreMinimal\n : cachedLookupIgnore\n )\n ) {\n tracedFiles.add(\n path.relative(distDir, filePath).replace(/\\\\/g, '/')\n )\n }\n }\n }\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n const cachedLookupIgnoreRoutes = new Map<string, boolean>()\n\n await Promise.all(\n [\n ...(entryNameFilesMap\n ? Object.entries(entryNameFilesMap)\n : new Map()),\n ].map(async ([entryName, entryNameFiles]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(route.substring('app'.length))\n }\n if (isPages) {\n route = normalizePagePath(route.substring('pages'.length))\n }\n\n // we don't need to trace for automatically statically optimized\n // pages as they don't have server bundles, note there is\n // the caveat with flying shuttle mode as it needs this for\n // detecting changed entries\n if (staticPages.includes(route)) {\n return\n }\n const entryOutputPath = path.join(\n distDir,\n 'server',\n `${entryName}.js`\n )\n const traceOutputPath = `${entryOutputPath}.nft.json`\n const existingTrace = JSON.parse(\n await fs.readFile(traceOutputPath, 'utf8')\n ) as {\n version: number\n files: string[]\n fileHashes: Record<string, string>\n }\n const traceOutputDir = path.dirname(traceOutputPath)\n const curTracedFiles = new Set<string>()\n\n for (const file of [...entryNameFiles, entryOutputPath]) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n for (const curFile of curFiles || []) {\n if (\n !shouldIgnore(\n curFile,\n routeIgnoreFn,\n reasons,\n cachedLookupIgnoreRoutes\n )\n ) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n const outputFile = path\n .relative(traceOutputDir, filePath)\n .replace(/\\\\/g, '/')\n curTracedFiles.add(outputFile)\n }\n }\n }\n\n for (const file of existingTrace.files || []) {\n curTracedFiles.add(file)\n }\n\n await fs.writeFile(\n traceOutputPath,\n JSON.stringify({\n ...existingTrace,\n files: [...curTracedFiles].sort(),\n })\n )\n })\n )\n }\n\n const moduleTypes = ['app-page', 'pages']\n\n for (const type of moduleTypes) {\n const modulePath = require.resolve(\n `next/dist/server/route-modules/${type}/module.compiled`\n )\n const relativeModulePath = path.relative(root, modulePath)\n\n const contextDir = path.join(\n path.dirname(modulePath),\n 'vendored',\n 'contexts'\n )\n\n for (const item of await fs.readdir(contextDir)) {\n const itemPath = path.relative(root, path.join(contextDir, item))\n if (!serverIgnoreFn(itemPath)) {\n addToTracedFiles(root, itemPath, serverTracedFiles)\n addToTracedFiles(root, itemPath, minimalServerTracedFiles)\n }\n }\n addToTracedFiles(root, relativeModulePath, serverTracedFiles)\n addToTracedFiles(root, relativeModulePath, minimalServerTracedFiles)\n }\n\n const serverTracedFilesSorted = Array.from(serverTracedFiles)\n serverTracedFilesSorted.sort()\n const minimalServerTracedFilesSorted = Array.from(\n minimalServerTracedFiles\n )\n minimalServerTracedFilesSorted.sort()\n\n await Promise.all([\n fs.writeFile(\n nextServerTraceOutput,\n JSON.stringify({\n version: 1,\n files: serverTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n fs.writeFile(\n nextMinimalTraceOutput,\n JSON.stringify({\n version: 1,\n files: minimalServerTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n ])\n })\n\n // apply outputFileTracingIncludes/outputFileTracingExcludes after runTurbotrace\n const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes')\n await includeExcludeSpan.traceAsyncFn(async () => {\n const globOrig =\n require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')\n const glob = (pattern: string): Promise<string[]> => {\n return new Promise((resolve, reject) => {\n globOrig(\n pattern,\n { cwd: dir, nodir: true, dot: true },\n (err, files) => {\n if (err) {\n return reject(err)\n }\n resolve(files)\n }\n )\n })\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n await Promise.all(\n [\n ...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),\n ].map(async ([entryName]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(entryName)\n }\n if (isPages) {\n route = normalizePagePath(entryName)\n }\n\n if (staticPages.includes(route)) {\n return\n }\n\n // edge routes have no trace files\n if (edgeRuntimeRoutes.hasOwnProperty(route)) {\n return\n }\n\n const combinedIncludes = new Set<string>()\n const combinedExcludes = new Set<string>()\n for (const curGlob of includeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const include of outputFileTracingIncludes[curGlob]) {\n combinedIncludes.add(include.replace(/\\\\/g, '/'))\n }\n }\n }\n\n for (const curGlob of excludeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const exclude of outputFileTracingExcludes[curGlob]) {\n combinedExcludes.add(exclude)\n }\n }\n }\n\n if (!combinedIncludes?.size && !combinedExcludes?.size) {\n return\n }\n\n const traceFile = path.join(\n distDir,\n `server`,\n `${entryName}.js.nft.json`\n )\n const pageDir = path.dirname(traceFile)\n const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8'))\n const includes: string[] = []\n const resolvedTraceIncludes = new Map<string, string[]>()\n\n if (combinedIncludes?.size) {\n await Promise.all(\n [...combinedIncludes].map(async (includeGlob) => {\n const results = await glob(includeGlob)\n const resolvedInclude = resolvedTraceIncludes.get(\n includeGlob\n ) || [\n ...results.map((file) => {\n return path.relative(pageDir, path.join(dir, file))\n }),\n ]\n includes.push(...resolvedInclude)\n resolvedTraceIncludes.set(includeGlob, resolvedInclude)\n })\n )\n }\n const combined = new Set([...traceContent.files, ...includes])\n\n if (combinedExcludes?.size) {\n const resolvedGlobs = [...combinedExcludes].map((exclude) =>\n path.join(dir, exclude)\n )\n\n // pre compile before forEach\n const isMatch = picomatch(resolvedGlobs, {\n dot: true,\n contains: true,\n })\n\n combined.forEach((file) => {\n if (isMatch(path.join(pageDir, file))) {\n combined.delete(file)\n }\n })\n }\n\n // overwrite trace file with custom includes/excludes\n await fs.writeFile(\n traceFile,\n JSON.stringify({\n version: traceContent.version,\n files: [...combined],\n })\n )\n })\n )\n })\n\n debug(`finished build tracing ${Date.now() - startTime}ms`)\n}\n"],"names":["collectBuildTraces","makeIgnoreFn","debug","debugOriginal","root","ignores","isMatch","picomatch","contains","dot","pathname","path","isAbsolute","startsWith","shouldIgnore","file","serverIgnoreFn","reasons","cachedIgnoreFiles","children","Set","has","get","set","add","reason","parents","size","type","includes","allParentsIgnored","parent","values","dir","config","distDir","edgeRuntimeRoutes","staticPages","nextBuildSpan","Span","name","buildTraceContext","outputFileTracingRoot","startTime","Date","now","outputFileTracingIncludes","outputFileTracingExcludes","excludeGlobKeys","Object","keys","includeGlobKeys","traceChild","isTurbotrace","traceAsyncFn","nextServerTraceOutput","join","nextMinimalTraceOutput","isStandalone","output","sharedEntriesSet","defaultOverrides","map","value","require","resolve","paths","cacheHandler","cacheHandlers","resolvedPath","resolveCacheHandlerPathToFilesystem","push","process","env","__NEXT_TEST_MODE","NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS","handlerPath","serverEntries","filter","Boolean","minimalServerEntries","additionalIgnores","glob","forEach","exclude","sharedIgnores","ciEnvironment","hasNextSupport","TRACE_IGNORES","sharedIgnoresFn","serverIgnores","nonNullable","minimalServerIgnores","minimalServerIgnoreFn","routesIgnores","routeIgnoreFn","serverTracedFiles","minimalServerTracedFiles","addToTracedFiles","base","dest","relative","replace","chunksToTrace","chunksTrace","action","input","result","nodeFileTrace","processCwd","mixedModules","moduleSyncCatchall","readFile","p","fs","e","isError","code","readlink","stat","ignore","fileList","esmFileList","parentFilesMap","getFilesMapFromReasons","cachedLookupIgnore","Map","cachedLookupIgnoreMinimal","entries","tracedFiles","curFiles","curFile","filePath","entryNameFilesMap","cachedLookupIgnoreRoutes","Promise","all","entryName","entryNameFiles","isApp","isPages","route","normalizeAppPath","substring","length","normalizePagePath","entryOutputPath","traceOutputPath","existingTrace","JSON","parse","traceOutputDir","dirname","curTracedFiles","outputFile","files","writeFile","stringify","sort","moduleTypes","modulePath","relativeModulePath","contextDir","item","readdir","itemPath","serverTracedFilesSorted","Array","from","minimalServerTracedFilesSorted","version","includeExcludeSpan","globOrig","pattern","reject","cwd","nodir","err","hasOwnProperty","combinedIncludes","combinedExcludes","curGlob","include","traceFile","pageDir","traceContent","resolvedTraceIncludes","includeGlob","results","resolvedInclude","combined","resolvedGlobs","delete"],"mappings":"AAAA,yDAAyD;;;;;;;;;;;;;;;;IA6FnCA,kBAAkB;eAAlBA;;IAjETC,YAAY;eAAZA;;;QA3BN;uBACc;4CAOd;6DAEU;yCACmC;iEACrC;6BACa;gEACG;8DACL;kEACJ;6BACW;qBACH;mCACI;0BACD;gEACb;;;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aAAaE;gBACzC;YAEJ;YACA,MAAMC,WAAW,IAAI1K,IAAI;mBAAIqK,aAAa9B,KAAK;mBAAK9H;aAAS;YAE7D,IAAIuJ,oCAAAA,iBAAkBzJ,IAAI,EAAE;gBAC1B,MAAMoK,gBAAgB;uBAAIX;iBAAiB,CAACtH,GAAG,CAAC,CAACsB,UAC/CzE,aAAI,CAAC6C,IAAI,CAACvB,KAAKmD;gBAGjB,6BAA6B;gBAC7B,MAAM9E,UAAUC,IAAAA,kBAAS,EAACwL,eAAe;oBACvCtL,KAAK;oBACLD,UAAU;gBACZ;gBAEAsL,SAAS3G,OAAO,CAAC,CAACpE;oBAChB,IAAIT,QAAQK,aAAI,CAAC6C,IAAI,CAACgI,SAASzK,QAAQ;wBACrC+K,SAASE,MAAM,CAACjL;oBAClB;gBACF;YACF;YAEA,qDAAqD;YACrD,MAAMmG,iBAAE,CAAC0C,SAAS,CAChB2B,WACAlC,KAAKQ,SAAS,CAAC;gBACba,SAASe,aAAaf,OAAO;gBAC7Bf,OAAO;uBAAImC;iBAAS;YACtB;QAEJ;IAEJ;IAEA5L,MAAM,CAAC,uBAAuB,EAAE0C,KAAKC,GAAG,KAAKF,UAAU,EAAE,CAAC;AAC5D","ignoreList":[0]} |
@@ -138,3 +138,3 @@ "use strict"; | ||
| }({}); | ||
| const nextVersion = "16.3.0-canary.97"; | ||
| const nextVersion = "16.3.0-canary.99"; | ||
| const ArchName = (0, _os.arch)(); | ||
@@ -141,0 +141,0 @@ const PlatformName = (0, _os.platform)(); |
@@ -96,3 +96,3 @@ "use strict"; | ||
| isPersistentCachingEnabled: persistentCaching, | ||
| nextVersion: "16.3.0-canary.97" | ||
| nextVersion: "16.3.0-canary.99" | ||
| }, { | ||
@@ -99,0 +99,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode, |
@@ -118,3 +118,3 @@ // Import cpu-profile first to start profiling early if enabled | ||
| deferredEntries: config.experimental.deferredEntries, | ||
| nextVersion: "16.3.0-canary.97" | ||
| nextVersion: "16.3.0-canary.99" | ||
| }; | ||
@@ -121,0 +121,0 @@ const sharedTurboOptions = { |
| 1:"$Sreact.fragment" | ||
| 2:I[87181,["/_next/static/chunks/00qfakp0bmxst.js"],"ClientPageRoot"] | ||
| 3:I[79331,["/_next/static/chunks/00qfakp0bmxst.js","/_next/static/chunks/0umcxbkfjfq.0.js"],"default"] | ||
| 6:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 2:I[52000,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ClientPageRoot"] | ||
| 3:I[79331,["/_next/static/chunks/0~8b6_um3q_ef.js","/_next/static/chunks/08a.k65hua~va.js"],"default"] | ||
| 6:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"OutletBoundary"] | ||
| 7:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","c",{"children":[["$","$L2",null,{"Component":"$3","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@4","$@5"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/08a.k65hua~va.js","async":true}]],["$","$L6",null,{"children":["$","$7",null,{"name":"Next.MetadataOutlet","children":"$@8"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} | ||
| 4:{} | ||
| 5:"$0:rsc:props:children:0:props:serverProvidedParams:params" | ||
| 8:null |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 4:I[87181,["/_next/static/chunks/00qfakp0bmxst.js"],"ClientPageRoot"] | ||
| 5:I[79331,["/_next/static/chunks/00qfakp0bmxst.js","/_next/static/chunks/0umcxbkfjfq.0.js"],"default"] | ||
| 8:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 4:I[52000,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ClientPageRoot"] | ||
| 5:I[79331,["/_next/static/chunks/0~8b6_um3q_ef.js","/_next/static/chunks/08a.k65hua~va.js"],"default"] | ||
| 8:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"OutletBoundary"] | ||
| 9:"$Sreact.suspense" | ||
| b:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"ViewportBoundary"] | ||
| d:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"MetadataBoundary"] | ||
| f:I[43334,["/_next/static/chunks/00qfakp0bmxst.js"],"default",1] | ||
| b:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ViewportBoundary"] | ||
| d:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"MetadataBoundary"] | ||
| f:I[20558,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default",1] | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/0~8b6_um3q_ef.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/08a.k65hua~va.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"BXmF4yXj1dJf2Wut0JJoI"} | ||
| 6:{} | ||
@@ -14,0 +14,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" |
| 1:"$Sreact.fragment" | ||
| 2:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"ViewportBoundary"] | ||
| 3:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"MetadataBoundary"] | ||
| 2:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ViewportBoundary"] | ||
| 3:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"MetadataBoundary"] | ||
| 4:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","h",{"children":[null,["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/0~8b6_um3q_ef.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}},"staleTime":300,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
@@ -1,2 +0,2 @@ | ||
| <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kp3gz-tar6qr.js"/><script src="/_next/static/chunks/0o8czoqls7u7z.js" async=""></script><script src="/_next/static/chunks/0x_ezzus9zvio.js" async=""></script><script src="/_next/static/chunks/turbopack-0htcm_o68u32o.js" async=""></script><script src="/_next/static/chunks/00qfakp0bmxst.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0_853fpryox2z.js"/><script src="/_next/static/chunks/0cdeg.livuop2.js" async=""></script><script src="/_next/static/chunks/0rp--m6md0lzz.js" async=""></script><script src="/_next/static/chunks/turbopack-0zkin_x25qa2w.js" async=""></script><script src="/_next/static/chunks/0~8b6_um3q_ef.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| (function() { | ||
@@ -10,2 +10,2 @@ const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\na:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nc:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"ssoYuJB_kT5Zgw5eY8qfb\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0_853fpryox2z.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[7631,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\"]\n3:I[96635,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\"]\n4:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"ViewportBoundary\"]\na:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"MetadataBoundary\"]\nc:I[20558,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0~8b6_um3q_ef.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"BXmF4yXj1dJf2Wut0JJoI\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 4:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 4:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"OutletBoundary"] | ||
| 5:"$Sreact.suspense" | ||
| 8:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"ViewportBoundary"] | ||
| a:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"MetadataBoundary"] | ||
| c:I[43334,["/_next/static/chunks/00qfakp0bmxst.js"],"default",1] | ||
| 8:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ViewportBoundary"] | ||
| a:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"MetadataBoundary"] | ||
| c:I[20558,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default",1] | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/0~8b6_um3q_ef.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"BXmF4yXj1dJf2Wut0JJoI"} | ||
| d:[] | ||
@@ -12,0 +12,0 @@ 7:"$Wd" |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 4:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 4:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"OutletBoundary"] | ||
| 5:"$Sreact.suspense" | ||
| 8:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"ViewportBoundary"] | ||
| a:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"MetadataBoundary"] | ||
| c:I[43334,["/_next/static/chunks/00qfakp0bmxst.js"],"default",1] | ||
| 8:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ViewportBoundary"] | ||
| a:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"MetadataBoundary"] | ||
| c:I[20558,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default",1] | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"P":null,"c":["","_not-found"],"q":"","i":false,"f":[[["",{"children":["/_not-found",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/0~8b6_um3q_ef.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","forbidden":"$undefined","unauthorized":"$undefined"}]]}],{"children":[["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style","children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style","children":404}],["$","div",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style","children":["$","h2",null,{"style":"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style","children":"This page could not be found."}]}]]}]}]],null,["$","$L4",null,{"children":["$","$5",null,{"name":"Next.MetadataOutlet","children":"$@6"}]}]]}],{},null,false,null]},null,false,"$@7"]},null,false,null],["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L8",null,{"children":"$L9"}],["$","div",null,{"hidden":true,"children":["$","$La",null,{"children":["$","$5",null,{"name":"Next.Metadata","children":"$Lb"}]}]}],null]}],false]],"m":"$undefined","G":["$c",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"BXmF4yXj1dJf2Wut0JJoI"} | ||
| d:[] | ||
@@ -12,0 +12,0 @@ 7:"$Wd" |
| 1:"$Sreact.fragment" | ||
| 2:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"ViewportBoundary"] | ||
| 3:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"MetadataBoundary"] | ||
| 2:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ViewportBoundary"] | ||
| 3:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"MetadataBoundary"] | ||
| 4:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","h",{"children":[["$","meta",null,{"name":"robots","content":"noindex"}],["$","$L2",null,{"children":[["$","meta","0",{"charSet":"utf-8"}],["$","meta","1",{"name":"viewport","content":"width=device-width, initial-scale=1"}]]}],["$","div",null,{"hidden":true,"children":["$","$L3",null,{"children":["$","$4",null,{"name":"Next.Metadata","children":[["$","title","0",{"children":"Next.js Bundle Analyzer"}],["$","meta","1",{"name":"description","content":"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"}]]}]}]}],null]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next"}],["$","script","script-0",{"src":"/_next/static/chunks/0~8b6_um3q_ef.js","async":true}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}],"notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]]}]}]]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
| 1:"$Sreact.fragment" | ||
| 2:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 2:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"OutletBoundary"] | ||
| 3:"$Sreact.suspense" | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","c",{"children":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],null,["$","$L2",null,{"children":["$","$3",null,{"name":"Next.MetadataOutlet","children":"$@4"}]}]]}],"isPartial":false,"staleTime":300,"varyParams":null,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} | ||
| 4:null |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 4:[] | ||
| 0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"rsc":["$","$1","c",{"children":[null,["$","$L2",null,{"parallelRouterKey":"children","template":["$","$L3",null,{}]}]]}],"isPartial":false,"staleTime":300,"varyParams":"$W4","buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"tree":{"name":"","param":null,"prefetchHints":16,"slots":{"children":{"name":"/_not-found","param":null,"prefetchHints":0,"slots":{"children":{"name":"__PAGE__","param":null,"prefetchHints":0,"slots":null}}}}},"staleTime":300,"buildId":"BXmF4yXj1dJf2Wut0JJoI"} |
@@ -1,2 +0,2 @@ | ||
| <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kp3gz-tar6qr.js"/><script src="/_next/static/chunks/0o8czoqls7u7z.js" async=""></script><script src="/_next/static/chunks/0x_ezzus9zvio.js" async=""></script><script src="/_next/static/chunks/turbopack-0htcm_o68u32o.js" async=""></script><script src="/_next/static/chunks/00qfakp0bmxst.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0_853fpryox2z.js"/><script src="/_next/static/chunks/0cdeg.livuop2.js" async=""></script><script src="/_next/static/chunks/0rp--m6md0lzz.js" async=""></script><script src="/_next/static/chunks/turbopack-0zkin_x25qa2w.js" async=""></script><script src="/_next/static/chunks/0~8b6_um3q_ef.js" async=""></script><meta name="robots" content="noindex"/><title>404: This page could not be found.</title><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| (function() { | ||
@@ -10,2 +10,2 @@ const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\na:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nc:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"ssoYuJB_kT5Zgw5eY8qfb\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><div style="font-family:system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji";height:100vh;text-align:center;display:flex;flex-direction:column;align-items:center;justify-content:center"><div><style>body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}</style><h1 class="next-error-h1" style="display:inline-block;margin:0 20px 0 0;padding:0 23px 0 0;font-size:24px;font-weight:500;vertical-align:top;line-height:49px">404</h1><div style="display:inline-block"><h2 style="font-size:14px;font-weight:400;line-height:49px;margin:0">This page could not be found.</h2></div></div></div><!--$--><!--/$--><script src="/_next/static/chunks/0_853fpryox2z.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[7631,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\"]\n3:I[96635,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\"]\n4:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"OutletBoundary\"]\n5:\"$Sreact.suspense\"\n8:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"ViewportBoundary\"]\na:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"MetadataBoundary\"]\nc:I[20558,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"_not-found\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"/_not-found\",{\"children\":[\"__PAGE__\",{}]}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0~8b6_um3q_ef.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[null,[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":\"$undefined\",\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:style\",\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:1:props:style\",\"children\":404}],[\"$\",\"div\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:style\",\"children\":[\"$\",\"h2\",null,{\"style\":\"$0:f:0:1:0:props:children:1:props:children:1:props:children:props:notFound:0:1:props:children:props:children:2:props:children:props:style\",\"children\":\"This page could not be found.\"}]}]]}]}]],null,[\"$\",\"$L4\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@6\"}]}]]}],{},null,false,null]},null,false,\"$@7\"]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[[\"$\",\"meta\",null,{\"name\":\"robots\",\"content\":\"noindex\"}],[\"$\",\"$L8\",null,{\"children\":\"$L9\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$La\",null,{\"children\":[\"$\",\"$5\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Lb\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$c\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"BXmF4yXj1dJf2Wut0JJoI\"}\n"])</script><script>self.__next_f.push([1,"d:[]\n7:\"$Wd\"\n"])</script><script>self.__next_f.push([1,"9:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"6:null\nb:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
@@ -1,2 +0,2 @@ | ||
| <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0kp3gz-tar6qr.js"/><script src="/_next/static/chunks/0o8czoqls7u7z.js" async=""></script><script src="/_next/static/chunks/0x_ezzus9zvio.js" async=""></script><script src="/_next/static/chunks/turbopack-0htcm_o68u32o.js" async=""></script><script src="/_next/static/chunks/00qfakp0bmxst.js" async=""></script><script src="/_next/static/chunks/0umcxbkfjfq.0.js" async=""></script><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| <!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><meta name="viewport" content="width=device-width, initial-scale=1"/><link rel="stylesheet" href="/_next/static/chunks/0i88bcw_h0tc6.css" data-precedence="next"/><link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/0_853fpryox2z.js"/><script src="/_next/static/chunks/0cdeg.livuop2.js" async=""></script><script src="/_next/static/chunks/0rp--m6md0lzz.js" async=""></script><script src="/_next/static/chunks/turbopack-0zkin_x25qa2w.js" async=""></script><script src="/_next/static/chunks/0~8b6_um3q_ef.js" async=""></script><script src="/_next/static/chunks/08a.k65hua~va.js" async=""></script><title>Next.js Bundle Analyzer</title><meta name="description" content="Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis"/><script> | ||
| (function() { | ||
@@ -10,2 +10,2 @@ const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; | ||
| })(); | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0kp3gz-tar6qr.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[32816,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n3:I[78470,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\"]\n4:I[87181,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/00qfakp0bmxst.js\",\"/_next/static/chunks/0umcxbkfjfq.0.js\"],\"default\"]\n8:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"ViewportBoundary\"]\nd:I[74690,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"MetadataBoundary\"]\nf:I[43334,[\"/_next/static/chunks/00qfakp0bmxst.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/00qfakp0bmxst.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0umcxbkfjfq.0.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"ssoYuJB_kT5Zgw5eY8qfb\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> | ||
| </script><script src="/_next/static/chunks/03~yq9q893hmn.js" noModule=""></script></head><body class="font-sans antialiased"><div hidden=""><!--$--><!--/$--></div><main class="h-screen flex flex-col bg-background"><div class="flex-none px-4 py-2 border-b border-border flex items-center gap-3"><div class="flex-1 flex"><div class="flex items-center gap-2 min-w-64 max-w-full"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground h-9 px-4 py-2 flex-grow-1 w-full justify-between font-mono text-sm" role="combobox" aria-expanded="false" disabled="" type="button" aria-haspopup="dialog" aria-controls="radix-_R_lbtb_" data-state="closed"><div class="flex items-center"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader mr-2 inline animate-spin" aria-hidden="true"><path d="M12 2v4"></path><path d="m16.2 7.8 2.9-2.9"></path><path d="M18 12h4"></path><path d="m16.2 16.2 2.9 2.9"></path><path d="M12 18v4"></path><path d="m4.9 19.1 2.9-2.9"></path><path d="M2 12h4"></path><path d="m4.9 4.9 2.9 2.9"></path></svg>Loading routes...</div><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down h-4 w-4 shrink-0 opacity-50" aria-hidden="true"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></div></button></div></div><div class="flex items-center gap-2"></div></div><div class="flex-1 flex min-h-0"><div class="flex-1 min-w-0 p-4 bg-background"><div class="h-full w-full grid grid-cols-12 grid-rows-8 gap-2"><div class="animate-pulse rounded-md bg-muted col-span-5 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-3"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-1"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-4"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-4 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-2 row-span-2"></div><div class="animate-pulse rounded-md bg-muted col-span-3 row-span-2"></div></div></div><button type="button" class="flex-none w-1 bg-border cursor-col-resize transition-colors" disabled="" aria-label="Resize sidebar"></button><div class="flex-none bg-muted border-l border-border overflow-y-auto" style="width:20%"><div class="flex-1 p-3 space-y-4 overflow-y-auto"><div class="animate-pulse rounded-md bg-muted h-4 w-3/4"></div><div class="animate-pulse rounded-md bg-muted h-4 w-full"></div><div class="animate-pulse rounded-md bg-muted h-4 w-5/6"></div><div class="mt-4 space-y-2"><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-full"></div><div class="animate-pulse rounded-md bg-muted h-3 w-4/5"></div></div></div></div></div></main><!--$--><!--/$--><script src="/_next/static/chunks/0_853fpryox2z.js" id="_R_" async=""></script><script>(self.__next_f=self.__next_f||[]).push([0])</script><script>self.__next_f.push([1,"1:\"$Sreact.fragment\"\n2:I[7631,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\"]\n3:I[96635,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\"]\n4:I[52000,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"ClientPageRoot\"]\n5:I[79331,[\"/_next/static/chunks/0~8b6_um3q_ef.js\",\"/_next/static/chunks/08a.k65hua~va.js\"],\"default\"]\n8:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"OutletBoundary\"]\n9:\"$Sreact.suspense\"\nb:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"ViewportBoundary\"]\nd:I[83656,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"MetadataBoundary\"]\nf:I[20558,[\"/_next/static/chunks/0~8b6_um3q_ef.js\"],\"default\",1]\n:HL[\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"style\"]\n"])</script><script>self.__next_f.push([1,"0:{\"P\":null,\"c\":[\"\",\"\"],\"q\":\"\",\"i\":false,\"f\":[[[\"\",{\"children\":[\"__PAGE__\",{}]},\"$undefined\",\"$undefined\",16],[[\"$\",\"$1\",\"c\",{\"children\":[[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}],[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/0~8b6_um3q_ef.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"html\",null,{\"lang\":\"en\",\"suppressHydrationWarning\":true,\"children\":[[\"$\",\"head\",null,{\"children\":[\"$\",\"script\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"\\n (function() {\\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\\n document.documentElement.classList.toggle('dark', theme === 'dark');\\n\\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) =\u003e {\\n document.documentElement.classList.toggle('dark', e.matches);\\n });\\n })();\\n \"}}]}],[\"$\",\"body\",null,{\"className\":\"font-sans antialiased\",\"children\":[\"$\",\"$L2\",null,{\"parallelRouterKey\":\"children\",\"error\":\"$undefined\",\"errorStyles\":\"$undefined\",\"errorScripts\":\"$undefined\",\"template\":[\"$\",\"$L3\",null,{}],\"templateStyles\":\"$undefined\",\"templateScripts\":\"$undefined\",\"notFound\":[[[\"$\",\"title\",null,{\"children\":\"404: This page could not be found.\"}],[\"$\",\"div\",null,{\"style\":{\"fontFamily\":\"system-ui,\\\"Segoe UI\\\",Roboto,Helvetica,Arial,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\"\",\"height\":\"100vh\",\"textAlign\":\"center\",\"display\":\"flex\",\"flexDirection\":\"column\",\"alignItems\":\"center\",\"justifyContent\":\"center\"},\"children\":[\"$\",\"div\",null,{\"children\":[[\"$\",\"style\",null,{\"dangerouslySetInnerHTML\":{\"__html\":\"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}\"}}],[\"$\",\"h1\",null,{\"className\":\"next-error-h1\",\"style\":{\"display\":\"inline-block\",\"margin\":\"0 20px 0 0\",\"padding\":\"0 23px 0 0\",\"fontSize\":24,\"fontWeight\":500,\"verticalAlign\":\"top\",\"lineHeight\":\"49px\"},\"children\":404}],[\"$\",\"div\",null,{\"style\":{\"display\":\"inline-block\"},\"children\":[\"$\",\"h2\",null,{\"style\":{\"fontSize\":14,\"fontWeight\":400,\"lineHeight\":\"49px\",\"margin\":0},\"children\":\"This page could not be found.\"}]}]]}]}]],[]],\"forbidden\":\"$undefined\",\"unauthorized\":\"$undefined\"}]}]]}]]}],{\"children\":[[\"$\",\"$1\",\"c\",{\"children\":[[\"$\",\"$L4\",null,{\"Component\":\"$5\",\"serverProvidedParams\":{\"searchParams\":{},\"params\":{},\"promises\":[\"$@6\",\"$@7\"]}}],[[\"$\",\"script\",\"script-0\",{\"src\":\"/_next/static/chunks/08a.k65hua~va.js\",\"async\":true,\"nonce\":\"$undefined\"}]],[\"$\",\"$L8\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.MetadataOutlet\",\"children\":\"$@a\"}]}]]}],{},null,false,null]},null,false,null],[\"$\",\"$1\",\"h\",{\"children\":[null,[\"$\",\"$Lb\",null,{\"children\":\"$Lc\"}],[\"$\",\"div\",null,{\"hidden\":true,\"children\":[\"$\",\"$Ld\",null,{\"children\":[\"$\",\"$9\",null,{\"name\":\"Next.Metadata\",\"children\":\"$Le\"}]}]}],null]}],false]],\"m\":\"$undefined\",\"G\":[\"$f\",[[\"$\",\"link\",\"0\",{\"rel\":\"stylesheet\",\"href\":\"/_next/static/chunks/0i88bcw_h0tc6.css\",\"precedence\":\"next\",\"crossOrigin\":\"$undefined\",\"nonce\":\"$undefined\"}]]],\"S\":true,\"h\":null,\"s\":\"$undefined\",\"l\":\"$undefined\",\"p\":\"$undefined\",\"d\":\"$undefined\",\"b\":\"BXmF4yXj1dJf2Wut0JJoI\"}\n"])</script><script>self.__next_f.push([1,"6:{}\n7:\"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params\"\n"])</script><script>self.__next_f.push([1,"c:[[\"$\",\"meta\",\"0\",{\"charSet\":\"utf-8\"}],[\"$\",\"meta\",\"1\",{\"name\":\"viewport\",\"content\":\"width=device-width, initial-scale=1\"}]]\n"])</script><script>self.__next_f.push([1,"a:null\ne:[[\"$\",\"title\",\"0\",{\"children\":\"Next.js Bundle Analyzer\"}],[\"$\",\"meta\",\"1\",{\"name\":\"description\",\"content\":\"Visualize and analyze your Next.js bundle sizes with interactive treemap and dependency analysis\"}]]\n"])</script></body></html> |
| 1:"$Sreact.fragment" | ||
| 2:I[32816,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 3:I[78470,["/_next/static/chunks/00qfakp0bmxst.js"],"default"] | ||
| 4:I[87181,["/_next/static/chunks/00qfakp0bmxst.js"],"ClientPageRoot"] | ||
| 5:I[79331,["/_next/static/chunks/00qfakp0bmxst.js","/_next/static/chunks/0umcxbkfjfq.0.js"],"default"] | ||
| 8:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"OutletBoundary"] | ||
| 2:I[7631,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 3:I[96635,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default"] | ||
| 4:I[52000,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ClientPageRoot"] | ||
| 5:I[79331,["/_next/static/chunks/0~8b6_um3q_ef.js","/_next/static/chunks/08a.k65hua~va.js"],"default"] | ||
| 8:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"OutletBoundary"] | ||
| 9:"$Sreact.suspense" | ||
| b:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"ViewportBoundary"] | ||
| d:I[74690,["/_next/static/chunks/00qfakp0bmxst.js"],"MetadataBoundary"] | ||
| f:I[43334,["/_next/static/chunks/00qfakp0bmxst.js"],"default",1] | ||
| b:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"ViewportBoundary"] | ||
| d:I[83656,["/_next/static/chunks/0~8b6_um3q_ef.js"],"MetadataBoundary"] | ||
| f:I[20558,["/_next/static/chunks/0~8b6_um3q_ef.js"],"default",1] | ||
| :HL["/_next/static/chunks/0i88bcw_h0tc6.css","style"] | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/00qfakp0bmxst.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/0umcxbkfjfq.0.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"ssoYuJB_kT5Zgw5eY8qfb"} | ||
| 0:{"P":null,"c":["",""],"q":"","i":false,"f":[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",16],[["$","$1","c",{"children":[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}],["$","script","script-0",{"src":"/_next/static/chunks/0~8b6_um3q_ef.js","async":true,"nonce":"$undefined"}]],["$","html",null,{"lang":"en","suppressHydrationWarning":true,"children":[["$","head",null,{"children":["$","script",null,{"dangerouslySetInnerHTML":{"__html":"\n (function() {\n const theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n document.documentElement.classList.toggle('dark', theme === 'dark');\n\n window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {\n document.documentElement.classList.toggle('dark', e.matches);\n });\n })();\n "}}]}],["$","body",null,{"className":"font-sans antialiased","children":["$","$L2",null,{"parallelRouterKey":"children","error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L3",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":404}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],[]],"forbidden":"$undefined","unauthorized":"$undefined"}]}]]}]]}],{"children":[["$","$1","c",{"children":[["$","$L4",null,{"Component":"$5","serverProvidedParams":{"searchParams":{},"params":{},"promises":["$@6","$@7"]}}],[["$","script","script-0",{"src":"/_next/static/chunks/08a.k65hua~va.js","async":true,"nonce":"$undefined"}]],["$","$L8",null,{"children":["$","$9",null,{"name":"Next.MetadataOutlet","children":"$@a"}]}]]}],{},null,false,null]},null,false,null],["$","$1","h",{"children":[null,["$","$Lb",null,{"children":"$Lc"}],["$","div",null,{"hidden":true,"children":["$","$Ld",null,{"children":["$","$9",null,{"name":"Next.Metadata","children":"$Le"}]}]}],null]}],false]],"m":"$undefined","G":["$f",[["$","link","0",{"rel":"stylesheet","href":"/_next/static/chunks/0i88bcw_h0tc6.css","precedence":"next","crossOrigin":"$undefined","nonce":"$undefined"}]]],"S":true,"h":null,"s":"$undefined","l":"$undefined","p":"$undefined","d":"$undefined","b":"BXmF4yXj1dJf2Wut0JJoI"} | ||
| 6:{} | ||
@@ -14,0 +14,0 @@ 7:"$0:f:0:1:1:children:0:props:children:0:props:serverProvidedParams:params" |
@@ -42,3 +42,3 @@ #!/usr/bin/env node | ||
| const nextBuild = async (options, directory)=>{ | ||
| process.title = `next-build (v${"16.3.0-canary.97"})`; | ||
| process.title = `next-build (v${"16.3.0-canary.99"})`; | ||
| process.on('SIGTERM', ()=>{ | ||
@@ -45,0 +45,0 @@ (0, _cpuprofile.saveCpuProfile)(); |
@@ -43,3 +43,3 @@ #!/usr/bin/env node | ||
| const bindings = await (0, _swc.loadBindings)((_config_experimental1 = config.experimental) == null ? void 0 : _config_experimental1.useWasmBinary); | ||
| await bindings.turbo.databaseCompact(cachePath, "16.3.0-canary.97"); | ||
| await bindings.turbo.databaseCompact(cachePath, "16.3.0-canary.99"); | ||
| console.log('Turbopack database compaction complete.'); | ||
@@ -46,0 +46,0 @@ }; |
@@ -14,2 +14,3 @@ "use strict"; | ||
| const _getprojectdir = require("../lib/get-project-dir"); | ||
| const _requestinsights = require("../next-devtools/shared/request-insights"); | ||
| const _config = /*#__PURE__*/ _interop_require_default(require("../server/config")); | ||
@@ -61,5 +62,6 @@ const _utils = require("../server/lib/utils"); | ||
| const route = request.route ?? request.url ?? request.requestId; | ||
| const kind = (0, _requestinsights.getRequestInsightKind)(request); | ||
| const duration = formatDuration(request.durationMs); | ||
| console.log(`${route} ${duration} ${request.status ?? 'pending'}`); | ||
| console.log(` request ${shortId(request.requestId)} page ${shortId(request.htmlRequestId)}`); | ||
| console.log(`${kind === 'instant-insights' ? `Instant Insights · ${route}` : route} ${duration} ${request.status ?? 'pending'}`); | ||
| console.log(` kind ${kind} request ${shortId(request.requestId)} page ${shortId(request.htmlRequestId)}`); | ||
| const visibleFetches = request.fetches.slice(0, DEFAULT_FETCH_LIMIT); | ||
@@ -66,0 +68,0 @@ if (visibleFetches.length < request.fetches.length) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/cli/next-request-insights.ts"],"sourcesContent":["import path from 'path'\nimport { readLockfileContent, parseDevServerInfo } from '../build/lockfile'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport type {\n RequestInsight,\n RequestInsightsSnapshot,\n} from '../next-devtools/shared/request-insights'\nimport loadConfig from '../server/config'\nimport { printAndExit } from '../server/lib/utils'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n} from '../shared/lib/constants'\n\nconst DEFAULT_REQUEST_LIMIT = 20\nconst DEFAULT_FETCH_LIMIT = 5\nconst DEV_SERVER_DISCOVERY_TIMEOUT_MS = 1000\nconst DEV_SERVER_DISCOVERY_RETRY_MS = 50\n\nexport type NextRequestInsightsOptions = {\n url?: string\n json?: boolean\n limit?: number\n}\n\nexport async function nextRequestInsights(\n options: NextRequestInsightsOptions,\n directory?: string\n) {\n const devServerUrl = options.url\n ? parseDevServerUrl(options.url)\n : await discoverDevServerUrl(directory)\n const endpoint = new URL(REQUEST_INSIGHTS_DEV_ENDPOINT, devServerUrl)\n\n const response = await fetch(endpoint).catch((error) => {\n printAndExit(\n `Failed to reach ${endpoint.toString()}: ${error instanceof Error ? error.message : String(error)}`,\n 1\n )\n throw error\n })\n\n const text = await response.text()\n let data: unknown\n try {\n data = JSON.parse(text)\n } catch {\n printAndExit(`Invalid response from ${endpoint.toString()}: ${text}`, 1)\n }\n\n if (!response.ok) {\n printAndExit(getResponseError(data, response.status), 1)\n }\n\n if (!isRequestInsightsSnapshot(data)) {\n exitWithError(\n `Invalid response from ${endpoint.toString()}: expected requests and fetches to be arrays.`\n )\n }\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2))\n return\n }\n\n const requests = data.requests\n if (requests.length === 0) {\n console.log('No request insights captured yet.')\n return\n }\n\n const limit = options.limit ?? DEFAULT_REQUEST_LIMIT\n const visibleRequests = requests.slice(-limit).reverse()\n console.log(\n `Showing ${visibleRequests.length} of ${requests.length} retained requests (newest first).`\n )\n\n for (const request of visibleRequests) {\n const route = request.route ?? request.url ?? request.requestId\n const duration = formatDuration(request.durationMs)\n console.log(`${route} ${duration} ${request.status ?? 'pending'}`)\n console.log(\n ` request ${shortId(request.requestId)} page ${shortId(request.htmlRequestId)}`\n )\n\n const visibleFetches = request.fetches.slice(0, DEFAULT_FETCH_LIMIT)\n if (visibleFetches.length < request.fetches.length) {\n console.log(\n ` showing first ${visibleFetches.length} of ${request.fetches.length} fetches`\n )\n }\n\n for (const fetch of visibleFetches) {\n console.log(\n ` fetch ${formatDuration(fetch.durationMs)} ${fetch.statusCode ?? '-'} ${fetch.cacheStatus ?? 'unknown'} ${fetch.method ?? 'GET'} ${fetch.url ?? ''}`\n )\n }\n }\n}\n\nasync function discoverDevServerUrl(directory?: string): Promise<URL> {\n const projectDir = getProjectDir(directory)\n const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, projectDir)\n const lockfilePath = path.join(projectDir, config.distDir, 'lock')\n const deadline = Date.now() + DEV_SERVER_DISCOVERY_TIMEOUT_MS\n\n while (Date.now() < deadline) {\n const lockfileContent = readLockfileContent(lockfilePath)\n const serverInfo = lockfileContent\n ? parseDevServerInfo(lockfileContent)\n : undefined\n\n if (serverInfo && typeof serverInfo.appUrl === 'string') {\n return parseDevServerUrl(serverInfo.appUrl)\n }\n\n await new Promise((resolve) =>\n setTimeout(resolve, DEV_SERVER_DISCOVERY_RETRY_MS)\n )\n }\n\n return exitWithError(\n `Unable to discover a running Next.js dev server from ${lockfilePath}. Start next dev or pass --url.`\n )\n}\n\nfunction exitWithError(message: string): never {\n return printAndExit(message, 1) as never\n}\n\nfunction getResponseError(data: unknown, status: number): string {\n if (\n typeof data === 'object' &&\n data !== null &&\n 'error' in data &&\n typeof data.error === 'string'\n ) {\n return data.error\n }\n\n return `Request failed with ${status}`\n}\n\nfunction isRequestInsightsSnapshot(\n data: unknown\n): data is RequestInsightsSnapshot {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'requests' in data &&\n Array.isArray(data.requests) &&\n data.requests.every(isRequestInsight)\n )\n}\n\nfunction isRequestInsight(request: unknown): request is RequestInsight {\n return (\n typeof request === 'object' &&\n request !== null &&\n 'fetches' in request &&\n Array.isArray(request.fetches)\n )\n}\n\nfunction parseDevServerUrl(value: string): URL {\n let url: URL\n\n try {\n url = new URL(value)\n } catch {\n return exitWithError(\n `Invalid dev server URL \"${value}\". Pass a valid HTTP or HTTPS URL.`\n )\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return exitWithError(\n `Invalid dev server URL \"${value}\". Pass a valid HTTP or HTTPS URL.`\n )\n }\n\n return url\n}\n\nfunction formatDuration(durationMs: number | undefined): string {\n if (typeof durationMs !== 'number') {\n return '-'\n }\n\n return durationMs < 1000\n ? `${Math.round(durationMs)}ms`\n : `${(durationMs / 1000).toFixed(2)}s`\n}\n\nfunction shortId(id: string | undefined): string {\n if (!id) {\n return '-'\n }\n\n return id.length > 8 ? id.slice(0, 8) : id\n}\n"],"names":["nextRequestInsights","DEFAULT_REQUEST_LIMIT","DEFAULT_FETCH_LIMIT","DEV_SERVER_DISCOVERY_TIMEOUT_MS","DEV_SERVER_DISCOVERY_RETRY_MS","options","directory","devServerUrl","url","parseDevServerUrl","discoverDevServerUrl","endpoint","URL","REQUEST_INSIGHTS_DEV_ENDPOINT","response","fetch","catch","error","printAndExit","toString","Error","message","String","text","data","JSON","parse","ok","getResponseError","status","isRequestInsightsSnapshot","exitWithError","json","console","log","stringify","requests","length","limit","visibleRequests","slice","reverse","request","route","requestId","duration","formatDuration","durationMs","shortId","htmlRequestId","visibleFetches","fetches","statusCode","cacheStatus","method","projectDir","getProjectDir","config","loadConfig","PHASE_DEVELOPMENT_SERVER","lockfilePath","path","join","distDir","deadline","Date","now","lockfileContent","readLockfileContent","serverInfo","parseDevServerInfo","undefined","appUrl","Promise","resolve","setTimeout","Array","isArray","every","isRequestInsight","value","protocol","Math","round","toFixed","id"],"mappings":";;;;+BAyBsBA;;;eAAAA;;;6DAzBL;0BACuC;+BAC1B;+DAKP;uBACM;2BAItB;;;;;;AAEP,MAAMC,wBAAwB;AAC9B,MAAMC,sBAAsB;AAC5B,MAAMC,kCAAkC;AACxC,MAAMC,gCAAgC;AAQ/B,eAAeJ,oBACpBK,OAAmC,EACnCC,SAAkB;IAElB,MAAMC,eAAeF,QAAQG,GAAG,GAC5BC,kBAAkBJ,QAAQG,GAAG,IAC7B,MAAME,qBAAqBJ;IAC/B,MAAMK,WAAW,IA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AAY,EAAE,CAAC,GAC7B,GAAG,AAACA,CAAAA,aAAa,IAAG,EAAGqC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC1C;AAEA,SAASpC,QAAQqC,EAAsB;IACrC,IAAI,CAACA,IAAI;QACP,OAAO;IACT;IAEA,OAAOA,GAAGhD,MAAM,GAAG,IAAIgD,GAAG7C,KAAK,CAAC,GAAG,KAAK6C;AAC1C","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/cli/next-request-insights.ts"],"sourcesContent":["import path from 'path'\nimport { readLockfileContent, parseDevServerInfo } from '../build/lockfile'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport type {\n RequestInsight,\n RequestInsightsSnapshot,\n} from '../next-devtools/shared/request-insights'\nimport { getRequestInsightKind } from '../next-devtools/shared/request-insights'\nimport loadConfig from '../server/config'\nimport { printAndExit } from '../server/lib/utils'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n REQUEST_INSIGHTS_DEV_ENDPOINT,\n} from '../shared/lib/constants'\n\nconst DEFAULT_REQUEST_LIMIT = 20\nconst DEFAULT_FETCH_LIMIT = 5\nconst DEV_SERVER_DISCOVERY_TIMEOUT_MS = 1000\nconst DEV_SERVER_DISCOVERY_RETRY_MS = 50\n\nexport type NextRequestInsightsOptions = {\n url?: string\n json?: boolean\n limit?: number\n}\n\nexport async function nextRequestInsights(\n options: NextRequestInsightsOptions,\n directory?: string\n) {\n const devServerUrl = options.url\n ? parseDevServerUrl(options.url)\n : await discoverDevServerUrl(directory)\n const endpoint = new URL(REQUEST_INSIGHTS_DEV_ENDPOINT, devServerUrl)\n\n const response = await fetch(endpoint).catch((error) => {\n printAndExit(\n `Failed to reach ${endpoint.toString()}: ${error instanceof Error ? error.message : String(error)}`,\n 1\n )\n throw error\n })\n\n const text = await response.text()\n let data: unknown\n try {\n data = JSON.parse(text)\n } catch {\n printAndExit(`Invalid response from ${endpoint.toString()}: ${text}`, 1)\n }\n\n if (!response.ok) {\n printAndExit(getResponseError(data, response.status), 1)\n }\n\n if (!isRequestInsightsSnapshot(data)) {\n exitWithError(\n `Invalid response from ${endpoint.toString()}: expected requests and fetches to be arrays.`\n )\n }\n\n if (options.json) {\n console.log(JSON.stringify(data, null, 2))\n return\n }\n\n const requests = data.requests\n if (requests.length === 0) {\n console.log('No request insights captured yet.')\n return\n }\n\n const limit = options.limit ?? DEFAULT_REQUEST_LIMIT\n const visibleRequests = requests.slice(-limit).reverse()\n console.log(\n `Showing ${visibleRequests.length} of ${requests.length} retained requests (newest first).`\n )\n\n for (const request of visibleRequests) {\n const route = request.route ?? request.url ?? request.requestId\n const kind = getRequestInsightKind(request)\n const duration = formatDuration(request.durationMs)\n console.log(\n `${kind === 'instant-insights' ? `Instant Insights · ${route}` : route} ${duration} ${request.status ?? 'pending'}`\n )\n console.log(\n ` kind ${kind} request ${shortId(request.requestId)} page ${shortId(request.htmlRequestId)}`\n )\n\n const visibleFetches = request.fetches.slice(0, DEFAULT_FETCH_LIMIT)\n if (visibleFetches.length < request.fetches.length) {\n console.log(\n ` showing first ${visibleFetches.length} of ${request.fetches.length} fetches`\n )\n }\n\n for (const fetch of visibleFetches) {\n console.log(\n ` fetch ${formatDuration(fetch.durationMs)} ${fetch.statusCode ?? '-'} ${fetch.cacheStatus ?? 'unknown'} ${fetch.method ?? 'GET'} ${fetch.url ?? ''}`\n )\n }\n }\n}\n\nasync function discoverDevServerUrl(directory?: string): Promise<URL> {\n const projectDir = getProjectDir(directory)\n const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, projectDir)\n const lockfilePath = path.join(projectDir, config.distDir, 'lock')\n const deadline = Date.now() + DEV_SERVER_DISCOVERY_TIMEOUT_MS\n\n while (Date.now() < deadline) {\n const lockfileContent = readLockfileContent(lockfilePath)\n const serverInfo = lockfileContent\n ? parseDevServerInfo(lockfileContent)\n : undefined\n\n if (serverInfo && typeof serverInfo.appUrl === 'string') {\n return parseDevServerUrl(serverInfo.appUrl)\n }\n\n await new Promise((resolve) =>\n setTimeout(resolve, DEV_SERVER_DISCOVERY_RETRY_MS)\n )\n }\n\n return exitWithError(\n `Unable to discover a running Next.js dev server from ${lockfilePath}. Start next dev or pass --url.`\n )\n}\n\nfunction exitWithError(message: string): never {\n return printAndExit(message, 1) as never\n}\n\nfunction getResponseError(data: unknown, status: number): string {\n if (\n typeof data === 'object' &&\n data !== null &&\n 'error' in data &&\n typeof data.error === 'string'\n ) {\n return data.error\n }\n\n return `Request failed with ${status}`\n}\n\nfunction isRequestInsightsSnapshot(\n data: unknown\n): data is RequestInsightsSnapshot {\n return (\n typeof data === 'object' &&\n data !== null &&\n 'requests' in data &&\n Array.isArray(data.requests) &&\n data.requests.every(isRequestInsight)\n )\n}\n\nfunction isRequestInsight(request: unknown): request is RequestInsight {\n return (\n typeof request === 'object' &&\n request !== null &&\n 'fetches' in request &&\n Array.isArray(request.fetches)\n )\n}\n\nfunction parseDevServerUrl(value: string): URL {\n let url: URL\n\n try {\n url = new URL(value)\n } catch {\n return exitWithError(\n `Invalid dev server URL \"${value}\". Pass a valid HTTP or HTTPS URL.`\n )\n }\n\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n return exitWithError(\n `Invalid dev server URL \"${value}\". Pass a valid HTTP or HTTPS URL.`\n )\n }\n\n return url\n}\n\nfunction formatDuration(durationMs: number | undefined): string {\n if (typeof durationMs !== 'number') {\n return '-'\n }\n\n return durationMs < 1000\n ? `${Math.round(durationMs)}ms`\n : `${(durationMs / 1000).toFixed(2)}s`\n}\n\nfunction shortId(id: string | undefined): string {\n if (!id) {\n return '-'\n }\n\n return id.length > 8 ? id.slice(0, 8) : id\n}\n"],"names":["nextRequestInsights","DEFAULT_REQUEST_LIMIT","DEFAULT_FETCH_LIMIT","DEV_SERVER_DISCOVERY_TIMEOUT_MS","DEV_SERVER_DISCOVERY_RETRY_MS","options","directory","devServerUrl","url","parseDevServerUrl","discoverDevServerUrl","endpoint","URL","REQUEST_INSIGHTS_DEV_ENDPOINT","response","fetch","catch","error","printAndExit","toString","Error","message","String","text","data","JSON","parse","ok","getResponseError","status","isRequestInsightsSnapshot","exitWithError","json","console","log","stringify","requests","length","limit","visibleRequests","slice","reverse","request","route","requestId","kind","getRequestInsightKind","duration","formatDuration","durationMs","shortId","htmlRequestId","visibleFetches","fetches","statusCode","cacheStatus","method","projectDir","getProjectDir","config","loadConfig","PHASE_DEVELOPMENT_SERVER","lockfilePath","path","join","distDir","deadline","Date","now","lockfileContent","readLockfileContent","serverInfo","parseDevServerInfo","undefined","appUrl","Promise","resolve","setTimeout","Array","isArray","every","isRequestInsight","value","protocol","Math","round","toFixed","id"],"mappings":";;;;+BA0BsBA;;;eAAAA;;;6DA1BL;0BACuC;+BAC1B;iCAKQ;+DACf;uBACM;2BAItB;;;;;;AAEP,MAAMC,wBAAwB;AAC9B,MAAMC,sBAAsB;AAC5B,MAAMC,kCAAkC;AACxC,MAAMC,gCAAgC;AAQ/B,eAAeJ,oBACpBK,OAAmC,EACnCC,SAAkB;IAElB,MAAMC,eAAeF,QAAQG,GAAG,GAC5BC,kBAAkBJ,QAAQG,GAAG,IAC7B,MAAME,qBAAqBJ;IAC/B,MAAMK,WAAW,IAAIC,IAAIC,wCAA6B,EAAEN;IAExD,MAAMO,WAAW,MAAMC,MAAMJ,UAAUK,KAAK,CAAC,CAACC;QAC5CC,IAAAA,mBAAY,EACV,CAAC,gBAAgB,EAAEP,SAASQ,QAAQ,GAAG,EAAE,EAAEF,iBAAiBG,QAAQH,MAAMI,OAAO,GAAGC,OAAOL,QAAQ,EACnG;QAEF,MAAMA;IACR;IAEA,MAAMM,OAAO,MAAMT,SAASS,IAAI;IAChC,IAAIC;IACJ,IAAI;QACFA,OAAOC,KAAKC,KAAK,CAACH;IACpB,EAAE,OAAM;QACNL,IAAAA,mBAAY,EAAC,CAAC,sBAAsB,EAAEP,SAASQ,QAAQ,GAAG,EAAE,EAAEI,MAAM,EAAE;IACxE;IAEA,IAAI,CAACT,SAASa,EAAE,EAAE;QAChBT,IAAAA,mBAAY,EAACU,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AAK;IACnB;IAEA,OAAO,CAAC,oBAAoB,EAAEY,QAAQ;AACxC;AAEA,SAASC,0BACPN,IAAa;IAEb,OACE,OAAOA,SAAS,YAChBA,SAAS,QACT,cAAcA,QACdsD,MAAMC,OAAO,CAACvD,KAAKY,QAAQ,KAC3BZ,KAAKY,QAAQ,CAAC4C,KAAK,CAACC;AAExB;AAEA,SAASA,iBAAiBvC,OAAgB;IACxC,OACE,OAAOA,YAAY,YACnBA,YAAY,QACZ,aAAaA,WACboC,MAAMC,OAAO,CAACrC,QAAQW,OAAO;AAEjC;AAEA,SAAS5C,kBAAkByE,KAAa;IACtC,IAAI1E;IAEJ,IAAI;QACFA,MAAM,IAAII,IAAIsE;IAChB,EAAE,OAAM;QACN,OAAOnD,cACL,CAAC,wBAAwB,EAAEmD,MAAM,kCAAkC,CAAC;IAExE;IAEA,IAAI1E,IAAI2E,QAAQ,KAAK,WAAW3E,IAAI2E,QAAQ,KAAK,UAAU;QACzD,OAAOpD,cACL,CAAC,wBAAwB,EAAEmD,MAAM,kCAAkC,CAAC;IAExE;IAEA,OAAO1E;AACT;AAEA,SAASwC,eAAeC,UAA8B;IACpD,IAAI,OAAOA,eAAe,UAAU;QAClC,OAAO;IACT;IAEA,OAAOA,aAAa,OAChB,GAAGmC,KAAKC,KAAK,CAACpC,YAAY,EAAE,CAAC,GAC7B,GAAG,AAACA,CAAAA,aAAa,IAAG,EAAGqC,OAAO,CAAC,GAAG,CAAC,CAAC;AAC1C;AAEA,SAASpC,QAAQqC,EAAsB;IACrC,IAAI,CAACA,IAAI;QACP,OAAO;IACT;IAEA,OAAOA,GAAGlD,MAAM,GAAG,IAAIkD,GAAG/C,KAAK,CAAC,GAAG,KAAK+C;AAC1C","ignoreList":[0]} |
@@ -18,3 +18,3 @@ /** | ||
| const _setattributesfromprops = require("./set-attributes-from-props"); | ||
| const version = "16.3.0-canary.97"; | ||
| const version = "16.3.0-canary.99"; | ||
| window.next = { | ||
@@ -21,0 +21,0 @@ version, |
@@ -70,3 +70,3 @@ "use strict"; | ||
| const now = Date.now(); | ||
| const staleAt = await (0, _cache.getStaleAt)(now, staticStageResponse.s); | ||
| const staleAt = await (0, _cache.resolveStaleAt)(now, staticStageResponse.s); | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, staticStageResponse.f, undefined, staticStageResponse.h, staticStageResponse.r ?? null, staleAt, initialTree, initialRenderedSearch, true // isResponsePartial | ||
@@ -85,3 +85,3 @@ ); | ||
| const now = Date.now(); | ||
| (0, _cache.getStaleAt)(now, initialStaleTime).then((staleAt)=>{ | ||
| (0, _cache.resolveStaleAt)(now, initialStaleTime).then((staleAt)=>{ | ||
| (0, _cache.writePrerenderResponseIntoCache)(now, _types.FetchStrategy.PPR, initialFlightData, undefined, initialHeadVaryParams, initialRootVaryParams ?? null, staleAt, initialTree, initialRenderedSearch, false // isResponsePartial | ||
@@ -88,0 +88,0 @@ ); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { getFlightDataPartsFromPath } from '../../flight-data-helpers'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n convertRootFlightRouterStateToRouteTree,\n getStaleAt,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n f: initialFlightData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n h: initialHeadVaryParams,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const normalizedFlightData = getFlightDataPartsFromPath(initialFlightData[0])\n const {\n tree: initialTree,\n seedData: initialSeedData,\n head: initialHead,\n } = normalizedFlightData\n // For the SSR render, seed data should always be available (we only send back a `null` response\n // in the case of a `loading` segment, pre-PPR.)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Convert the initial FlightRouterState into the RouteTree type.\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the FlightRouterState\n // baked into the initial RSC payload won't have the correct segment inlining\n // hints because those are computed after the pre-render. The server marks\n // these trees with InliningHintsStale, which causes the route cache entry\n // to be immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = convertRootFlightRouterStateToRouteTree(\n initialTree,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialSeedData,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialSeedData !== null && initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await getStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n getStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialFlightData,\n undefined, // buildId — not applicable for initial HTML\n initialHeadVaryParams,\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","f","initialFlightData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","h","initialHeadVaryParams","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","normalizedFlightData","getFlightDataPartsFromPath","tree","initialTree","seedData","initialSeedData","head","initialHead","canonicalUrl","createHrefFromUrl","acc","metadataVaryPath","initialRouteTree","convertRootFlightRouterStateToRouteTree","initialTask","createInitialCacheNodeForHydration","computeDynamicStaleAt","UnknownDynamicStaleTime","discoverKnownRoute","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","decodeStageUntilBoundary","staleAt","getStaleAt","writePrerenderResponseIntoCache","FetchStrategy","PPR","catch","cancel","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","flightDatas","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","extractPathFromFlightRouterState","previousNextUrl","debugInfo"],"mappings":";;;;+BA+BgBA;;;eAAAA;;;mCA7BkB;oCACe;mCAGN;gCACQ;uBAO5C;uBACuB;yBAIvB;qCACkC;kCACN;AAU5B,SAASA,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,iBAAiB,EACpBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGxB;IAEJ,sFAAsF;IACtF,kGAAkG;IAClG,mCAAmC;IACnC,MAAMyB,sBAAsBrB,yBAAyBsB,IAAI,CAAC;IAE1D,MAAMC,uBAAuBC,IAAAA,6CAA0B,EAACtB,iBAAiB,CAAC,EAAE;IAC5E,MAAM,EACJuB,MAAMC,WAAW,EACjBC,UAAUC,eAAe,EACzBC,MAAMC,WAAW,EAClB,GAAGP;IACJ,gGAAgG;IAChG,gDAAgD;IAEhD,MAAMQ,eACJ,6EAA6E;IAC7E,kJAAkJ;IAClJjC,WAEIkC,IAAAA,oCAAiB,EAAClC,YAClBuB;IAEN,iEAAiE;IACjE,2EAA2E;IAC3E,6EAA6E;IAC7E,8CAA8C;IAC9C,EAAE;IACF,2EAA2E;IAC3E,6EAA6E;IAC7E,0EAA0E;IAC1E,0EAA0E;IAC1E,2EAA2E;IAC3E,0CAA0C;IAC1C,MAAMY,MAAM;QAAEC,kBAAkB;IAAK;IACrC,MAAMC,mBAAmBC,IAAAA,8CAAuC,EAC9DV,aACAtB,uBACA6B;IAEF,MAAMC,mBAAmBD,IAAIC,gBAAgB;IAC7C,MAAMG,cAA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ACAC,mBAAmB;YACjBC,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAnD;QACAoD,gBAAgB/E;QAChB,sEAAsE;QACtEgF,SACE,AAACC,CAAAA,IAAAA,oDAAgC,EAAC3D,gBAAgB5B,UAAU8C,QAAO,KACnE;QACF0C,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOjB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { getFlightDataPartsFromPath } from '../../flight-data-helpers'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n convertRootFlightRouterStateToRouteTree,\n resolveStaleAt,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n f: initialFlightData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n h: initialHeadVaryParams,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const normalizedFlightData = getFlightDataPartsFromPath(initialFlightData[0])\n const {\n tree: initialTree,\n seedData: initialSeedData,\n head: initialHead,\n } = normalizedFlightData\n // For the SSR render, seed data should always be available (we only send back a `null` response\n // in the case of a `loading` segment, pre-PPR.)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Convert the initial FlightRouterState into the RouteTree type.\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the FlightRouterState\n // baked into the initial RSC payload won't have the correct segment inlining\n // hints because those are computed after the pre-render. The server marks\n // these trees with InliningHintsStale, which causes the route cache entry\n // to be immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = convertRootFlightRouterStateToRouteTree(\n initialTree,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialSeedData,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialSeedData !== null && initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialFlightData,\n undefined, // buildId — not applicable for initial HTML\n initialHeadVaryParams,\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","f","initialFlightData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","h","initialHeadVaryParams","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","normalizedFlightData","getFlightDataPartsFromPath","tree","initialTree","seedData","initialSeedData","head","initialHead","canonicalUrl","createHrefFromUrl","acc","metadataVaryPath","initialRouteTree","convertRootFlightRouterStateToRouteTree","initialTask","createInitialCacheNodeForHydration","computeDynamicStaleAt","UnknownDynamicStaleTime","discoverKnownRoute","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","decodeStageUntilBoundary","staleAt","resolveStaleAt","writePrerenderResponseIntoCache","FetchStrategy","PPR","catch","cancel","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","flightDatas","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","extractPathFromFlightRouterState","previousNextUrl","debugInfo"],"mappings":";;;;+BA+BgBA;;;eAAAA;;;mCA7BkB;oCACe;mCAGN;gCACQ;uBAO5C;uBACuB;yBAIvB;qCACkC;kCACN;AAU5B,SAASA,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,iBAAiB,EACpBC,GAAGC,qBAA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A6B8D;QAC/B;QAEA,2EAA2E;QAC3E,2EAA2E;QAC3E,0EAA0E;QAC1E,uCAAuC;QACvC,IAAIzC,gCAAgC,MAAM;YACxC0C,IAAAA,mCAA4B,EAC1BlB,KAAKC,GAAG,IACRzB,8BACAQ,aACAtB,uBAEC6C,IAAI,CAAC,CAACY;gBACL,IAAIA,cAAc,MAAM;oBACtBC,IAAAA,0CAAmC,EACjCpB,KAAKC,GAAG,IACRa,oBAAa,CAACO,UAAU,EACxBF,UAAUG,WAAW,EACrBH,UAAUI,OAAO,EACjBJ,UAAUK,iBAAiB,EAC3BL,UAAUM,cAAc,EACxBN,UAAUO,sBAAsB,EAChCP,UAAUR,OAAO,EACjBQ,UAAUQ,cAAc,EACxB;gBAEJ;YACF,GACCX,KAAK,CAAC;YACL,qEAAqE;YACrE,8CAA8C;YAChD;QACJ;IACF;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,YAAY;IACZ,EAAE;IACF,6EAA6E;IAC7E,8EAA8E;IAC9E,gEAAgE;IAChE,EAAE;IACF,yEAAyE;IACzE,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMY,eAAe;QACnB7C,MAAMY,YAAYkC,KAAK;QACvBC,OAAOnC,YAAYoC,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,mBAAmB;YACjBC,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAnD;QACAoD,gBAAgB/E;QAChB,sEAAsE;QACtEgF,SACE,AAACC,CAAAA,IAAAA,oDAAgC,EAAC3D,gBAAgB5B,UAAU8C,QAAO,KACnE;QACF0C,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOjB;AACT","ignoreList":[0]} |
@@ -96,2 +96,3 @@ import type { FlightData, Segment as FlightRouterStateSegment } from '../../../shared/lib/app-router-types'; | ||
| status: EntryStatus.Empty; | ||
| blockedTasks: Set<PrefetchTask> | null; | ||
| rsc: null; | ||
@@ -103,2 +104,3 @@ isPartial: true; | ||
| status: EntryStatus.Pending; | ||
| blockedTasks: Set<PrefetchTask> | null; | ||
| rsc: null; | ||
@@ -110,2 +112,3 @@ isPartial: boolean; | ||
| status: EntryStatus.Rejected; | ||
| blockedTasks: Set<PrefetchTask> | null; | ||
| rsc: null; | ||
@@ -117,2 +120,3 @@ isPartial: true; | ||
| status: EntryStatus.Fulfilled; | ||
| blockedTasks: null; | ||
| rsc: React.ReactNode | null; | ||
@@ -195,3 +199,3 @@ isPartial: boolean; | ||
| export declare function overwriteRevalidatingSegmentCacheEntry(now: number, fetchStrategy: FetchStrategy, tree: RouteTree): EmptySegmentCacheEntry; | ||
| export declare function upsertSegmentEntry(now: number, varyPath: SegmentVaryPath, candidateEntry: SegmentCacheEntry): SegmentCacheEntry | null; | ||
| export declare function upsertSegmentEntry(now: number, varyPath: SegmentVaryPath, candidateEntry: SegmentCacheEntry, lookupVaryPath: SegmentVaryPath | null): SegmentCacheEntry | null; | ||
| export declare function createDetachedSegmentCacheEntry(now: number): EmptySegmentCacheEntry; | ||
@@ -257,13 +261,18 @@ export declare function upgradeToPendingSegment(emptyEntry: EmptySegmentCacheEntry, fetchStrategy: FetchStrategy, navigationLockPrefetch: NavigationLockPrefetch | null): PendingSegmentCacheEntry; | ||
| /** | ||
| * Reads the stale time from an async iterable or a response header and | ||
| * returns a staleAt timestamp. | ||
| * Reads a stale-at time by `await`ing the staleTime async iterable (last | ||
| * yielded value wins) and, if a `response` is given and the iterable yields | ||
| * nothing, falling back to the `Next-Router-Stale-Time` header. | ||
| * | ||
| * TODO: Buffer the response and then read the iterable values | ||
| * synchronously, similar to readVaryParams. This would avoid the need to | ||
| * make this async, and we could also use it in | ||
| * writeDynamicTreeResponseIntoCache. This will also be needed when React | ||
| * starts leaving async iterables hanging when the outer RSC stream is | ||
| * aborted e.g. due to sync I/O (with unstable_allowPartialStream). | ||
| * The async form is required for the two things `readFulfilledStaleAt` can't | ||
| * do: the header fallback, and reading a dynamic `Full` response | ||
| * (fetchStrategy.Full with Partial Prefetching disabled) — the one response | ||
| * kind that isn't buffered before it's read, so its iterable values must be | ||
| * awaited rather than drained synchronously off their thenable status. | ||
| * | ||
| * Buffered responses (static PPR, runtime prefetch, stage decodes) don't need | ||
| * the async form: segment bundles and the shell-stage decode already read | ||
| * staleTime synchronously via `readFulfilledStaleAt`, and the remaining | ||
| * buffered callers here could be moved to it too. | ||
| */ | ||
| export declare function getStaleAt(now: number, staleTimeIterable: AsyncIterable<number> | undefined, response?: RSCResponse<unknown>): Promise<number>; | ||
| export declare function resolveStaleAt(now: number, staleTimeIterable: AsyncIterable<number> | undefined, response?: RSCResponse<unknown>): Promise<number>; | ||
| /** | ||
@@ -270,0 +279,0 @@ * Writes a prerender response into the segment cache at the vary path |
@@ -285,3 +285,3 @@ "use strict"; | ||
| // subsequent navigations can serve cached static segments instantly. | ||
| (0, _cache.getStaleAt)(now, staticStageResponse.s).then((staleAt)=>{ | ||
| (0, _cache.resolveStaleAt)(now, staticStageResponse.s).then((staleAt)=>{ | ||
| const buildId = responseHeaders.get(_constants.NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? staticStageResponse.b; | ||
@@ -288,0 +288,0 @@ // TODO: Implement Shell extraction as part of Cached Navigations. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData } from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n convertRootFlightRouterStateToRouteTree,\n getStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type RouteTree,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { PageVaryPath } from './vary-path'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.data,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n data: null,\n head: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n flightData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n createHrefFromUrl(canonicalUrl),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n getStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n buildId,\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n// TODO: The rest of this file is related to converting the server response into\n// the data structures used by the client. Probably should move to a\n// separate module.\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree\n metadataVaryPath: PageVaryPath | null\n data: CacheNodeSeedData | null\n head: HeadData | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n flightData: Array<NormalizedFlightData> | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n\n let baseTree: FlightRouterState = currentTree\n let baseData: CacheNodeSeedData | null = null\n let head: HeadData | null = null\n if (flightData !== null) {\n for (const {\n segmentPath,\n tree: treePatch,\n seedData: dataPatch,\n head: headPatch,\n } of flightData) {\n const result = convertServerPatchToFullTreeImpl(\n baseTree,\n baseData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n 0\n )\n baseTree = result.tree\n baseData = result.data\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch\n }\n }\n\n const finalFlightRouterState = baseTree\n\n // Convert the final FlightRouterState into a RouteTree type.\n //\n // TODO: Eventually, FlightRouterState will evolve to being a transport format\n // only. The RouteTree type will become the main type used for dealing with\n // routes on the client, and we'll store it in the state directly.\n const acc = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n finalFlightRouterState,\n renderedSearch as NormalizedSearch,\n acc\n )\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n data: baseData,\n renderedSearch,\n head,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n baseRouterState: FlightRouterState,\n baseData: CacheNodeSeedData | null,\n treePatch: FlightRouterState,\n dataPatch: CacheNodeSeedData | null,\n segmentPath: FlightSegmentPath,\n renderedSearch: string,\n index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch,\n }\n }\n\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey: string = segmentPath[index]\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n const baseTreeChildren = baseRouterState[1]\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n const newTreeChildren: Record<string, FlightRouterState> = {}\n const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n for (const parallelRouteKey in baseTreeChildren) {\n const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n const childBaseSeedData =\n baseSeedDataChildren !== null\n ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n : null\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(\n childBaseRouterState,\n childBaseSeedData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2\n )\n\n newTreeChildren[parallelRouteKey] = result.tree\n newSeedDataChildren[parallelRouteKey] = result.data\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n }\n }\n\n let clonedTree: FlightRouterState\n let clonedSeedData: CacheNodeSeedData\n // Clone all the fields except the children.\n\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [baseRouterState[0], newTreeChildren]\n if (2 in baseRouterState) {\n const compressedRefreshState = baseRouterState[2]\n if (\n compressedRefreshState !== undefined &&\n compressedRefreshState !== null\n ) {\n // Since this part of the tree was patched with new data, any parent\n // refresh states should be updated to reflect the new rendered search\n // value. (The refresh state acts like a \"context provider\".) All pages\n // within the same server response share the same renderedSearch value,\n // but the same RouteTree could be composed from multiple different\n // routes, and multiple responses.\n clonedTree[2] = [compressedRefreshState[0], renderedSearch]\n }\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3]\n }\n // Recompute the propagated \"subtree\" prefetch hints for this segment. Mirrors\n // the propagation done on the server in\n // createFlightRouterStateFromLoaderTree.\n let prefetchHints = (baseRouterState[4] ?? 0) & ~SubtreePrefetchHints\n for (const parallelRouteKey in newTreeChildren) {\n const childHints = newTreeChildren[parallelRouteKey][4]\n if (childHints !== undefined) {\n prefetchHints = propagateSubtreeBits(prefetchHints, childHints)\n }\n }\n if (prefetchHints !== 0) {\n clonedTree[4] = prefetchHints\n }\n\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n null,\n ]\n\n return {\n tree: clonedTree,\n data: clonedSeedData,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves once it has spawned every request and all of them have fulfilled,\n // so the navigation below reads present data rather than a still-in-flight\n // entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","convertServerPatchToFullTree","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","getLinkForCurrentNavigation","fetchStrategy","FetchStrategy","Full","routeTree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","metadataVaryPath","data","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","computeDynamicStaleAt","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","flightData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","discoverKnownRoute","search","createHrefFromUrl","response","staticStageResponse","isResponsePartial","getStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writePrerenderResponseIntoCache","f","h","r","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","flightDatas","headVaryParams","rootVaryParamsIterable","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","currentTree","dynamicStaleTimeSeconds","baseTree","baseData","segmentPath","treePatch","seedData","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","acc","convertRootFlightRouterStateToRouteTree","baseRouterState","index","length","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","parallelRouteKey","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","SubtreePrefetchHints","childHints","propagateSubtreeBits","isEmptySeedDataPartial","beginNavigationLockPrefetch","navigationLockPrefetch","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree"],"mappings":";;;;;;;;;;;;;;;;;;;IAuoBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA4CAC,4BAA4B;eAA5BA;;IAtyBAC,QAAQ;eAARA;;IAgKAC,oBAAoB;eAApBA;;;gCA9MT;qCAE6B;gCAQ7B;mCAC2B;2BACY;uBAYvC;kCAC4B;0BACmB;2BACjB;uBACW;uBACJ;oCAGb;oCACI;+BACG;yBACyB;iCAChB;AAUxC,SAASD,SACdE,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,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AAuB,EAAE,GAC/BtL,QAAQ;QACVsL,wBAAwBhM,0BAA0B4F,OAAOjB,IAAI;IAC/D;IAEA,OAAOiB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData } from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n convertRootFlightRouterStateToRouteTree,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type RouteTree,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { PageVaryPath } from './vary-path'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.data,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n data: null,\n head: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n flightData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n createHrefFromUrl(canonicalUrl),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n buildId,\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n// TODO: The rest of this file is related to converting the server response into\n// the data structures used by the client. Probably should move to a\n// separate module.\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree\n metadataVaryPath: PageVaryPath | null\n data: CacheNodeSeedData | null\n head: HeadData | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n flightData: Array<NormalizedFlightData> | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n\n let baseTree: FlightRouterState = currentTree\n let baseData: CacheNodeSeedData | null = null\n let head: HeadData | null = null\n if (flightData !== null) {\n for (const {\n segmentPath,\n tree: treePatch,\n seedData: dataPatch,\n head: headPatch,\n } of flightData) {\n const result = convertServerPatchToFullTreeImpl(\n baseTree,\n baseData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n 0\n )\n baseTree = result.tree\n baseData = result.data\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch\n }\n }\n\n const finalFlightRouterState = baseTree\n\n // Convert the final FlightRouterState into a RouteTree type.\n //\n // TODO: Eventually, FlightRouterState will evolve to being a transport format\n // only. The RouteTree type will become the main type used for dealing with\n // routes on the client, and we'll store it in the state directly.\n const acc = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n finalFlightRouterState,\n renderedSearch as NormalizedSearch,\n acc\n )\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n data: baseData,\n renderedSearch,\n head,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n baseRouterState: FlightRouterState,\n baseData: CacheNodeSeedData | null,\n treePatch: FlightRouterState,\n dataPatch: CacheNodeSeedData | null,\n segmentPath: FlightSegmentPath,\n renderedSearch: string,\n index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch,\n }\n }\n\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey: string = segmentPath[index]\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n const baseTreeChildren = baseRouterState[1]\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n const newTreeChildren: Record<string, FlightRouterState> = {}\n const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n for (const parallelRouteKey in baseTreeChildren) {\n const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n const childBaseSeedData =\n baseSeedDataChildren !== null\n ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n : null\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(\n childBaseRouterState,\n childBaseSeedData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2\n )\n\n newTreeChildren[parallelRouteKey] = result.tree\n newSeedDataChildren[parallelRouteKey] = result.data\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n }\n }\n\n let clonedTree: FlightRouterState\n let clonedSeedData: CacheNodeSeedData\n // Clone all the fields except the children.\n\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [baseRouterState[0], newTreeChildren]\n if (2 in baseRouterState) {\n const compressedRefreshState = baseRouterState[2]\n if (\n compressedRefreshState !== undefined &&\n compressedRefreshState !== null\n ) {\n // Since this part of the tree was patched with new data, any parent\n // refresh states should be updated to reflect the new rendered search\n // value. (The refresh state acts like a \"context provider\".) All pages\n // within the same server response share the same renderedSearch value,\n // but the same RouteTree could be composed from multiple different\n // routes, and multiple responses.\n clonedTree[2] = [compressedRefreshState[0], renderedSearch]\n }\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3]\n }\n // Recompute the propagated \"subtree\" prefetch hints for this segment. Mirrors\n // the propagation done on the server in\n // createFlightRouterStateFromLoaderTree.\n let prefetchHints = (baseRouterState[4] ?? 0) & ~SubtreePrefetchHints\n for (const parallelRouteKey in newTreeChildren) {\n const childHints = newTreeChildren[parallelRouteKey][4]\n if (childHints !== undefined) {\n prefetchHints = propagateSubtreeBits(prefetchHints, childHints)\n }\n }\n if (prefetchHints !== 0) {\n clonedTree[4] = prefetchHints\n }\n\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n null,\n ]\n\n return {\n tree: clonedTree,\n data: clonedSeedData,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves once it has spawned every request and all of them have fulfilled,\n // so the navigation below reads present data rather than a still-in-flight\n // entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","convertServerPatchToFullTree","navigate","navigateToKnownRoute","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","beginLockedNavigation","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","createCacheKey","route","readRouteCacheEntry","status","EntryStatus","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","catch","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","getLinkForCurrentNavigation","fetchStrategy","FetchStrategy","Full","routeTree","prefetchHints","PrefetchHint","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","createLinkPrefetchPartialError","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","startPPRNavigation","metadataVaryPath","data","head","dynamicStaleAt","FreshnessPolicy","Gesture","spawnDynamicRequests","node","renderedSearch","tree","hash","prefetchSeed","metadata","varyPath","computeDynamicStaleAt","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","fetchServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","flightData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","discoverKnownRoute","search","createHrefFromUrl","response","staticStageResponse","isResponsePartial","resolveStaleAt","s","then","staleAt","buildId","get","NEXT_NAV_DEPLOYMENT_ID_HEADER","b","writePrerenderResponseIntoCache","f","h","r","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","PPRRuntime","flightDatas","headVaryParams","rootVaryParamsIterable","revealAfter","isJavaScriptURLString","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","computeChangedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","ScrollBehavior","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","currentTree","dynamicStaleTimeSeconds","baseTree","baseData","segmentPath","treePatch","seedData","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","acc","convertRootFlightRouterStateToRouteTree","baseRouterState","index","length","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","parallelRouteKey","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","SubtreePrefetchHints","childHints","propagateSubtreeBits","isEmptySeedDataPartial","beginNavigationLockPrefetch","navigationLockPrefetch","schedulePrefetchTask","PrefetchPriority","promise","updateCapturedSPAToTree"],"mappings":";;;;;;;;;;;;;;;;;;;IAuoBgBA,sBAAsB;eAAtBA;;IAmCAC,sBAAsB;eAAtBA;;IA0IAC,0BAA0B;eAA1BA;;IA4CAC,4BAA4B;eAA5BA;;IAtyBAC,QAAQ;eAARA;;IAgKAC,oBAAoB;eAApBA;;;gCA9MT;qCAE6B;gCAQ7B;mCAC2B;2BACY;uBAYvC;kCAC4B;0BACmB;2BACjB;uBACW;uBACJ;oCAGb;oCACI;+BACG;yBACyB;iCAChB;AAUxC,SAASD,SACdE,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC;IAEhC,IAAIC,iBAAwC;IAE5C,oEAAoE;IACpE,0EAA0E;IAC1E,wEAAwE;IACxE,sEAAsE;IACtE,6DAA6D;IAC7D,aAAa;IACb,IAAIC,QAAQC,GAAG,CAACC,yBAAyB,EAAE;QACzC,MAAM,EAAEC,kBAAkB,EAAE,GAC1BC,QAAQ;QACV,IAAID,sBAAsB;YACxB,2EAA2E;YAC3E,yEAAyE;YACzE,0EAA0E;YAC1E,0BAA0B;YAC1BJ,iBAAiBM,IAAAA,qCAAqB;YACtC,OAAOC,2BACLjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;QAEJ;IACF;IAEA,OAAOQ,aACLlB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;AAEJ;AAEA,SAASQ,aACPlB,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,c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MAAM,EAAE0L,2BAA2B,EAAE,GACnCjL,QAAQ;IACV,MAAMkL,yBAAyBD;IAC/BE,IAAAA,+BAAoB,EAClB5K,UACAjB,0BACAwC,eACAsJ,uBAAgB,CAAC1G,OAAO,EACxB,MACAwG;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBG,OAAO;IACtC;IAEA,uEAAuE;IACvE,wCAAwC;IACxC,MAAMnG,SAAS,MAAM/E,aACnBlB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;IAGF,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAACuF,OAAOwC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAE0D,uBAAuB,EAAE,GAC/BtL,QAAQ;QACVsL,wBAAwBhM,0BAA0B4F,OAAOjB,IAAI;IAC/D;IAEA,OAAOiB;AACT","ignoreList":[0]} |
@@ -71,2 +71,16 @@ import type { FlightRouterState } from '../../../shared/lib/app-router-types'; | ||
| hasBackgroundWork: boolean; | ||
| /** | ||
| * Set during a pass when the task spawned a segment request, or encountered | ||
| * one that was already in flight (a Pending entry) — i.e. a response the | ||
| * pass cares about but hasn't received yet. The task blocks instead of | ||
| * advancing, and is re-pinged as each awaited entry settles; see | ||
| * blockTaskOnPendingResponse for the full rationale. Each ping re-runs a | ||
| * full traversal for the task, so expect roughly one re-pass per settling | ||
| * entry. Re-runs don't re-spawn revalidations: when a completed | ||
| * revalidation was re-keyed, its upsert evicts any superseded entry that | ||
| * would shadow it (see upsertSegmentEntry in cache.ts), and when its upsert | ||
| * was declined, the settled entry left in the revalidation slot dedupes | ||
| * further attempts (see pingFullSegmentRevalidation). | ||
| */ | ||
| hasPendingResponses: boolean; | ||
| spawnedRuntimePrefetches: Set<SegmentRequestKey> | null; | ||
@@ -73,0 +87,0 @@ /** |
@@ -63,3 +63,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build. | ||
| const _isnextroutererror = require("./components/is-next-router-error"); | ||
| const version = "16.3.0-canary.97"; | ||
| const version = "16.3.0-canary.99"; | ||
| let router; | ||
@@ -66,0 +66,0 @@ const emitter = (0, _mitt.default)(); |
@@ -1,1 +0,1 @@ | ||
| (function(){var e={527:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:true});function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}var n=r(629);var s=r(703);var i=r(611);var o=_interopRequireDefault(i);var a=r(692);var u=_interopRequireDefault(a);var c=r(366);var l=r(958);var f=new(0,l.Logger)("utils getUrlByRequestOptions");function normalizeClientRequestEndArgs(...e){f.info("arguments",e);const t=new Array(3).fill(null).map(((t,r)=>e[r]||t));t.sort(((e,r)=>{if(typeof e==="function"){return 1}if(typeof r==="function"){return-1}if(typeof e==="string"&&typeof r==="string"){return t.indexOf(e)-t.indexOf(r)}return 0}));f.info("normalized args",t);return t}var h=new(0,l.Logger)("http normalizeWriteArgs");function normalizeClientRequestWriteArgs(e){h.info("normalizing ClientRequest.write arguments...",e);const t=e[0];const r=typeof e[1]==="string"?e[1]:void 0;const n=typeof e[1]==="function"?e[1]:e[2];const s=[t,r,n];h.info("successfully normalized ClientRequest.write arguments:",s);return s}var p=r(203);var d=Symbol("isClone");function cloneIncomingMessage(e){const t=e.pipe(new(0,p.PassThrough));inheritProperties(e,t);const r=Object.create(i.IncomingMessage.prototype);getPrototypes(t).forEach((e=>{inheritProperties(e,r)}));Object.setPrototypeOf(t,r);Object.defineProperty(t,d,{enumerable:true,value:true});return t}function getPrototypes(e){const t=[];let r=e;while(r=Object.getPrototypeOf(r)){t.push(r)}return t}function inheritProperties(e,t){const r=[...Object.getOwnPropertyNames(e),...Object.getOwnPropertySymbols(e)];for(const n of r){if(t.hasOwnProperty(n)){continue}const r=Object.getOwnPropertyDescriptor(e,n);if(!r){continue}Object.defineProperty(t,n,r)}}var g=r(955);function createResponse(e){const t=new ReadableStream({start(t){e.on("data",(e=>t.enqueue(e)));e.on("end",(()=>t.close()))}});return new Response(t,{status:e.statusCode,statusText:e.statusMessage,headers:g.objectToHeaders.call(void 0,e.headers)})}function createRequest(e){const t=new(0,g.Headers);const r=e.getHeaders();for(const e in r){const n=r[e];if(!n){continue}const s=Array.prototype.concat([],n);for(const r of s){t.append(e,r.toString())}}const n=e.method||"GET";return new Request(e.url,{method:n,headers:t,credentials:"same-origin",body:n==="HEAD"||n==="GET"?null:e.requestBuffer})}var m=r(505);var v=class extends i.ClientRequest{constructor([e,t,r],n){super(t,r);this.chunks=[];this.responseSource="mock";this.logger=n.logger.extend(`request ${t.method} ${e.href}`);this.logger.info("constructing ClientRequest using options:",{url:e,requestOptions:t,callback:r});this.url=e;this.emitter=n.emitter;this.requestBuffer=null;this.response=new(0,i.IncomingMessage)(this.socket)}writeRequestBodyChunk(e,t){if(e==null){return}if(this.requestBuffer==null){this.requestBuffer=Buffer.from([])}const r=Buffer.isBuffer(e)?e:Buffer.from(e,t);this.requestBuffer=Buffer.concat([this.requestBuffer,r])}write(...e){var t;const[r,n,s]=normalizeClientRequestWriteArgs(e);this.logger.info("write:",{chunk:r,encoding:n,callback:s});this.chunks.push({chunk:r,encoding:n});this.writeRequestBodyChunk(r,n);this.logger.info("chunk successfully stored!",(t=this.requestBuffer)==null?void 0:t.byteLength);if(!r||r.length===0){this.logger.info("written chunk is empty, skipping callback...")}else{s==null?void 0:s()}return true}end(...e){this.logger.info("end",e);const t=n.uuidv4.call(void 0);const[r,s,i]=normalizeClientRequestEndArgs(...e);this.logger.info("normalized arguments:",{chunk:r,encoding:s,callback:i});this.writeRequestBodyChunk(r,s||void 0);const o=createRequest(this);const a=n.toInteractiveRequest.call(void 0,o);if(this.getHeader("X-Request-Id")!=null){this.removeHeader("X-Request-Id");return this.passthrough(r,s,i)}this.logger.info('emitting the "request" event for %d listener(s)...',this.emitter.listenerCount("request"));this.emitter.emit("request",{request:a,requestId:t});c.until.call(void 0,(async()=>{await this.emitter.untilIdle("request",(({args:[{requestId:e}]})=>e===t));const[e]=await a.respondWith.invoked();this.logger.info("event.respondWith called with:",e);return e})).then((e=>{this.logger.info("the listeners promise awaited!");if(!this.headersSent){for(const[e,t]of o.headers){this.setHeader(e,t)}}if(e.error){this.logger.info("encountered resolver exception, aborting request...",e.error);this.emit("error",e.error);this.terminate();return this}const n=e.data;if(n){const e=n.clone();this.logger.info("received mocked response:",n);this.responseSource="mock";this.respondWith(n);this.logger.info(n.status,n.statusText,"(MOCKED)");i==null?void 0:i();this.logger.info('emitting the custom "response" event...');this.emitter.emit("response",{response:e,isMockedResponse:true,request:o,requestId:t});this.logger.info("request (mock) is completed");return this}this.logger.info("no mocked response received!");this.once("response-internal",(e=>{this.logger.info(e.statusCode,e.statusMessage);this.logger.info("original response headers:",e.headers);this.logger.info('emitting the custom "response" event...');this.emitter.emit("response",{response:createResponse(e),isMockedResponse:false,request:o,requestId:t})}));return this.passthrough(r,s,i)}));return this}emit(e,...t){this.logger.info("emit: %s",e);if(e==="response"){this.logger.info('found "response" event, cloning the response...');try{const r=t[0];const n=cloneIncomingMessage(r);const s=cloneIncomingMessage(r);this.emit("response-internal",s);this.logger.info('response successfully cloned, emitting "response" event...');return super.emit(e,n,...t.slice(1))}catch(r){this.logger.info("error when cloning response:",r);return super.emit(e,...t)}}if(e==="error"){const e=t[0];const r=e.code||"";this.logger.info("error:\n",e);if(this.responseSource==="mock"&&v.suppressErrorCodes.includes(r)){if(!this.capturedError){this.capturedError=e;this.logger.info("captured the first error:",this.capturedError)}return false}}return super.emit(e,...t)}passthrough(e,t,r){this.responseSource="bypass";if(this.capturedError){this.emit("error",this.capturedError);return this}this.logger.info("writing request chunks...",this.chunks);for(const{chunk:e,encoding:t}of this.chunks){if(t){super.write(e,t)}else{super.write(e)}}this.once("error",(e=>{this.logger.info("original request error:",e)}));this.once("abort",(()=>{this.logger.info("original request aborted!")}));this.once("response-internal",(e=>{this.logger.info(e.statusCode,e.statusMessage);this.logger.info("original response headers:",e.headers)}));this.logger.info("performing original request...");return super.end(...[e,t,r].filter(Boolean))}respondWith(e){this.logger.info("responding with a mocked response...",e);Object.defineProperties(this,{writableFinished:{value:true},writableEnded:{value:true}});this.emit("finish");const{status:t,statusText:r,headers:n,body:s}=e;this.response.statusCode=t;this.response.statusMessage=r;if(n){this.response.headers={};n.forEach(((e,t)=>{this.response.rawHeaders.push(t,e);const r=t.toLowerCase();const n=this.response.headers[r];this.response.headers[r]=n?Array.prototype.concat([],n,e):e}))}this.logger.info("mocked response headers ready:",n);const i=new(0,m.DeferredPromise);const finishResponseStream=()=>{this.logger.info("finished response stream!");i.resolve()};if(s){const e=s.getReader();const readNextChunk=async()=>{const{done:t,value:r}=await e.read();if(t){finishResponseStream();return}this.response.emit("data",r);return readNextChunk()};readNextChunk()}else{finishResponseStream()}this.res=this.response;this.emit("response",this.response);i.then((()=>{this.logger.info("finalizing response...");this.response.push(null);this.response.complete=true;this.response.emit("end");this.terminate()}))}terminate(){var e;(e=this.agent)==null?void 0:e.destroy()}};var y=v;y.suppressErrorCodes=["ENOTFOUND","ECONNREFUSED","ECONNRESET","EAI_AGAIN"];function getRequestOptionsByUrl(e){const t={method:"GET",protocol:e.protocol,hostname:typeof e.hostname==="string"&&e.hostname.startsWith("[")?e.hostname.slice(1,-1):e.hostname,host:e.host,path:`${e.pathname}${e.search||""}`};if(!!e.port){t.port=Number(e.port)}if(e.username||e.password){t.auth=`${e.username}:${e.password}`}return t}var b=new(0,l.Logger)("utils getUrlByRequestOptions");var O="/";var w="http:";var q="localhost";var x=443;function getAgent(e){return e.agent instanceof i.Agent?e.agent:void 0}function getProtocolByRequestOptions(e){var t;if(e.protocol){return e.protocol}const r=getAgent(e);const n=r==null?void 0:r.protocol;if(n){return n}const s=getPortByRequestOptions(e);const i=e.cert||s===x;return i?"https:":((t=e.uri)==null?void 0:t.protocol)||w}function getPortByRequestOptions(e){if(e.port){return Number(e.port)}if(e.hostname!=null){const[,t]=e.hostname.match(/:(\d+)$/)||[];if(t!=null){return Number(t)}}const t=getAgent(e);if(t==null?void 0:t.options.port){return Number(t.options.port)}if(t==null?void 0:t.defaultPort){return Number(t.defaultPort)}return void 0}function getHostByRequestOptions(e){const{hostname:t,host:r}=e;if(t!=null){return t.replace(/:\d+$/,"")}return r||q}function getAuthByRequestOptions(e){if(e.auth){const[t,r]=e.auth.split(":");return{username:t,password:r}}}function isRawIPv6Address(e){return e.includes(":")&&!e.startsWith("[")&&!e.endsWith("]")}function getHostname(e,t){const r=typeof t!=="undefined"?`:${t}`:"";if(isRawIPv6Address(e)){return`[${e}]${r}`}if(typeof t==="undefined"){return e}return`${e}${r}`}function getUrlByRequestOptions(e){b.info("request options",e);if(e.uri){b.info('constructing url from explicitly provided "options.uri": %s',e.uri);return new URL(e.uri.href)}b.info("figuring out url from request options...");const t=getProtocolByRequestOptions(e);b.info("protocol",t);const r=getHostByRequestOptions(e);b.info("host",r);const n=getPortByRequestOptions(e);b.info("port",n);const s=getHostname(r,n);b.info("hostname",s);const i=e.path||O;b.info("path",i);const o=getAuthByRequestOptions(e);b.info("credentials",o);const a=o?`${o.username}:${o.password}@`:"";b.info("auth string:",a);const u=new URL(`${t}//${a}${s}${i}`);b.info("created url:",u);return u}var j=new(0,l.Logger)("cloneObject");function isPlainObject(e){var t;j.info("is plain object?",e);if(e==null||!((t=e.constructor)==null?void 0:t.name)){j.info("given object is undefined, not a plain object...");return false}j.info("checking the object constructor:",e.constructor.name);return e.constructor.name==="Object"}function cloneObject(e){j.info("cloning object:",e);const t=Object.entries(e).reduce(((e,[t,r])=>{j.info("analyzing key-value pair:",t,r);e[t]=isPlainObject(r)?cloneObject(r):r;return e}),{});return isPlainObject(e)?t:Object.assign(Object.getPrototypeOf(e),t)}function isObject(e){return Object.prototype.toString.call(e)==="[object Object]"}var P=new(0,l.Logger)("http normalizeClientRequestArgs");function resolveRequestOptions(e,t){if(typeof e[1]==="undefined"||typeof e[1]==="function"){P.info("request options not provided, deriving from the url",t);return getRequestOptionsByUrl(t)}if(e[1]){P.info("has custom RequestOptions!",e[1]);const r=getRequestOptionsByUrl(t);P.info("derived RequestOptions from the URL:",r);P.info("cloning RequestOptions...");const n=cloneObject(e[1]);P.info("successfully cloned RequestOptions!",n);return{...r,...n}}P.info("using an empty object as request options");return{}}function resolveCallback(e){return typeof e[1]==="function"?e[1]:e[2]}function normalizeClientRequestArgs(e,...t){let r;let n;let s;P.info("arguments",t);P.info("using default protocol:",e);if(typeof t[0]==="string"){P.info("first argument is a location string:",t[0]);r=new URL(t[0]);P.info("created a url:",r);const e=getRequestOptionsByUrl(r);P.info("request options from url:",e);n=resolveRequestOptions(t,r);P.info("resolved request options:",n);s=resolveCallback(t)}else if(t[0]instanceof URL){r=t[0];P.info("first argument is a URL:",r);n=resolveRequestOptions(t,r);P.info("derived request options:",n);s=resolveCallback(t)}else if("hash"in t[0]&&!("method"in t[0])){const[r]=t;P.info("first argument is a legacy URL:",r);if(r.hostname===null){P.info("given legacy URL is relative (no hostname)");return isObject(t[1])?normalizeClientRequestArgs(e,{path:r.path,...t[1]},t[2]):normalizeClientRequestArgs(e,{path:r.path},t[1])}P.info("given legacy url is absolute");const n=new URL(r.href);return t[1]===void 0?normalizeClientRequestArgs(e,n):typeof t[1]==="function"?normalizeClientRequestArgs(e,n,t[1]):normalizeClientRequestArgs(e,n,t[1],t[2])}else if(isObject(t[0])){n=t[0];P.info("first argument is RequestOptions:",n);n.protocol=n.protocol||e;P.info("normalized request options:",n);r=getUrlByRequestOptions(n);P.info("created a URL from RequestOptions:",r.href);s=resolveCallback(t)}else{throw new Error(`Failed to construct ClientRequest with these parameters: ${t}`)}n.protocol=n.protocol||r.protocol;n.method=n.method||"GET";if(typeof n.agent==="undefined"){const e=n.protocol==="https:"?new(0,a.Agent)({rejectUnauthorized:n.rejectUnauthorized}):new(0,i.Agent);n.agent=e;P.info("resolved fallback agent:",e)}if(!n._defaultAgent){P.info('has no default agent, setting the default agent for "%s"',n.protocol);n._defaultAgent=n.protocol==="https:"?a.globalAgent:i.globalAgent}P.info("successfully resolved url:",r.href);P.info("successfully resolved options:",n);P.info("successfully resolved callback:",s);return[r,n,s]}function get(e,t){return(...r)=>{const n=normalizeClientRequestArgs(`${e}:`,...r);const s=new y(n,t);s.end();return s}}var E=new(0,l.Logger)("http request");function request(e,t){return(...r)=>{E.info('request call (protocol "%s"):',e,r);const n=normalizeClientRequestArgs(`${e}:`,...r);return new y(n,t)}}var L=class extends s.Interceptor{constructor(){super(L.interceptorSymbol);this.modules=new Map;this.modules.set("http",o.default);this.modules.set("https",u.default)}setup(){const e=this.logger.extend("setup");for(const[t,r]of this.modules){const{request:n,get:s}=r;this.subscriptions.push((()=>{r.request=n;r.get=s;e.info('native "%s" module restored!',t)}));const i={emitter:this.emitter,logger:this.logger};r.request=request(t,i);r.get=get(t,i);e.info('native "%s" module patched!',t)}}};var _=L;_.interceptorSymbol=Symbol("http");t.ClientRequestInterceptor=_},703:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=(e=>true?require:0)((function(e){if(true)return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')}));var s=r(958);var i=r(932);function nextTick(e){setTimeout(e,0)}var o=class extends i.Emitter{constructor(){super();this.logger=new(0,s.Logger)("async-event-emitter");this.queue=new Map;this.readyState="ACTIVE"}on(e,t){const r=this.logger.extend("on");r.info('adding "%s" listener...',e);if(this.readyState==="DEACTIVATED"){r.info("the emitter is destroyed, skipping!");return this}return super.on(e,(async(...n)=>{const s=this.openListenerQueue(e);r.info('awaiting the "%s" listener...',e);s.push({args:n,done:new Promise((async(s,i)=>{try{await t(...n);s();r.info('"%s" listener has resolved!',e)}catch(e){r.info('"%s" listener has rejected!',e);i(e)}}))})}))}emit(e,...t){const r=this.logger.extend("emit");r.info('emitting "%s" event...',e);if(this.readyState==="DEACTIVATED"){r.info("the emitter is destroyed, skipping!");return false}if(this.isInternalEventName(e)){return super.emit(e,...t)}this.openListenerQueue(e);r.info('appending a one-time cleanup "%s" listener...',e);this.once(e,(()=>{nextTick((()=>{this.queue.delete(e);r.info('cleaned up "%s" listeners queue!',e)}))}));return super.emit(e,...t)}async untilIdle(e,t=()=>true){const r=this.queue.get(e)||[];await Promise.all(r.filter(t).map((({done:e})=>e))).finally((()=>{this.queue.delete(e)}))}openListenerQueue(e){const t=this.logger.extend("openListenerQueue");t.info('opening "%s" listeners queue...',e);const r=this.queue.get(e);if(!r){t.info("no queue found, creating one...");this.queue.set(e,[]);return[]}t.info("returning an exising queue:",r);return r}removeAllListeners(e){const t=this.logger.extend("removeAllListeners");t.info("event:",e);if(e){this.queue.delete(e);t.info('cleared the "%s" listeners queue!',e,this.queue.get(e))}else{this.queue.clear();t.info("cleared the listeners queue!",this.queue)}return super.removeAllListeners(e)}activate(){const e=this.logger.extend("activate");this.readyState="ACTIVE";e.info("set state to:",this.readyState)}deactivate(){const e=this.logger.extend("deactivate");e.info("removing all listeners...");this.removeAllListeners();this.readyState="DEACTIVATED";e.info("set state to:",this.readyState)}isInternalEventName(e){return e==="newListener"||e==="removeListener"}};function getGlobalSymbol(e){return globalThis[e]||void 0}function setGlobalSymbol(e,t){globalThis[e]=t}function deleteGlobalSymbol(e){delete globalThis[e]}var a=(e=>{e["INACTIVE"]="INACTIVE";e["APPLYING"]="APPLYING";e["APPLIED"]="APPLIED";e["DISPOSING"]="DISPOSING";e["DISPOSED"]="DISPOSED";return e})(a||{});var u=class{constructor(e){this.symbol=e;this.readyState="INACTIVE";this.emitter=new o;this.subscriptions=[];this.logger=new(0,s.Logger)(e.description);this.emitter.setMaxListeners(0);this.logger.info("constructing the interceptor...")}checkEnvironment(){return true}apply(){const e=this.logger.extend("apply");e.info("applying the interceptor...");if(this.readyState==="APPLIED"){e.info("intercepted already applied!");return}const t=this.checkEnvironment();if(!t){e.info("the interceptor cannot be applied in this environment!");return}this.readyState="APPLYING";this.emitter.activate();e.info("activated the emiter!",this.emitter.readyState);const r=this.getInstance();if(r){e.info("found a running instance, reusing...");this.on=(t,n)=>{e.info('proxying the "%s" listener',t);r.emitter.addListener(t,n);this.subscriptions.push((()=>{r.emitter.removeListener(t,n);e.info('removed proxied "%s" listener!',t)}))};this.readyState="APPLIED";return}e.info("no running instance found, setting up a new instance...");this.setup();this.setInstance();this.readyState="APPLIED"}setup(){}on(e,t){const r=this.logger.extend("on");if(this.readyState==="DISPOSING"||this.readyState==="DISPOSED"){r.info("cannot listen to events, already disposed!");return}r.info('adding "%s" event listener:',e,t.name);this.emitter.on(e,t)}dispose(){const e=this.logger.extend("dispose");if(this.readyState==="DISPOSED"){e.info("cannot dispose, already disposed!");return}e.info("disposing the interceptor...");this.readyState="DISPOSING";if(!this.getInstance()){e.info("no interceptors running, skipping dispose...");return}this.clearInstance();e.info("global symbol deleted:",getGlobalSymbol(this.symbol));if(this.subscriptions.length>0){e.info("disposing of %d subscriptions...",this.subscriptions.length);for(const e of this.subscriptions){e()}this.subscriptions=[];e.info("disposed of all subscriptions!",this.subscriptions.length)}this.emitter.deactivate();e.info("destroyed the listener!");this.readyState="DISPOSED"}getInstance(){var e;const t=getGlobalSymbol(this.symbol);this.logger.info("retrieved global instance:",(e=t==null?void 0:t.constructor)==null?void 0:e.name);return t}setInstance(){setGlobalSymbol(this.symbol,this);this.logger.info("set global instance!",this.symbol.description)}clearInstance(){deleteGlobalSymbol(this.symbol);this.logger.info("cleared global instance!",this.symbol.description)}};t.__require=n;t.getGlobalSymbol=getGlobalSymbol;t.deleteGlobalSymbol=deleteGlobalSymbol;t.InterceptorReadyState=a;t.Interceptor=u},629:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:true});var n=r(552);function createLazyCallback(e={}){let t=0;let r;let n;const s=new Promise((e=>{n=e})).finally((()=>{clearTimeout(r)}));const fn=function(...r){var s;if(e.maxCalls&&t>=e.maxCalls){(s=e.maxCallsCallback)==null?void 0:s.call(e)}n(r);t++};fn.invoked=async()=>{r=setTimeout((()=>{n([])}),0);return s};return fn}function toInteractiveRequest(e){Object.defineProperty(e,"respondWith",{writable:false,enumerable:true,value:createLazyCallback({maxCalls:1,maxCallsCallback(){throw new Error(n.format.call(void 0,'Failed to respond to "%s %s" request: the "request" event has already been responded to.',e.method,e.url))}})});return e}function uuidv4(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(e){const t=Math.random()*16|0;const r=e=="x"?t:t&3|8;return r.toString(16)}))}t.toInteractiveRequest=toInteractiveRequest;t.uuidv4=uuidv4},761:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:true});t.DeferredPromise=void 0;const n=r(835);class DeferredPromise extends Promise{#e;resolve;reject;constructor(e=null){const t=(0,n.createDeferredExecutor)();super(((r,n)=>{t(r,n);e?.(t.resolve,t.reject)}));this.#e=t;this.resolve=this.#e.resolve;this.reject=this.#e.reject}get state(){return this.#e.state}get rejectionReason(){return this.#e.rejectionReason}then(e,t){return this.#t(super.then(e,t))}catch(e){return this.#t(super.catch(e))}finally(e){return this.#t(super.finally(e))}#t(e){return Object.defineProperties(e,{resolve:{configurable:true,value:this.resolve},reject:{configurable:true,value:this.reject}})}}t.DeferredPromise=DeferredPromise},835:function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:true});t.createDeferredExecutor=void 0;function createDeferredExecutor(){const executor=(e,t)=>{executor.state="pending";executor.resolve=t=>{if(executor.state!=="pending"){return}executor.result=t;const onFulfilled=e=>{executor.state="fulfilled";return e};return e(t instanceof Promise?t:Promise.resolve(t).then(onFulfilled))};executor.reject=e=>{if(executor.state!=="pending"){return}queueMicrotask((()=>{executor.state="rejected"}));return t(executor.rejectionReason=e)}};return executor}t.createDeferredExecutor=createDeferredExecutor},505:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){if(n===undefined)n=r;var s=Object.getOwnPropertyDescriptor(t,r);if(!s||("get"in s?!t.__esModule:s.writable||s.configurable)){s={enumerable:true,get:function(){return t[r]}}}Object.defineProperty(e,n,s)}:function(e,t,r,n){if(n===undefined)n=r;e[n]=t[r]});var s=this&&this.__exportStar||function(e,t){for(var r in e)if(r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r))n(t,e,r)};Object.defineProperty(t,"__esModule",{value:true});s(r(835),t);s(r(761),t)},958:function(e,t,r){var n=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var o=Object.prototype.hasOwnProperty;var __export=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:true})};var __copyProps=(e,t,r,a)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let u of i(t))if(!o.call(e,u)&&u!==r)n(e,u,{get:()=>t[u],enumerable:!(a=s(t,u))||a.enumerable})}return e};var __toCommonJS=e=>__copyProps(n({},"__esModule",{value:true}),e);var a={};__export(a,{Logger:()=>h});e.exports=__toCommonJS(a);var u=r(566);var c=r(552);var l={};__export(l,{blue:()=>blue,gray:()=>gray,green:()=>green,red:()=>red,yellow:()=>yellow});function yellow(e){return`[33m${e}[0m`}function blue(e){return`[34m${e}[0m`}function gray(e){return`[90m${e}[0m`}function red(e){return`[31m${e}[0m`}function green(e){return`[32m${e}[0m`}var f=(0,u.isNodeProcess)();var h=class{constructor(e){this.name=e;this.prefix=`[${this.name}]`;const t=getVariable("DEBUG");const r=getVariable("LOG_LEVEL");const n=t==="1"||t==="true"||typeof t!=="undefined"&&this.name.startsWith(t);if(n){this.debug=isDefinedAndNotEquals(r,"debug")?noop:this.debug;this.info=isDefinedAndNotEquals(r,"info")?noop:this.info;this.success=isDefinedAndNotEquals(r,"success")?noop:this.success;this.warning=isDefinedAndNotEquals(r,"warning")?noop:this.warning;this.error=isDefinedAndNotEquals(r,"error")?noop:this.error}else{this.info=noop;this.success=noop;this.warning=noop;this.error=noop;this.only=noop}}prefix;extend(e){return new h(`${this.name}:${e}`)}debug(e,...t){this.logEntry({level:"debug",message:gray(e),positionals:t,prefix:this.prefix,colors:{prefix:"gray"}})}info(e,...t){this.logEntry({level:"info",message:e,positionals:t,prefix:this.prefix,colors:{prefix:"blue"}});const r=new p;return(e,...t)=>{r.measure();this.logEntry({level:"info",message:`${e} ${gray(`${r.deltaTime}ms`)}`,positionals:t,prefix:this.prefix,colors:{prefix:"blue"}})}}success(e,...t){this.logEntry({level:"info",message:e,positionals:t,prefix:`✔ ${this.prefix}`,colors:{timestamp:"green",prefix:"green"}})}warning(e,...t){this.logEntry({level:"warning",message:e,positionals:t,prefix:`⚠ ${this.prefix}`,colors:{timestamp:"yellow",prefix:"yellow"}})}error(e,...t){this.logEntry({level:"error",message:e,positionals:t,prefix:`✖ ${this.prefix}`,colors:{timestamp:"red",prefix:"red"}})}only(e){e()}createEntry(e,t){return{timestamp:new Date,level:e,message:t}}logEntry(e){const{level:t,message:r,prefix:n,colors:s,positionals:i=[]}=e;const o=this.createEntry(t,r);const a=s?.timestamp||"gray";const u=s?.prefix||"gray";const c={timestamp:l[a],prefix:l[u]};const f=this.getWriter(t);f([c.timestamp(this.formatTimestamp(o.timestamp))].concat(n!=null?c.prefix(n):[]).concat(serializeInput(r)).join(" "),...i.map(serializeInput))}formatTimestamp(e){return`${e.toLocaleTimeString("en-GB")}:${e.getMilliseconds()}`}getWriter(e){switch(e){case"debug":case"success":case"info":{return log}case"warning":{return warn}case"error":{return error}}}};var p=class{startTime;endTime;deltaTime;constructor(){this.startTime=performance.now()}measure(){this.endTime=performance.now();const e=this.endTime-this.startTime;this.deltaTime=e.toFixed(2)}};var noop=()=>void 0;function log(e,...t){if(f){process.stdout.write((0,c.format)(e,...t)+"\n");return}console.log(e,...t)}function warn(e,...t){if(f){process.stderr.write((0,c.format)(e,...t)+"\n");return}console.warn(e,...t)}function error(e,...t){if(f){process.stderr.write((0,c.format)(e,...t)+"\n");return}console.error(e,...t)}function getVariable(e){if(f){return process.env[e]}return globalThis[e]?.toString()}function isDefinedAndNotEquals(e,t){return e!==void 0&&e!==t}function serializeInput(e){if(typeof e==="undefined"){return"undefined"}if(e===null){return"null"}if(typeof e==="string"){return e}if(typeof e==="object"){return JSON.stringify(e)}return e.toString()}},366:function(e){var t=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var __export=(e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:true})};var __copyProps=(e,i,o,a)=>{if(i&&typeof i==="object"||typeof i==="function"){for(let u of n(i))if(!s.call(e,u)&&u!==o)t(e,u,{get:()=>i[u],enumerable:!(a=r(i,u))||a.enumerable})}return e};var __toCommonJS=e=>__copyProps(t({},"__esModule",{value:true}),e);var i={};__export(i,{until:()=>until});e.exports=__toCommonJS(i);var until=async e=>{try{const t=await e().catch((e=>{throw e}));return{error:null,data:t}}catch(e){return{error:e,data:null}}};0&&0},955:function(e){var t=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var __export=(e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:true})};var __copyProps=(e,i,o,a)=>{if(i&&typeof i==="object"||typeof i==="function"){for(let u of n(i))if(!s.call(e,u)&&u!==o)t(e,u,{get:()=>i[u],enumerable:!(a=r(i,u))||a.enumerable})}return e};var __toCommonJS=e=>__copyProps(t({},"__esModule",{value:true}),e);var i={};__export(i,{Headers:()=>f,flattenHeadersList:()=>flattenHeadersList,flattenHeadersObject:()=>flattenHeadersObject,headersToList:()=>headersToList,headersToObject:()=>headersToObject,headersToString:()=>headersToString,listToHeaders:()=>listToHeaders,objectToHeaders:()=>objectToHeaders,reduceHeadersObject:()=>reduceHeadersObject,stringToHeaders:()=>stringToHeaders});e.exports=__toCommonJS(i);var o=/[^a-z0-9\-#$%&'*+.^_`|~]/i;function normalizeHeaderName(e){if(typeof e!=="string"){e=String(e)}if(o.test(e)||e.trim()===""){throw new TypeError("Invalid character in header field name")}return e.toLowerCase()}function normalizeHeaderValue(e){if(typeof e!=="string"){e=String(e)}return e}var a=Symbol("normalizedHeaders");var u=Symbol("rawHeaderNames");var c,l;var f=class{constructor(e){this[c]={};this[l]=new Map;if(["Headers","HeadersPolyfill"].includes(e==null?void 0:e.constructor.name)||e instanceof f){const t=e;t.forEach(((e,t)=>{this.append(t,e)}),this)}else if(Array.isArray(e)){e.forEach((([e,t])=>{this.append(e,Array.isArray(t)?t.join(", "):t)}))}else if(e){Object.getOwnPropertyNames(e).forEach((t=>{const r=e[t];this.append(t,Array.isArray(r)?r.join(", "):r)}))}}[(c=a,l=u,Symbol.iterator)](){return this.entries()}*keys(){for(const e of Object.keys(this[a])){yield e}}*values(){for(const e of Object.values(this[a])){yield e}}*entries(){for(const e of Object.keys(this[a])){yield[e,this.get(e)]}}get(e){return this[a][normalizeHeaderName(e)]||null}set(e,t){const r=normalizeHeaderName(e);this[a][r]=normalizeHeaderValue(t);this[u].set(r,e)}append(e,t){const r=normalizeHeaderName(e);let n=this.has(r)?`${this.get(r)}, ${t}`:t;this.set(e,n)}delete(e){if(!this.has(e)){return}const t=normalizeHeaderName(e);delete this[a][t];this[u].delete(t)}all(){return this[a]}raw(){const e={};for(const[t,r]of this.entries()){e[this[u].get(t)]=r}return e}has(e){return this[a].hasOwnProperty(normalizeHeaderName(e))}forEach(e,t){for(const r in this[a]){if(this[a].hasOwnProperty(r)){e.call(t,this[a][r],r,this)}}}};function headersToList(e){const t=[];e.forEach(((e,r)=>{const n=e.includes(",")?e.split(",").map((e=>e.trim())):e;t.push([r,n])}));return t}function headersToString(e){const t=headersToList(e);const r=t.map((([e,t])=>{const r=[].concat(t);return`${e}: ${r.join(", ")}`}));return r.join("\r\n")}var h=["user-agent"];function headersToObject(e){const t={};e.forEach(((e,r)=>{const n=!h.includes(r.toLowerCase())&&e.includes(",");t[r]=n?e.split(",").map((e=>e.trim())):e}));return t}function stringToHeaders(e){const t=e.trim().split(/[\r\n]+/);return t.reduce(((e,t)=>{if(t.trim()===""){return e}const r=t.split(": ");const n=r.shift();const s=r.join(": ");e.append(n,s);return e}),new f)}function listToHeaders(e){const t=new f;e.forEach((([e,r])=>{const n=[].concat(r);n.forEach((r=>{t.append(e,r)}))}));return t}function reduceHeadersObject(e,t,r){return Object.keys(e).reduce(((r,n)=>t(r,n,e[n])),r)}function objectToHeaders(e){return reduceHeadersObject(e,((e,t,r)=>{const n=[].concat(r).filter(Boolean);n.forEach((r=>{e.append(t,r)}));return e}),new f)}function flattenHeadersList(e){return e.map((([e,t])=>[e,[].concat(t).join(", ")]))}function flattenHeadersObject(e){return reduceHeadersObject(e,((e,t,r)=>{e[t]=[].concat(r).join(", ");return e}),{})}0&&0},566:function(e){var t=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var __export=(e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:true})};var __copyProps=(e,i,o,a)=>{if(i&&typeof i==="object"||typeof i==="function"){for(let u of n(i))if(!s.call(e,u)&&u!==o)t(e,u,{get:()=>i[u],enumerable:!(a=r(i,u))||a.enumerable})}return e};var __toCommonJS=e=>__copyProps(t({},"__esModule",{value:true}),e);var i={};__export(i,{isNodeProcess:()=>isNodeProcess});e.exports=__toCommonJS(i);function isNodeProcess(){if(typeof navigator!=="undefined"&&navigator.product==="ReactNative"){return true}if(typeof process!=="undefined"){const e=process.type;if(e==="renderer"||e==="worker"){return false}return!!(process.versions&&process.versions.node)}return false}0&&0},552:function(e){"use strict";var t=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var __export=(e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:true})};var __copyProps=(e,i,o,a)=>{if(i&&typeof i==="object"||typeof i==="function"){for(let u of n(i))if(!s.call(e,u)&&u!==o)t(e,u,{get:()=>i[u],enumerable:!(a=r(i,u))||a.enumerable})}return e};var __toCommonJS=e=>__copyProps(t({},"__esModule",{value:true}),e);var i={};__export(i,{InvariantError:()=>u,format:()=>format,invariant:()=>invariant});e.exports=__toCommonJS(i);var o=/(%?)(%([sdjo]))/g;function serializePositional(e,t){switch(t){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e==="string"){return e}const t=JSON.stringify(e);if(t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)){return e}return t}}}function format(e,...t){if(t.length===0){return e}let r=0;let n=e.replace(o,((e,n,s,i)=>{const o=t[r];const a=serializePositional(o,i);if(!n){r++;return a}return e}));if(r<t.length){n+=` ${t.slice(r).join(" ")}`}n=n.replace(/%{2,2}/g,"%");return n}var a=2;function cleanErrorStack(e){if(!e.stack){return}const t=e.stack.split("\n");t.splice(1,a);e.stack=t.join("\n")}var u=class extends Error{constructor(e,...t){super(e);this.message=e;this.name="Invariant Violation";this.message=format(e,...t);cleanErrorStack(this)}};var invariant=(e,t,...r)=>{if(!e){throw new u(t,...r)}};invariant.as=(e,t,r,...n)=>{if(!t){const t=e.prototype.name!=null;const s=t?new e(format(r,n)):e(format(r,n));throw s}};0&&0},932:function(e){var t=Object.defineProperty;var r=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var s=Object.prototype.hasOwnProperty;var __export=(e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:true})};var __copyProps=(e,i,o,a)=>{if(i&&typeof i==="object"||typeof i==="function"){for(let u of n(i))if(!s.call(e,u)&&u!==o)t(e,u,{get:()=>i[u],enumerable:!(a=r(i,u))||a.enumerable})}return e};var __toCommonJS=e=>__copyProps(t({},"__esModule",{value:true}),e);var i={};__export(i,{Emitter:()=>u,MemoryLeakError:()=>o});e.exports=__toCommonJS(i);var o=class extends Error{constructor(e,t,r){super(`Possible EventEmitter memory leak detected. ${r} ${t.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`);this.emitter=e;this.type=t;this.count=r;this.name="MaxListenersExceededWarning"}};var a=class{static listenerCount(e,t){return e.listenerCount(t)}constructor(){this.events=new Map;this.maxListeners=a.defaultMaxListeners;this.hasWarnedAboutPotentialMemoryLeak=false}_emitInternalEvent(e,t,r){this.emit(e,...[t,r])}_getListeners(e){return this.events.get(e)||[]}_removeListener(e,t){const r=e.indexOf(t);if(r>-1){e.splice(r,1)}return[]}_wrapOnceListener(e,t){const onceListener=(...r)=>{this.removeListener(e,onceListener);t.apply(this,r)};return onceListener}setMaxListeners(e){this.maxListeners=e;return this}getMaxListeners(){return this.maxListeners}eventNames(){return Array.from(this.events.keys())}emit(e,...t){const r=this._getListeners(e);r.forEach((e=>{e.apply(this,t)}));return r.length>0}addListener(e,t){this._emitInternalEvent("newListener",e,t);const r=this._getListeners(e).concat(t);this.events.set(e,r);if(this.maxListeners>0&&this.listenerCount(e)>this.maxListeners&&!this.hasWarnedAboutPotentialMemoryLeak){this.hasWarnedAboutPotentialMemoryLeak=true;const t=new o(this,e,this.listenerCount(e));console.warn(t)}return this}on(e,t){return this.addListener(e,t)}once(e,t){return this.addListener(e,this._wrapOnceListener(e,t))}prependListener(e,t){const r=this._getListeners(e);if(r.length>0){const n=[t].concat(r);this.events.set(e,n)}else{this.events.set(e,r.concat(t))}return this}prependOnceListener(e,t){return this.prependListener(e,this._wrapOnceListener(e,t))}removeListener(e,t){const r=this._getListeners(e);if(r.length>0){this._removeListener(r,t);this.events.set(e,r);this._emitInternalEvent("removeListener",e,t)}return this}off(e,t){return this.removeListener(e,t)}removeAllListeners(e){if(e){this.events.delete(e)}else{this.events.clear()}return this}listeners(e){return Array.from(this._getListeners(e))}listenerCount(e){return this._getListeners(e).length}rawListeners(e){return this.listeners(e)}};var u=a;u.defaultMaxListeners=10;0&&0},611:function(e){"use strict";e.exports=require("http")},692:function(e){"use strict";e.exports=require("https")},203:function(e){"use strict";e.exports=require("stream")}};var t={};function __nccwpck_require__(r){var n=t[r];if(n!==undefined){return n.exports}var s=t[r]={exports:{}};var i=true;try{e[r].call(s.exports,s,s.exports,__nccwpck_require__);i=false}finally{if(i)delete t[r]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r={};!function(){"use strict";var e=r;Object.defineProperty(e,"__esModule",{value:true});var t=__nccwpck_require__(527);__nccwpck_require__(629);__nccwpck_require__(703);e.ClientRequestInterceptor=t.ClientRequestInterceptor}();module.exports=r})(); | ||
| (function(){var e={349:function(e,t,s){if(typeof Promise.withResolvers!=="function"){Promise.withResolvers=function withResolvers(){let e;let t;const s=new Promise(((s,r)=>{e=s;t=r}));return{promise:s,resolve:e,reject:t}}}e.exports=s(1)},1:function(e,t,s){"use strict";s.r(t);s.d(t,{ClientRequestInterceptor:function(){return qe}});var r=class{#e;#t;constructor(){this.#e=[];this.#t=new Map}get[Symbol.iterator](){return this.#e[Symbol.iterator].bind(this.#e)}entries(){return this.#t.entries()}get(e){return this.#t.get(e)||[]}getAll(){return this.#e.map((([,e])=>e))}append(e,t){this.#e.push([e,t]);this.#s(e,(e=>e.push(t)))}prepend(e,t){this.#e.unshift([e,t]);this.#s(e,(e=>e.unshift(t)))}delete(e,t){if(this.size===0)return false;const s=this.#t.get(e);if(!s)return false;const r=s.indexOf(t);if(r===-1)return false;s.splice(r,1);this.#e.splice(this.#e.findIndex((s=>s[0]===e&&s[1]===t)),1);return true}deleteAll(e){if(this.size===0)return;this.#e=this.#e.filter((t=>t[0]!==e));this.#t.delete(e)}get size(){return this.#e.length}clear(){if(this.size===0)return;this.#e.length=0;this.#t.clear()}#s(e,t){t(this.#t.get(e)||this.#t.set(e,[]).get(e))}};const o=Symbol("kDefaultPrevented");const n=Symbol("kPropagationStopped");const i=Symbol("kImmediatePropagationStopped");var a=class extends MessageEvent{#r;[o];[n];[i];constructor(...e){super(e[0],e[1]);this[o]=false}get defaultPrevented(){return this[o]}preventDefault(){super.preventDefault();this[o]=true}stopImmediatePropagation(){super.stopImmediatePropagation();this[i]=true}};var c=class{#o;#n;#i;#a;#c;#l;#u;hooks;constructor(){this.#o=new r;this.#n=new WeakMap;this.#i=new WeakMap;this.#a=new WeakSet;this.#c=new r;this.#l=new WeakMap;this.#u=new WeakMap;this.hooks={on:(e,t,s)=>{if(s?.signal?.aborted)return;if(s?.once){const s=t;const wrapper=(...t)=>{this.#h(e,wrapper);return s(...t)};t=wrapper}this.#c.append(e,t);if(s)this.#l.set(t,s);if(s?.signal){const{signal:r}=s;const onAbort=()=>{this.#h(e,t)};r.addEventListener("abort",onAbort,{once:true});this.#u.set(t,(()=>{r.removeEventListener("abort",onAbort)}))}},removeListener:(e,t)=>{this.#h(e,t)}}}#h(e,t){this.#c.delete(e,t);const s=this.#u.get(t);if(s){s();this.#u.delete(t)}}#d(e,t){const s=this.#o.delete(e,t);const r=this.#i.get(t);if(r){r();this.#i.delete(t)}return s}on(e,t,s){this.#p(e,t,s);return this}once(e,t,s){return this.on(e,t,{...s||{},once:true})}earlyOn(e,t,s){this.#p(e,t,s,"prepend");return this}earlyOnce(e,t,s){return this.earlyOn(e,t,{...s||{},once:true})}emit(e){if(this.#o.size===0)return false;const t=this.listenerCount(e.type)>0;const s=this.#f(e);for(const t of this.#E(e.type)){if(s.event[n]!=null&&s.event[n]!==this){s.revoke();return false}if(s.event[i])break;this.#T(s.event,t)}s.revoke();return t}async emitAsPromise(e){if(this.#o.size===0)return[];const t=[];const s=this.#f(e);for(const r of this.#E(e.type)){if(s.event[n]!=null&&s.event[n]!==this){s.revoke();return[]}if(s.event[i])break;const e=await Promise.resolve(this.#T(s.event,r));if(!this.#R(r))t.push(e)}s.revoke();return Promise.allSettled(t).then((e=>e.map((e=>e.status==="fulfilled"?e.value:e.reason))))}*emitAsGenerator(e){if(this.#o.size===0)return;const t=this.#f(e);for(const s of this.#E(e.type)){if(t.event[n]!=null&&t.event[n]!==this){t.revoke();return}if(t.event[i])break;const e=this.#T(t.event,s);if(!this.#R(s))yield e}t.revoke()}removeListener(e,t){const s=this.#n.get(t);if(!this.#d(e,t))return;for(const r of this.#c.get("removeListener").slice())r(e,t,s)}removeAllListeners(e){if(e==null){for(const[e,t]of this.#o.entries())while(t.length>0)this.removeListener(e,t[0]);for(const[e,t]of[...this.#c])if(!this.#l.get(t)?.persist)this.#h(e,t);return}const t=this.listeners(e);while(t.length>0)this.removeListener(e,t[0])}listeners(e){if(e==null)return this.#o.getAll();return this.#o.get(e)}listenerCount(e){if(e==null)return this.#o.size;return this.listeners(e).length}#p(e,t,s,r="append"){if(s?.signal?.aborted)return;for(const r of this.#c.get("newListener").slice())r(e,t,s);if(e==="*")this.#a.add(t);if(r==="prepend")this.#o.prepend(e,t);else this.#o.append(e,t);if(s){this.#n.set(t,s);if(s.signal){const{signal:r}=s;const onAbort=()=>{this.removeListener(e,t)};r.addEventListener("abort",onAbort,{once:true});this.#i.set(t,(()=>{r.removeEventListener("abort",onAbort)}))}}}#f(e){const{stopPropagation:t}=e;e.stopPropagation=()=>{e[n]=this;t.call(e)};return{event:e,revoke(){e.stopPropagation=t}}}#T(e,t){for(const t of this.#c.get("beforeEmit").slice())if(t(e)===false)return;const s=t.call(this,e);const r=this.#n.get(t);if(r?.once){const s=this.#R(t)?"*":e.type;if(this.#d(s,t))for(const e of this.#c.get("removeListener").slice())e(s,t,r)}return s}*#E(e){const t=[];for(const[s,r]of this.#o)if(s==="*"||s===e)t.push(r);yield*t}#R(e){return this.#a.has(e)}};var l=require("next/dist/compiled/debug");var u=class{constructor(){this.subscriptions=[]}dispose(){let e;while(e=this.subscriptions.pop())e()}};const h=/\d{2}:\d{2}:\d{2}\.\d{3}/;function normalizeNamespace(e){return e.split(":").map((e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"").toLowerCase())).filter(Boolean).join(":")}function getTimestamp(){return(new Date).toISOString().slice(11,23)}async function readBody(e){if(e.body==null)return null;try{return await e.clone().text()}catch{return null}}function formatHeaders(e){return Array.from(e.entries()).map((([e,t])=>`${e}: ${t}`))}async function formatHttpMessage(e,t){const s=[e,...formatHeaders(t.headers)];const r=await readBody(t);s.push("",r??"");return s.join("\n")}async function formatRequest(e){return formatHttpMessage(`${e.method} ${e.url}`,e)}async function formatResponse(e){const t=e.statusText?` ${e.statusText}`:"";return formatHttpMessage(`HTTP ${e.status}${t}`,e)}function formatLogArguments(e){const t=e[0];if(typeof t==="string"){const s=t.replace(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /,"");const r=s.match(h);if(!r||r.index===void 0){e[0]=s;return}const o=s.slice(0,r.index).trim();const n=s.slice(r.index+r[0].length).trimStart();e[0]=`${r[0]} ${o} ${n}`}}function useConciseTimestamp(e){e.log=(...e)=>{formatLogArguments(e);l.log(...e)}}function isVerboseLoggingEnabled(){if(typeof process!=="undefined"&&process.env.DEBUG_LEVEL==="verbose")return true;if(typeof document==="undefined")return false;try{return globalThis.localStorage?.getItem("debugLevel")==="verbose"}catch{return false}}function createLogger(e){const t=l(`interceptors:${normalizeNamespace(e)}`);Reflect.set(t,"useColors",true);useConciseTimestamp(t);return{info(e,...s){t(`${getTimestamp()} ${e}`,...s)},verbose(e,...s){if(!isVerboseLoggingEnabled())return;t(`${getTimestamp()} ${e}`,...s)},isEnabled(e){return t.enabled&&(e==="default"||isVerboseLoggingEnabled())}}}const d=globalThis.__MSW_INTERCEPTORS_REGISTRY??=new Map;var p=class extends u{#S;static singleton(e){const t=e.symbol;const s=d.get(t);if(s instanceof e)return s;const r=new e;d.set(t,r);return r}constructor(){super();this.on=(e,t,s)=>this.emitter.on(e,t,s);this.once=(e,t,s)=>this.emitter.once(e,t,s);this.listeners=e=>this.emitter.listeners(e);this.listenerCount=e=>this.emitter.listenerCount(e);this.removeListener=(e,t)=>this.emitter.removeListener(e,t);this.removeAllListeners=e=>{this.logger.info("removeAllListeners %o",{eventType:e??"*"});return this.emitter.removeAllListeners(e)};this.#S=new Set;this.readyState="INACTIVE";this.emitter=new c;this.logger=createLogger(this.#_())}apply(e=this){if(this.#S.has(e))return;if(this.readyState!=="ACTIVE"&&!this.predicate())return;this.#S.add(e);if(this.readyState==="ACTIVE")return;try{this.setup();this.readyState="ACTIVE";this.logger.info("apply")}catch(t){this.dispose(e);throw t}}dispose(e=this){if(!this.#S.delete(e))return;if(this.#S.size>0)return;super.dispose();this.emitter.removeAllListeners();this.readyState="DISPOSED";this.logger.info("disable")}#_(){const e=this.constructor.symbol?.description;if(e)return e.replace(/-interceptor$/,"");return this.constructor.name.replace(/Interceptor$/,"")}};const f=new TextEncoder;function encodeBuffer(e){return f.encode(e)}function decodeBuffer(e,t){return new TextDecoder(t).decode(e)}function toBuffer(e,t){if(Buffer.isBuffer(e))return e;if(e instanceof Uint8Array)return Buffer.from(e.buffer);return Buffer.from(e,t)}var E=/(%?)(%([sdijo]))/g;function serializePositional(e,t){switch(t){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e==="string"){return e}const t=JSON.stringify(e);if(t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)){return e}return t}}}function format(e,...t){if(t.length===0){return e}let s=0;let r=e.replace(E,((e,r,o,n)=>{const i=t[s];const a=serializePositional(i,n);if(!r){s++;return a}return e}));if(s<t.length){r+=` ${t.slice(s).join(" ")}`}r=r.replace(/%{2,2}/g,"%");return r}var T=2;function cleanErrorStack(e){if(!e.stack){return}const t=e.stack.split("\n");t.splice(1,T);e.stack=t.join("\n")}var R=class extends Error{constructor(e,...t){super(e);this.message=e;this.name="Invariant Violation";this.message=format(e,...t);cleanErrorStack(this)}};var invariant=(e,t,...s)=>{if(!e){throw new R(t,...s)}};invariant.as=(e,t,s,...r)=>{if(!t){const t=r.length===0?s:format(s,...r);let o;try{o=Reflect.construct(e,[t])}catch(s){o=e(t)}throw o}};var S=class InterceptorError extends Error{constructor(e){super(e);this.name="InterceptorError";Object.setPrototypeOf(this,InterceptorError.prototype)}};var _=class RequestController{static{this.PENDING=0}static{this.PASSTHROUGH=1}static{this.RESPONSE=2}static{this.ERROR=3}#A;constructor(e,t,s){this.request=e;this.source=t;this.options=s;this.readyState=RequestController.PENDING;this.#A=Promise.withResolvers();this.handled=this.#A.promise}async passthrough(){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to passthrough the "%s %s" request: the request has already been handled',this.request.method,this.request.url);this.readyState=RequestController.PASSTHROUGH;if(this.options)this.options.logger.info("[%s] passthrough",this.options.requestId);await this.source.passthrough();this.#A.resolve()}respondWith(e){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)',this.request.method,this.request.url,e.status,e.statusText||"OK",this.readyState);this.readyState=RequestController.RESPONSE;if(this.options?.logger.isEnabled("default")){const{logger:t,requestId:s}=this.options;formatResponse(e).then((e=>{t.info("[%s] mocked %s",s,e)}))}this.#A.resolve();this.source.respondWith(e)}errorWith(e){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)',this.request.method,this.request.url,e?.toString(),this.readyState);this.readyState=RequestController.ERROR;if(this.options)this.options.logger.info("[%s] error %o",this.options.requestId,e);this.source.errorWith(e);this.#A.resolve()}};function createRequestId(){return Math.random().toString(16).slice(2)}const A=Symbol("kRawHeaders");const g=Symbol("kRestorePatches");function recordRawHeader(e,t,s){ensureRawHeadersSymbol(e,[]);const r=Reflect.get(e,A);if(s==="set"){for(let e=r.length-1;e>=0;e--)if(r[e][0].toLowerCase()===t[0].toLowerCase())r.splice(e,1)}r.push(t)}function ensureRawHeadersSymbol(e,t){if(Reflect.has(e,A))return;defineRawHeadersSymbol(e,t)}function defineRawHeadersSymbol(e,t){Object.defineProperty(e,A,{value:t,enumerable:false,configurable:true})}function recordRawFetchHeaders(){if(Reflect.get(Headers,g))return Reflect.get(Headers,g);const{Headers:e,Request:t,Response:s}=globalThis;const{set:r,append:o,delete:n}=Headers.prototype;Object.defineProperty(Headers,g,{value:()=>{Headers.prototype.set=r;Headers.prototype.append=o;Headers.prototype.delete=n;globalThis.Headers=e;globalThis.Request=t;globalThis.Response=s;Object.setPrototypeOf(m,t);Object.setPrototypeOf(m.prototype,t.prototype);Object.setPrototypeOf(N,s);Object.setPrototypeOf(N.prototype,s.prototype);Reflect.deleteProperty(Headers,g)},enumerable:false,configurable:true});Object.defineProperty(globalThis,"Headers",{enumerable:true,writable:true,value:new Proxy(Headers,{construct(e,t,s){const r=t[0]||[];if(r instanceof Headers&&Reflect.has(r,A)){const t=Reflect.get(r,A).map((e=>[e[0],e[1]]));const o=Reflect.construct(e,[t],s);ensureRawHeadersSymbol(o,[...t]);return o}const o=Reflect.construct(e,t,s);if(!Reflect.has(o,A))ensureRawHeadersSymbol(o,Array.isArray(r)?r:Object.entries(r));return o}})});Headers.prototype.set=new Proxy(Headers.prototype.set,{apply(e,t,s){recordRawHeader(t,[s[0],s[1]],"set");return Reflect.apply(e,t,s)}});Headers.prototype.append=new Proxy(Headers.prototype.append,{apply(e,t,s){recordRawHeader(t,[s[0],s[1]],"append");return Reflect.apply(e,t,s)}});Headers.prototype.delete=new Proxy(Headers.prototype.delete,{apply(e,t,s){const r=Reflect.get(t,A);if(r){for(let e=r.length-1;e>=0;e--)if(r[e][0].toLowerCase()===s[0].toLowerCase())r.splice(e,1)}return Reflect.apply(e,t,s)}});Object.defineProperty(globalThis,"Request",{enumerable:true,writable:true,value:new Proxy(Request,{construct(e,t,s){const r=Reflect.construct(e,t,s);const o=[];if(typeof t[0]==="object"&&t[0].headers!=null)o.push(...inferRawHeaders(t[0].headers));if(typeof t[1]==="object"&&t[1].headers!=null)o.push(...inferRawHeaders(t[1].headers));if(o.length>0)ensureRawHeadersSymbol(r.headers,o);return r}})});Object.defineProperty(globalThis,"Response",{enumerable:true,writable:true,value:new Proxy(Response,{construct(e,t,s){const r=Reflect.construct(e,t,s);if(typeof t[1]==="object"&&t[1].headers!=null)ensureRawHeadersSymbol(r.headers,inferRawHeaders(t[1].headers));return r}})});Object.setPrototypeOf(m,globalThis.Request);Object.setPrototypeOf(m.prototype,globalThis.Request.prototype);Object.setPrototypeOf(N,globalThis.Response);Object.setPrototypeOf(N.prototype,globalThis.Response.prototype);return restoreHeadersPrototype}function restoreHeadersPrototype(){if(!Reflect.get(Headers,g))return;Reflect.get(Headers,g)()}function getRawFetchHeaders(e){if(!Reflect.has(e,A))return Array.from(e.entries());const t=Reflect.get(e,A);return t.length>0?t:Array.from(e.entries())}function inferRawHeaders(e){if(e instanceof Headers)return Reflect.get(e,A)||[];return Reflect.get(new Headers(e),A)}function copyRawHeaders(e,t){const s=[...getRawFetchHeaders(e)];if(s.length===0)return;for(const[e,r]of t)if(s.every((t=>t[0].toLowerCase()!==e.toLowerCase())))s.push([e,r]);defineRawHeadersSymbol(t,s)}function getValueBySymbol(e,t){const s=Object.getOwnPropertySymbols(t).find((t=>t.description===e));if(s)return Reflect.get(t,s)}function isObject(e,t=false){return t?Object.prototype.toString.call(e).startsWith("[object "):Object.prototype.toString.call(e)==="[object Object]"}function isPropertyAccessible(e,t){try{e[t];return true}catch{return false}}function createServerErrorResponse(e){return new Response(JSON.stringify(e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e),{status:500,statusText:"Unhandled Exception",headers:{"Content-Type":"application/json"}})}const O=Symbol("kErrorResponse");function getErrorResponse(e){if(e instanceof Error&&O in e&&isResponseError(e[O]))return e[O]}function isResponseError(e){return e!=null&&e instanceof Response&&isPropertyAccessible(e,"type")&&e.type==="error"}function isResponseLike(e){return isObject(e,true)&&isPropertyAccessible(e,"status")&&isPropertyAccessible(e,"statusText")&&isPropertyAccessible(e,"bodyUsed")}var m=class FetchRequest extends Request{static#g(e,t={},s){return t[s]??(e instanceof Request?e[s]:void 0)}static isConfigurableMethod(e){return e!=="CONNECT"&&e!=="TRACE"&&e!=="TRACK"}static isMethodWithBody(e){return e!=="HEAD"&&e!=="GET"&&FetchRequest.isConfigurableMethod(e)}static isConfigurableMode(e){return e!=="navigate"&&e!=="websocket"&&e!=="webtransport"}constructor(e,t){const s=FetchRequest.#g(e,t,"method")||"GET";const r=FetchRequest.isConfigurableMethod(s)?s:"GET";const o=t!=null&&"body"in t;const n=!FetchRequest.isMethodWithBody(s)?{body:void 0}:o?{body:t.body}:{};const i=FetchRequest.#g(e,t,"mode")??void 0;const a=FetchRequest.isConfigurableMode(i)?i:void 0;super(e,{...t||{},method:r,mode:a,duplex:t?.duplex??(FetchRequest.isMethodWithBody(s)?"half":void 0),...n});if(s!==r)this.#O("method",s);if(s==="CONNECT"){const t=new URL(e instanceof Request?e.url:e);let s;if(t.protocol==="localhost:")s=t.href;else s=t.pathname.replace(/^\/+/,"");Object.defineProperty(this,"url",{get:()=>s,enumerable:true,configurable:true})}if(i!=null&&i!==a)this.#O("mode",i)}#O(e,t){const s=getValueBySymbol("state",this);if(s)Reflect.set(s,e,t);else Object.defineProperty(this,e,{value:t,enumerable:true,configurable:true,writable:false})}};const y=Symbol("kStatus");const C=Symbol("kUrl");var N=class FetchResponse extends Response{static from(e,t){if(e instanceof FetchResponse)return e;if(isResponseError(e))return e;const s=new FetchResponse(e.body,{url:t?.url??e.url,status:t?.status||e.status,statusText:t?.statusText??e.statusText,headers:t?.headers??e.headers});copyRawHeaders(e.headers,s.headers);return s}static{this.STATUS_CODES_WITHOUT_BODY=[101,103,204,205,304]}static{this.STATUS_CODES_WITH_REDIRECT=[301,302,303,307,308]}static isConfigurableStatusCode(e){return e>=200&&e<=599}static isRedirectResponse(e){return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(e)}static isResponseWithBody(e){return!FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(e)}static setStatus(e,t){const s=getValueBySymbol("state",t);if(s)s.status=e;else Object.defineProperty(t,"status",{value:e,enumerable:true,configurable:true,writable:false});Object.defineProperty(t,y,{value:e,enumerable:false})}static setUrl(e,t){if(!e||e==="about:"||!URL.canParse(e))return;const s=getValueBySymbol("state",t);if(s)s.urlList.push(new URL(e));else Object.defineProperty(t,"url",{value:e,enumerable:true,configurable:true,writable:false});Object.defineProperty(t,C,{value:e,enumerable:false})}static parseRawHeaders(e){const t=new Headers;for(let s=0;s<e.length;s+=2)t.append(e[s],e[s+1]);return t}static clone(e){try{return e.clone()}catch(e){return Response.json(e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{},{status:500,statusText:"Unclonable Response"})}}#m;#y;constructor(e,t={}){const s=t.status??200;const r=FetchResponse.isConfigurableStatusCode(s)?s:200;const o=FetchResponse.isResponseWithBody(s)?e:null;super(o,{status:r,statusText:t.statusText,headers:t.headers});if(s!==r)FetchResponse.setStatus(s,this);FetchResponse.setUrl(t.url,this)}clone(){const e=super.clone();const t=Reflect.get(this,y);if(t)FetchResponse.setStatus(t,e);const s=Reflect.get(this,C);if(s)FetchResponse.setUrl(s,e);return e}};var b=require("node:http");var k=require("node:net");var P=require("node:tls");var I=class{#C=new Map;applyPatch(e,t,s){const r=this.#C.get(e);invariant(!r?.has(t),`Failed to replace a global value at "${String(t)}": already replaced.`);const o=getDeepPropertyDescriptor(e,t);if(typeof o==="undefined"){console.warn(`Failed to replace a global value at "${String(t)}": not a global value.`);return()=>{}}if(o.descriptor.configurable)Object.defineProperty(e,t,{value:s(e[t]),enumerable:true,configurable:true});else if(o.descriptor.writable)e[t]=s(e[t]);else throw new Error(`Failed to patch a non-configurable non-writable property "${t.toString()}"`);const restorePatch=()=>{const s=this.#C.get(e);if(!s?.has(t))return;if(o.owner===e)Object.defineProperty(o.owner,t,o.descriptor);else Reflect.deleteProperty(e,t);s.delete(t);if(s.size===0)this.#C.delete(e)};if(r)r.set(t,restorePatch);else this.#C.set(e,new Map([[t,restorePatch]]));return restorePatch}restoreAllPatches(){const e=[];for(const[,t]of this.#C)for(const[,s]of t)try{s()}catch(t){if(t instanceof Error)e.push(t);else throw t}if(e.length>0)throw new AggregateError(e,"FOO!")}};const H=new I;function getDeepPropertyDescriptor(e,t){let s=e;let r;while(s){r=Object.getOwnPropertyDescriptor(s,t);if(r)return{owner:s,descriptor:r};s=Object.getPrototypeOf(s)}}function normalizeNetConnectArgs(e){if(e.length===0)return[{path:""},null];const t=typeof e[1]==="function"?e[1]:e[2]||null;if(typeof e[0]==="string")return[{path:e[0]},t];if(typeof e[0]==="number")return[{port:e[0],path:"",host:typeof e[1]==="string"?e[1]:void 0},t];if(typeof e[0]==="object"){if("port"in e[0])return[{path:"",port:Reflect.get(e[0],"port"),host:Reflect.get(e[0],"host"),auth:Reflect.get(e[0],"auth"),family:Reflect.get(e[0],"family"),hints:Reflect.get(e[0],"hints"),session:Reflect.get(e[0],"session"),localAddress:Reflect.get(e[0],"localAddress"),localPort:Reflect.get(e[0],"localPort"),timeout:Reflect.get(e[0],"timeout"),lookup:Reflect.get(e[0],"lookup"),allowHalfOpen:Reflect.get(e[0],"allowHalfOpen"),noDelay:Reflect.get(e[0],"noDelay"),keepAlive:Reflect.get(e[0],"keepAlive"),keepAliveInitialDelay:Reflect.get(e[0],"keepAliveInitialDelay"),autoSelectFamily:Reflect.get(e[0],"autoSelectFamily"),autoSelectFamilyAttemptTimeout:Reflect.get(e[0],"autoSelectFamilyAttemptTimeout")},t];return[{path:e[0].path||"",family:Reflect.get(e[0],"family"),session:Reflect.get(e[0],"session"),auth:Reflect.get(e[0],"auth"),timeout:Reflect.get(e[0],"timeout"),allowHalfOpen:Reflect.get(e[0],"allowHalfOpen")},t]}throw new Error(`Invalid arguments passed to net.connect: ${e}`)}function writePendingData(e,t,s,r){if(Array.isArray(t)){for(let s=0;s<t.length;s++){const o=t[s];if(s===t.length-1)e.write(o.chunk,o.encoding,r);else e.write(o.chunk,o.encoding)}return}e.write(t,s,r)}function unwrapPendingData(e,t){if(Array.isArray(e))for(const s of e)t(s.chunk,s.encoding,s.callback);else t(e)}function getTlsConnectOptions(e){const t=Object.getOwnPropertySymbols(e).find((e=>e.description==="connect-options"));if(t==null)return;return Reflect.get(e,t)}function getAddressInfoByConnectionOptions(e){if(e==null)return{};const t=e.family===6||k.isIPv6(e.host||"");return{address:t?"::1":"127.0.0.1",port:Number(e.port)||(e.protocol==="https:"?443:80),family:t?"IPv6":"IPv4"}}function getLocalAddressInfoByConnectionOptions(e){if(e==null)return{};const t=e.family===6||k.isIPv6(e.host||"");return{address:e.localAddress||(t?"::1":"127.0.0.1"),port:e.localPort||getEphemeralPort(),family:t?"IPv6":"IPv4"}}function getEphemeralPort(){return 49152+Math.floor(Math.random()*16384)}const D=Symbol("kListenerWrap");const L=Symbol("kRawSocket");const w=Symbol("kPatched");const v=createLogger("socket");function toServerSocket(e){const t=[];let s;let r=false;let o=false;const flushPendingWrites=()=>{if(e.connecting){r=true;if(!o){o=true;e.once("ready",(()=>{o=false;flushPendingWrites()}))}return false}while(t.length>0){const s=t.shift();e._unrefTimer();const o=e.push(toBuffer(s.chunk,s.encoding),s.encoding);s.callback?.();if(!o){r=true;return false}}const n=r;r=false;if(s){const t=s;s=void 0;if(t.chunk!=null)e.push(toBuffer(t.chunk,t.encoding),t.encoding);e.push(null);t.callback?.()}if(n)e.emit("internal:drain");return true};const n=e._read.bind(e);e._read=e=>{n(e);if(t.length>0||s!=null||r)flushPendingWrites()};return new Proxy(e,{get:(e,o,n)=>{const getRealValue=()=>Reflect.get(e,o,n);if(o==="on"||o==="addListener"||o==="once"||o==="prependListener"||o==="prependOnceListener"){const t=getRealValue();return(s,r)=>{if(s==="data"){const listenerWrap=(e,t)=>{r(toBuffer(e,t))};Object.defineProperty(r,D,{enumerable:false,writable:false,value:listenerWrap});Reflect.apply(t,e,["internal:write",listenerWrap]);return e}if(s==="drain"){Reflect.apply(t,e,["internal:drain",r]);return e}return t.call(e,s,r)}}if(o==="off"||o==="removeListener"){const t=getRealValue();return(s,r)=>{if(s==="data"){const s=r[D];if(s)return t.call(e,"internal:write",s)}if(s==="drain")return t.call(e,"internal:drain",r);return t.call(e,s,r)}}if(o==="write")return(e,s,o)=>{if(typeof s==="function"){o=s;s=void 0}t.push({chunk:e,encoding:s,callback:o});if(r)return false;return flushPendingWrites()};if(o==="end")return(...t)=>{const r=t[t.length-1];s={chunk:typeof t[0]==="function"?void 0:t[0],encoding:typeof t[1]==="string"?t[1]:void 0,callback:typeof r==="function"?r:void 0};flushPendingWrites();return e};return getRealValue()}})}var M=class SocketController{static{this.PENDING=0}static{this.CLAIMED=1}static{this.PASSTHROUGH=2}constructor(e){this[L]=e;e[w]=true;this.readyState=SocketController.PENDING}claim(){invariant(this.readyState===SocketController.PENDING,"Failed to claim a socket connection: already handled (%s)",this.readyState);this.readyState=SocketController.CLAIMED}passthrough(){invariant(this.readyState===SocketController.PENDING,"Failed to passthrough a socket connection: already handled (%s)",this.readyState);this.readyState=SocketController.PASSTHROUGH}};var U=class extends M{#N;#b;#k=null;#P=[];#I=false;#H=[];#D=false;#L=false;#w=false;#v=false;constructor(e,t,s){super(e);this.socket=e;this.createConnection=t;this.#N=s;this.socket._read=()=>{this.#k?.resume()};this.#b=this.socket._writeGeneric;this.#P=[];this.socket._writeGeneric=(...e)=>{this.#M(e)};this.socket.connect=new Proxy(this.socket.connect,{apply:(e,t,s)=>{v.verbose("socket.connect() %o",s);this.#N=s[0];if(s[0]!=null&&typeof s[0]==="object"&&(s[0].localAddress!=null||s[0].localPort!=null))s[0]={...s[0],localAddress:void 0,localPort:void 0};return Reflect.apply(e,t,s)}});e.on("free",(()=>{v.verbose("client socket freed!");this.reset()})).on("close",(()=>{v.verbose("client socket closed!");this.#L=true;this.#k?.destroy();this.#k=null;this.#P=[];this.#I=false;this.#H=[]}));this.serverSocket=toServerSocket(this.socket);this.pendingConnection=Promise.withResolvers();this.#U()}reset(){if(this.readyState===M.PENDING)return;this.#U()}#U(){v.verbose("resetting the socket...");this.readyState=M.PENDING;this.pendingConnection=Promise.withResolvers();this.#P=[];this.#v=false;this.socket._pendingData=null;this.socket._pendingEncoding="";const wrapHandle=e=>{this.pendingConnection.promise.then((()=>{v.verbose("connection request resolved!",this.readyState);process.nextTick((()=>{if(this.readyState===M.PENDING&&this.socket.connecting&&this.#P.length===0&&this.socket.listenerCount("connect")>0){v.verbose('assume connect->write socket, calling "connect" listeners...');this.emulateConnect()}}))}));if(e.setTypeOfService)e.setTypeOfService=void 0;e.connect=e.connect6=t=>{v.verbose("handle.connect()");this.pendingConnection.resolve([t,e])};v.verbose("socket handle wrapped! waiting for connection request...")};if(this.socket._handle)wrapHandle(this.socket._handle);else this.socket.prependOnceListener("connectionAttempt",(()=>{wrapHandle(this.socket._handle)}))}#M(e){const t=e[1];v.verbose("socket write (state: %d) %o",this.readyState,e);this.#P.push(e);if(this.readyState===M.PENDING){const e=Array.isArray(this.socket._pendingData)?this.socket._pendingData:[];unwrapPendingData(t,((t,s)=>{e.push({chunk:t,encoding:s})}));this.socket._pendingData=e;if(this.socket.listenerCount("internal:write")===0){v.verbose("no server data listeners, scheduling to the next tick...");process.nextTick((()=>{this.#q(t)}))}else this.#q(t)}else this.#q(t);switch(this.readyState){case M.PENDING:if(!this.#P.includes(e))this.#P.push(e);this.#B(e);return;case M.CLAIMED:this.#F(e);this.#B(e);return;case M.PASSTHROUGH:if(!this.#F(e))return;if(!this.#D&&this.#k){writePendingData(this.#k,t,e[2],e[3]);return}this.#b.apply(this.socket,e)}}#B(e){const t=e[3];if(typeof t==="function"){t();e[3]=void 0}}#F(e){const t=this.#P.indexOf(e);if(t===-1)return false;this.#P.splice(t,1);return true}emulateConnect(){this.#v=true;Reflect.set(this.socket,"connecting",false);for(const e of this.socket.rawListeners("connect"))e.apply(this.socket)}#q=e=>{if(e==null)return;v.verbose("server push %o",e);unwrapPendingData(e,((e,t)=>{v.verbose('server emitting "data" %o',{chunk:e,encoding:t});this.socket.emit("internal:write",e,t)}))};#x=()=>{if(!this.#k)return;if(this.socket.destroyed){this.#k.destroy();return}const e=this.socket._handle;const t=e!=null&&typeof e.hasRef==="function"&&!e.hasRef();this.socket._handle=this.#k._handle;this.#D=true;if(t)this.socket._handle.unref?.();if(e!=null){e.close();e._parent?.close()}Reflect.set(this.socket,"connecting",false);this.socket.remoteAddress;this.socket.emit("connect");this.socket.emit("ready")};#G=(e,t,s,r)=>{this.socket.emit("connectionAttemptFailed",e,t,s,r)};#W=(e,t,s)=>{this.socket.emit("connectionAttemptTimeout",e,t,s)};#j=e=>{v.verbose('real socket "data" event %o',e);this.socket._unrefTimer();if(this.#I){v.verbose("reads are corked, buffering the data...");this.#H.push({type:"data",chunk:e});return}if(!this.socket.push(e)){v.verbose("client socket forbade more pushes, pausing the passthrough socket...");this.#k?.pause()}};#V=e=>{v.verbose('real socket "error" event %o',e);if(this.socket.destroyed){v.verbose("real socket errored but client socket already destroyed, skipping...");return}v.verbose("real socket errored, forwarding %o",e);this.socket.destroy(e);if(this.#D)process.nextTick((()=>this.socket.emit("close",true)))};#K=()=>{this.socket._unrefTimer();if(this.#I){this.#H.push({type:"end"});return}this.#w=true;this.socket.push(null)};#$=e=>{if(this.#D&&this.socket._handle)this.socket._handle.shutdown=()=>1;if(this.#I){this.#H.push({type:"close",hadError:e});return}if(this.#L)return;if(this.socket.destroyed&&!this.#D)return;this.#X(e)};#X(e){if(this.#w&&!this.socket.readableEnded&&!this.socket.destroyed){let t=false;const deliverClose=s=>{if(t)return;t=true;process.nextTick((()=>{if(!this.#L)this.socket.emit("close",s??e)}))};this.socket.once("end",(()=>{deliverClose()}));const s=this.socket._destroy;this.socket._destroy=(e,t)=>{deliverClose(e!=null);return s.call(this.socket,e,t)};return}this.socket.emit("close",e)}#Y=()=>{v.verbose("client socket drained!");this.#k?.resume()};corkReads(){this.#I=true}uncorkReads(){if(!this.#I)return;this.#I=false;for(const e of this.#H.splice(0))switch(e.type){case"data":if(!this.socket.push(e.chunk)){v.verbose("client socket forbade more pushes, pausing the passthrough socket...");this.#k?.pause()}break;case"end":this.#w=true;this.socket.push(null);break;case"close":this.#X(e.hadError);break}}claim(){super.claim();if(this.socket.destroyed){v.verbose("socket already destroyed, skipping claim...");return}if(!this.socket.connecting&&!this.#v){v.verbose("socket already connected, skipping claim...");return}v.verbose("-> claim!");this.socket._handle.getsockname=e=>{Object.assign(e,getLocalAddressInfoByConnectionOptions(this.#N));return 0};this.socket._handle.getpeername=e=>{Object.assign(e,getAddressInfoByConnectionOptions(this.#N));return 0};this.#P=[];this.socket._pendingData=null;this.socket._pendingEncoding="";this.pendingConnection.promise.then((([e,t])=>{v.verbose("connection request resolved, mocking the connection...");if(this.#v)Reflect.set(this.socket,"connecting",true);e.oncomplete(0,t,e,true,true)}))}passthrough(e){super.passthrough();v.verbose("-> passthrough!");const createRealSocket=()=>{const e=this.createConnection();e[w]=true;if(this.socket.timeout!=null)e.setTimeout(this.socket.timeout);return e};const t=this.#k&&!this.#k.destroyed?this.#k:createRealSocket();if(t!==this.#k)this.#k=t;if(this.#P.length===0)v.verbose("passthrough with empty writes buffer (state: %d)",this.readyState);for(let s=0;s<this.#P.length;s++){const r=this.#P[s];if(s===0&&typeof e==="function"){const t=r[1];const s=r[2];e(t,s,(e=>{r[1]=e}))}const[,o,n,i]=r;writePendingData(t,o,n,i)}this.#P=[];this.socket._pendingData=null;this.socket._pendingEncoding="";this.socket.address=t.address.bind(t);this.socket.removeListener("drain",this.#Y);this.socket.on("drain",this.#Y);t.removeListener("connect",this.#x).removeListener("connectionAttemptFailed",this.#G).removeListener("connectionAttemptTimeout",this.#W).removeListener("data",this.#j).removeListener("error",this.#V).removeListener("end",this.#K).removeListener("close",this.#$);t.once("connect",this.#x).on("connectionAttemptFailed",this.#G).on("connectionAttemptTimeout",this.#W).on("data",this.#j).on("error",this.#V).on("end",this.#K).on("close",this.#$);return t}};var q=class extends U{#z;constructor(e,t,s){super(e,t,s);this.socket=e;this.createConnection=t;this.#z=s;e.prependListener("secureConnect",(()=>{e.alpnProtocol=e._handle.getALPNNegotiatedProtocol()}))}emulateConnect(){super.emulateConnect();for(const e of this.socket.rawListeners("secureConnect"))e.apply(this.socket)}claim(){if(this.socket.destroyed){super.claim();return}this.socket.prependOnceListener("secureConnect",(()=>{Reflect.set(this.socket,"authorized",false);Reflect.set(this.socket,"authorizationError","MOCKED_CONNECTION_NOT_VERIFIED")}));const e=this.socket._handle;e.start=()=>void 0;e.verifyError=()=>void 0;e.getSession=()=>Buffer.from("mocked session");const t=getTlsConnectOptions(this.socket);if(t)t.checkServerIdentity=()=>{};e.getCipher=()=>({name:"TLS_AES_256_GCM_SHA384",standardName:"TLS_AES_256_GCM_SHA384",version:"TLSv1.3"});e.getEphemeralKeyInfo=()=>({type:"ECDH",name:"X25519",size:253});const s=this.#z?.ALPNProtocols;if(Array.isArray(s)&&s.length>0){const[t]=s;e.getALPNNegotiatedProtocol=()=>typeof t==="string"?t:false}this.socket.once("connect",(()=>{const t="0".repeat(64);const s="0".repeat(96);for(const e of["SERVER_HANDSHAKE_TRAFFIC_SECRET","EXPORTER_SECRET","SERVER_TRAFFIC_SECRET_0","CLIENT_HANDSHAKE_TRAFFIC_SECRET","CLIENT_TRAFFIC_SECRET_0"])this.socket.emit("keylog",Buffer.from(`${e} ${t} ${s}\n`));e.onhandshakedone();e.onnewsession(1,Buffer.from("mocked session"));e.onnewsession(2,Buffer.from("mocked session"))}));super.claim()}passthrough(e){const t=super.passthrough(e);for(const e of this.socket.listeners("connect"))if(e===this.socket._start||"listener"in e&&e.listener===this.socket._start)this.socket.removeListener("connect",e);t.on("secure",(()=>{this.socket.emit("secure")})).on("session",((...e)=>{this.socket.emit("session",...e)})).on("keylog",((...e)=>{this.socket.emit("keylog",...e)})).on("OCSPResponse",((...e)=>{this.socket.emit("OCSPResponse",...e)}));return t}};function normalizeTlsConnectArgs(e){const t=normalizeNetConnectArgs(e);const s=t[0];const r=t[1];if(e[0]!==null&&typeof e[0]==="object")Object.assign(s,e[0]);else if(e[1]!==null&&typeof e[1]==="object")Object.assign(s,e[1]);else if(e[2]!==null&&typeof e[2]==="object")Object.assign(s,e[2]);return r?[s,r]:[s]}var B=class extends a{constructor(e){super(...["connection",{}]);this.socket=e.socket;this.connectionOptions=e.connectionOptions;this.controller=e.controller}};const F=createLogger("socket");const mockLookup=(e,t,s)=>{const r=t.family===6?6:4;const o=r===6?"::1":"127.0.0.1";process.nextTick((()=>{if(t.all){s(null,[{address:o,family:r}]);return}s(null,o,r)}))};var x=class extends p{static{this.symbol=Symbol.for("socket-interceptor")}predicate(){return true}setup(){const e=this;let t=false;this.subscriptions.push(H.applyPatch(k.Socket.prototype,"connect",(s=>function connect(...r){const o=this;if(o[w]||t)return s.apply(o,r);F.verbose("socket.connect() %o",r);const n=Array.isArray(r[0])?r[0]:r;const[i,a]=normalizeNetConnectArgs(n);F.verbose("connection options %o",{transportConnectionOptions:i,connectionCallback:a});let c;let l;if(o instanceof P.TLSSocket){const e=getTlsConnectOptions(o);const[s]=normalizeTlsConnectArgs([{...i,...e}]);l=s;c=new q(o,(()=>{t=true;try{return P.connect(e??s)}finally{t=false}}),s)}else{const e=n.filter((e=>typeof e!=="function"));const t=n[0]!==null&&typeof n[0]==="object"&&!("href"in n[0])?n[0]:{};l=i;c=new U(o,(()=>{const r=new k.Socket(t);Reflect.apply(s,r,e);return r}))}process.nextTick((()=>{if(o.destroyed)return;if(!e.emitter.emit(new B({socket:c.serverSocket,controller:c,connectionOptions:l}))){F.verbose('no "connection" listeners found on the interceptor, passthrough...');c.passthrough();return}F.verbose('emitted "connection" event!')}));F.verbose("connecting the socket...");const u={...i};u.lookup=mockLookup;try{return o.connect(u,a??void 0)}catch(e){o.destroy();throw e}})),this.#Q())}#Q(){if(typeof b.Agent.prototype.addRequest!=="function")return()=>{};return H.applyPatch(b.Agent.prototype,"addRequest",(e=>function(...t){for(const e of Object.values(this.freeSockets)){if(e==null)continue;for(const t of e)if(!t[w])t.destroy()}return e?.apply(this,t)}))}};var G=require("node:async_hooks");var W=require("node:stream");var j=require("node:fs");async function until(e){try{return[null,await e().catch((e=>{throw e}))]}catch(e){return[e,null]}}var V=Object.create;var K=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf;var z=Object.prototype.hasOwnProperty;var __commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);var __copyProps=(e,t,s,r)=>{if(t&&typeof t==="object"||typeof t==="function")for(var o=X(t),n=0,i=o.length,a;n<i;n++){a=o[n];if(!z.call(e,a)&&a!==s)K(e,a,{get:(e=>t[e]).bind(null,a),enumerable:!(r=$(t,a))||r.enumerable})}return e};var __toESM=(e,t,s)=>(s=e!=null?V(Y(e)):{},__copyProps(t||!e||!e.__esModule?K(s,"default",{value:e,enumerable:true}):s,e));const Q=new G.AsyncLocalStorage;function runInRequestContext(e,t){if(Q.getStore())return e();const s={initiator:void 0,logger:t};return Q.run(s,(()=>{const t=e();s.initiator=t;return t}))}const J=createLogger("http-request");function forwardHttpEvents(e){const t=new AbortController;const{source:s,emitter:r,predicate:o,responsePredicate:n}=e;s.on("request",(async e=>{if(o(e.initiator)){J.verbose('forwarding "request" event %o',{requestId:e.requestId});await r.emitAsPromise(e)}}),{signal:t.signal});const responseListener=async e=>{if(o(e.initiator)&&(n==null||n(e))){J.verbose('forwarding "response" event %o',{requestId:e.requestId,responseType:e.responseType});await r.emitAsPromise(e)}};const unhandledExceptionListener=async e=>{if(o(e.initiator)){J.verbose('forwarding "unhandledException" event %o',{requestId:e.requestId});await r.emitAsPromise(e)}};const addResponseListener=()=>{if(!s.listeners("response").includes(responseListener))s.on("response",responseListener,{signal:t.signal})};const addUnhandledExceptionListener=()=>{if(!s.listeners("unhandledException").includes(unhandledExceptionListener))s.on("unhandledException",unhandledExceptionListener,{signal:t.signal})};if(r.listenerCount("response")>0)addResponseListener();if(r.listenerCount("unhandledException")>0)addUnhandledExceptionListener();r.hooks.on("newListener",(e=>{if(e==="response")addResponseListener();if(e==="unhandledException")addUnhandledExceptionListener()}),{signal:t.signal,persist:true});r.hooks.on("removeListener",(e=>{if(e==="response"&&r.listenerCount("response")===0)s.removeListener("response",responseListener);if(e==="unhandledException"&&r.listenerCount("unhandledException")===0)s.removeListener("unhandledException",unhandledExceptionListener)}),{signal:t.signal,persist:true});return()=>{t.abort()}}var Z=class extends a{constructor(e){super(...["request",{}]);this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator;this.controller=e.controller}};var ee=class extends a{constructor(e){super(...["response",{}]);this.response=e.response;this.responseType=e.responseType;this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator}};var te=class extends a{constructor(e){super(...["unhandledException",{}]);this.error=e.error;this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator;this.controller=e.controller}};function connectionOptionsToUrl(e,t){const s=k.isIPv6(e.host||"");const r=t instanceof P.TLSSocket?"https:":getProtocolByConnectionOptions(e);const o=e.host||"localhost";const n=new URL(`${r}//${s?`[${o}]`:o}`);if(e.path)n.pathname=e.path;if(e.port)n.port=e.port.toString();if(e.auth){const[t,s]=e.auth.split(":");n.username=encodeURIComponent(t);n.password=encodeURIComponent(s)}return n}function getProtocolByConnectionOptions(e){if(e.protocol)return e.protocol;if(e.port===443)return"https:";return"http:"}var se=__toESM(__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SPECIAL_HEADERS=e.MINOR=e.MAJOR=e.QDTEXT=e.CONNECTION_TOKEN_CHARS=e.RELAXED_HEADER_CHARS=e.HEADER_CHARS=e.HTAB_SP_VCHAR_OBS_TEXT=e.SP=e.HTAB=e.TOKEN=e.HEX=e.URL_CHAR=e.USERINFO_CHARS=e.MARK=e.ALPHANUM=e.DIGIT=e.HEX_MAP=e.NUM_MAP=e.ALPHA=e.METHODS=e.METHODS_HTTP=e.METHODS_HTTP2=e.METHODS_HTTP1=e.METHODS_RTSP=e.METHODS_RAOP=e.METHODS_AIRPLAY=e.METHODS_ICECAST=e.METHODS_NON_STANDARD=e.METHODS_CALDAV=e.METHODS_UPNP=e.METHODS_SUBVERSION=e.METHODS_WEBDAV=e.METHODS_BASIC_HTTP=e.METHODS_HTTP1_HEAD=e.HEADER_STATE=e.FINISH=e.STATUSES=e.LENIENT_FLAGS=e.FLAGS=e.TYPE=e.ERROR=void 0;e.ERROR={OK:0,INTERNAL:1,STRICT:2,CR_EXPECTED:25,LF_EXPECTED:3,UNEXPECTED_CONTENT_LENGTH:4,UNEXPECTED_SPACE:30,CLOSED_CONNECTION:5,INVALID_METHOD:6,INVALID_URL:7,INVALID_CONSTANT:8,INVALID_VERSION:9,INVALID_HEADER_TOKEN:10,INVALID_CONTENT_LENGTH:11,INVALID_CHUNK_SIZE:12,INVALID_STATUS:13,INVALID_EOF_STATE:14,INVALID_TRANSFER_ENCODING:15,CB_MESSAGE_BEGIN:16,CB_HEADERS_COMPLETE:17,CB_MESSAGE_COMPLETE:18,CB_CHUNK_HEADER:19,CB_CHUNK_COMPLETE:20,PAUSED:21,PAUSED_UPGRADE:22,PAUSED_H2_UPGRADE:23,USER:24,CB_URL_COMPLETE:26,CB_STATUS_COMPLETE:27,CB_METHOD_COMPLETE:32,CB_VERSION_COMPLETE:33,CB_HEADER_FIELD_COMPLETE:28,CB_HEADER_VALUE_COMPLETE:29,CB_CHUNK_EXTENSION_NAME_COMPLETE:34,CB_CHUNK_EXTENSION_VALUE_COMPLETE:35,CB_RESET:31,CB_PROTOCOL_COMPLETE:38};e.TYPE={BOTH:0,REQUEST:1,RESPONSE:2};e.FLAGS={CONNECTION_KEEP_ALIVE:1,CONNECTION_CLOSE:2,CONNECTION_UPGRADE:4,CHUNKED:8,UPGRADE:16,CONTENT_LENGTH:32,SKIPBODY:64,TRAILING:128,TRANSFER_ENCODING:512};e.LENIENT_FLAGS={HEADERS:1,CHUNKED_LENGTH:2,KEEP_ALIVE:4,TRANSFER_ENCODING:8,VERSION:16,DATA_AFTER_CLOSE:32,OPTIONAL_LF_AFTER_CR:64,OPTIONAL_CRLF_AFTER_CHUNK:128,OPTIONAL_CR_BEFORE_LF:256,SPACES_AFTER_CHUNK_SIZE:512,HEADER_VALUE_RELAXED:1024};e.STATUSES={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,RESPONSE_IS_STALE:110,REVALIDATION_FAILED:111,DISCONNECTED_OPERATION:112,HEURISTIC_EXPIRATION:113,MISCELLANEOUS_WARNING:199,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,TRANSFORMATION_APPLIED:214,IM_USED:226,MISCELLANEOUS_PERSISTENT_WARNING:299,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,SWITCH_PROXY:306,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,PAGE_EXPIRED:419,ENHANCE_YOUR_CALM:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL:430,REQUEST_HEADER_FIELDS_TOO_LARGE:431,LOGIN_TIMEOUT:440,NO_RESPONSE:444,RETRY_WITH:449,BLOCKED_BY_PARENTAL_CONTROL:450,UNAVAILABLE_FOR_LEGAL_REASONS:451,CLIENT_CLOSED_LOAD_BALANCED_REQUEST:460,INVALID_X_FORWARDED_FOR:463,REQUEST_HEADER_TOO_LARGE:494,SSL_CERTIFICATE_ERROR:495,SSL_CERTIFICATE_REQUIRED:496,HTTP_REQUEST_SENT_TO_HTTPS_PORT:497,INVALID_TOKEN:498,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,BANDWIDTH_LIMIT_EXCEEDED:509,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511,WEB_SERVER_UNKNOWN_ERROR:520,WEB_SERVER_IS_DOWN:521,CONNECTION_TIMEOUT:522,ORIGIN_IS_UNREACHABLE:523,TIMEOUT_OCCURED:524,SSL_HANDSHAKE_FAILED:525,INVALID_SSL_CERTIFICATE:526,RAILGUN_ERROR:527,SITE_IS_OVERLOADED:529,SITE_IS_FROZEN:530,IDENTITY_PROVIDER_AUTHENTICATION_ERROR:561,NETWORK_READ_TIMEOUT:598,NETWORK_CONNECT_TIMEOUT:599};e.FINISH={SAFE:0,SAFE_WITH_CB:1,UNSAFE:2};e.HEADER_STATE={GENERAL:0,CONNECTION:1,CONTENT_LENGTH:2,TRANSFER_ENCODING:3,UPGRADE:4,CONNECTION_KEEP_ALIVE:5,CONNECTION_CLOSE:6,CONNECTION_UPGRADE:7,TRANSFER_ENCODING_CHUNKED:8};e.METHODS_HTTP1_HEAD={HEAD:2};e.METHODS_BASIC_HTTP={DELETE:0,GET:1,...e.METHODS_HTTP1_HEAD,POST:3,PUT:4,CONNECT:5,OPTIONS:6,TRACE:7,PATCH:28,LINK:31,UNLINK:32};e.METHODS_WEBDAV={COPY:8,LOCK:9,MKCOL:10,MOVE:11,PROPFIND:12,PROPPATCH:13,SEARCH:14,UNLOCK:15,BIND:16,REBIND:17,UNBIND:18,ACL:19};e.METHODS_SUBVERSION={REPORT:20,MKACTIVITY:21,CHECKOUT:22,MERGE:23};e.METHODS_UPNP={"M-SEARCH":24,NOTIFY:25,SUBSCRIBE:26,UNSUBSCRIBE:27};e.METHODS_CALDAV={MKCALENDAR:30};e.METHODS_NON_STANDARD={PURGE:29,QUERY:46};e.METHODS_ICECAST={SOURCE:33};e.METHODS_AIRPLAY={GET:1,POST:3};e.METHODS_RAOP={FLUSH:45};e.METHODS_RTSP={OPTIONS:e.METHODS_BASIC_HTTP.OPTIONS,DESCRIBE:35,ANNOUNCE:36,SETUP:37,PLAY:38,PAUSE:39,TEARDOWN:40,GET_PARAMETER:41,SET_PARAMETER:42,REDIRECT:43,RECORD:44,...e.METHODS_AIRPLAY,...e.METHODS_RAOP};e.METHODS_HTTP1={...e.METHODS_BASIC_HTTP,...e.METHODS_WEBDAV,...e.METHODS_SUBVERSION,...e.METHODS_UPNP,...e.METHODS_CALDAV,...e.METHODS_NON_STANDARD,...e.METHODS_ICECAST};e.METHODS_HTTP2={PRI:34};e.METHODS_HTTP={...e.METHODS_HTTP1,...e.METHODS_HTTP2};e.METHODS={...e.METHODS_HTTP1,...e.METHODS_HTTP2,...e.METHODS_RTSP};e.ALPHA=["A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"];e.NUM_MAP={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9};e.HEX_MAP={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15};e.DIGIT=["0","1","2","3","4","5","6","7","8","9"];e.ALPHANUM=[...e.ALPHA,...e.DIGIT];e.MARK=["-","_",".","!","~","*","'","(",")"];e.USERINFO_CHARS=[...e.ALPHANUM,...e.MARK,"%",";",":","&","=","+","$",","];e.URL_CHAR=["!",'"',"$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","@","[","\\","]","^","_","`","{","|","}","~",...e.ALPHANUM];e.HEX=[...e.DIGIT,"a","b","c","d","e","f","A","B","C","D","E","F"];e.TOKEN=["!","#","$","%","&","'","*","+","-",".","^","_","`","|","~",...e.ALPHANUM];e.HTAB=["\t"];e.SP=[" "];const t=[33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126];const s=[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];e.HTAB_SP_VCHAR_OBS_TEXT=[...e.HTAB,...e.SP,...t,...s];e.HEADER_CHARS=e.HTAB_SP_VCHAR_OBS_TEXT;e.RELAXED_HEADER_CHARS=[...[1,2,3,4,5,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127],...e.HEADER_CHARS];e.CONNECTION_TOKEN_CHARS=[...e.HTAB,...e.SP,33,34,35,36,37,38,39,40,41,42,43,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,...s];e.QDTEXT=[...e.HTAB,...e.SP,33,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,...s];e.MAJOR=e.NUM_MAP;e.MINOR=e.MAJOR;e.SPECIAL_HEADERS={connection:e.HEADER_STATE.CONNECTION,"content-length":e.HEADER_STATE.CONTENT_LENGTH,"proxy-connection":e.HEADER_STATE.CONNECTION,"transfer-encoding":e.HEADER_STATE.TRANSFER_ENCODING,upgrade:e.HEADER_STATE.UPGRADE};e.default={ERROR:e.ERROR,TYPE:e.TYPE,FLAGS:e.FLAGS,LENIENT_FLAGS:e.LENIENT_FLAGS,STATUSES:e.STATUSES,FINISH:e.FINISH,HEADER_STATE:e.HEADER_STATE,ALPHA:e.ALPHA,NUM_MAP:e.NUM_MAP,HEX_MAP:e.HEX_MAP,DIGIT:e.DIGIT,ALPHANUM:e.ALPHANUM,MARK:e.MARK,USERINFO_CHARS:e.USERINFO_CHARS,URL_CHAR:e.URL_CHAR,HEX:e.HEX,TOKEN:e.TOKEN,HEADER_CHARS:e.HEADER_CHARS,RELAXED_HEADER_CHARS:e.RELAXED_HEADER_CHARS,CONNECTION_TOKEN_CHARS:e.CONNECTION_TOKEN_CHARS,QDTEXT:e.QDTEXT,HTAB_SP_VCHAR_OBS_TEXT:e.HTAB_SP_VCHAR_OBS_TEXT,MAJOR:e.MAJOR,MINOR:e.MINOR,SPECIAL_HEADERS:e.SPECIAL_HEADERS,METHODS:e.METHODS,METHODS_HTTP:e.METHODS_HTTP,METHODS_HTTP1_HEAD:e.METHODS_HTTP1_HEAD,METHODS_HTTP1:e.METHODS_HTTP1,METHODS_HTTP2:e.METHODS_HTTP2,METHODS_ICECAST:e.METHODS_ICECAST,METHODS_RTSP:e.METHODS_RTSP}}))(),1);const re=se.TYPE.REQUEST;se.TYPE.RESPONSE;const oe=Symbol("kPtr");const ne=Symbol("kUrl");const ie=Symbol("kStatusMessage");const ae=Symbol("kHeadersFields");const ce=Symbol("kHeadersValues");const le=Symbol("kLastHeaderCallback");const ue=Symbol("kCallbacks");const he=Symbol("kType");const de=0;const pe=1;const fe=2;const Ee=new Map;const Te=Object.fromEntries(Object.entries(se.METHODS).map((([e,t])=>[t,e])));function readStringFrom(e,t){return Buffer.from(Ae.buffer,e,t).toString("latin1")}const Re=require("url").pathToFileURL(__filename).href;const Se=new WebAssembly.Module(j.readFileSync(new URL("./llhttp/llhttp.wasm",Re)));const _e=new WebAssembly.Instance(Se,{env:{wasm_on_message_begin(e){const t=Ee.get(e);t[ne]="";t[ie]="";t[ae]=[];t[ce]=[];t[le]=de;return t[ue].onMessageBegin?.()??0},wasm_on_url(e,t,s){Ee.get(e)[ne]=readStringFrom(t,s);return 0},wasm_on_status(e,t,s){Ee.get(e)[ie]=readStringFrom(t,s);return 0},wasm_on_header_field(e,t,s){const r=Ee.get(e);const o=readStringFrom(t,s);const n=r[ae];if(r[le]===pe)n[n.length-1]+=o;else{n.push(o);r[le]=pe}return 0},wasm_on_header_value(e,t,s){const r=Ee.get(e);const o=readStringFrom(t,s);const n=r[ce];if(r[le]===fe)n[n.length-1]+=o;else{n.push(o);r[le]=fe}return 0},wasm_on_headers_complete(e,t,s,r){const o=Ee.get(e);const n=be(e);const i=Ne(e);const a=[];const c=s===1;const l=r===1;for(let e=0;e<o[ae].length;e++)a.push(o[ae][e],o[ce][e]);if(o[he]===re){const t=Te[ye(e)];const s=o[ne];return o[ue].onHeadersComplete?.({versionMajor:n,versionMinor:i,rawHeaders:a,method:t,url:s,upgrade:c,shouldKeepAlive:l})??0}else{const t=Ce(e);const s=o[ie];return o[ue].onHeadersComplete?.({versionMajor:n,versionMinor:i,rawHeaders:a,statusCode:t,statusMessage:s,upgrade:c,shouldKeepAlive:l})??0}},wasm_on_body(e,t,s){const r=Ee.get(e);const o=Buffer.from(new Uint8Array(Ae.buffer,t,s));return r[ue].onBody?.(o)??0},wasm_on_message_complete(e){return Ee.get(e)[ue].onMessageComplete?.()??0}}});const Ae=_e.exports.memory;const ge=_e.exports.llhttp_alloc;const Oe=_e.exports.malloc;const me=_e.exports.llhttp_execute;_e.exports.llhttp_get_type;_e.exports.llhttp_get_upgrade;_e.exports.llhttp_should_keep_alive;const ye=_e.exports.llhttp_get_method;const Ce=_e.exports.llhttp_get_status_code;const Ne=_e.exports.llhttp_get_http_minor;const be=_e.exports.llhttp_get_http_major;const ke=_e.exports.llhttp_get_error_reason;const Pe=_e.exports.llhttp_get_error_pos;const Ie=_e.exports.free;const He=_e.exports._initialize;He();var De=class{constructor(e,t){this[ne]="";this[ie]="";this[ae]=[];this[ce]=[];this[le]=de;this[he]=e;this[ue]=t;const s=ge(e);if(s===0)throw new Error("Failed to allocate llhttp parser");this[oe]=s;Ee.set(this[oe],this)}destroy(){if(this[oe]===0)return;Ee.delete(this[oe]);Ie(this[oe]);this[oe]=0}execute(e){const t=Oe(e.byteLength);if(t===0)throw new Error("Failed to allocate llhttp input buffer");let s;try{new Uint8Array(Ae.buffer).set(e,t);s=me(this[oe],t,e.byteLength)}catch(e){Ie(t);throw e}if(s===se.ERROR.PAUSED_UPGRADE){const s=Pe(this[oe])-t;Ie(t);return e.subarray(s)}Ie(t);this.#J(s);return null}#J(e){if(e===se.ERROR.OK)return;const t=ke(this[oe]);const s=new Uint8Array(Ae.buffer).indexOf(0,t)-t;throw new Error(readStringFrom(t,s))}};var Le=class extends De{#Z;constructor(e){super(1,{onHeadersComplete:({rawHeaders:t,method:s,url:r})=>{const o=(s||e.connectionOptions.method||"GET").toUpperCase();const n=new URL(r||"",e.connectionOptions.url);const i=N.parseRawHeaders([...t]);if(n.username||n.password){if(!i.has("authorization")){const e=Buffer.from(`${n.username}:${n.password}`).toString("base64");i.set("authorization",`Basic ${e}`)}n.username="";n.password=""}this.#Z=new W.Readable({read:()=>{}});const a=new AbortController;const c=new m(n,{method:o,headers:i,credentials:"same-origin",body:W.Readable.toWeb(this.#Z),signal:a.signal});e.onRequest(c,a)},onBody:e=>{invariant(this.#Z,"Failed to write to a request stream: stream does not exist. This is likely an issue with the library. Please report it on GitHub.");this.#Z.push(e)},onMessageComplete:()=>{this.#Z?.push(null)}})}free(){this.destroy();this.#Z?.destroy();this.#Z=void 0}};var we=class extends De{#ee;constructor(e){super(2,{onHeadersComplete:({rawHeaders:t,statusCode:s,statusMessage:r})=>{const o=N.parseRawHeaders([...t]);const n=new N(N.isResponseWithBody(s)?W.Readable.toWeb(this.#ee=new W.Readable({read(){}})):null,{status:s,statusText:r,headers:o});e.onResponse(n)},onBody:e=>{invariant(this.#ee,"Failed to read from a response stream: stream does not exist. This is likely an issue with the library. Please report it on GitHub.");this.#ee.push(e)},onMessageComplete:()=>{this.#ee?.push(null)}})}free(){this.destroy();this.#ee=null}};function isNodeLikeError(e){if(e==null)return false;if(!(e instanceof Error))return false;return"code"in e&&"errno"in e}async function handleRequest(e){if(e.logger?.isEnabled("default"))formatRequest(e.request).then((t=>{e.logger?.info("[%s] %s",e.requestId,t)}));const handleResponse=async t=>{if(t instanceof Error){await e.controller.errorWith(t);return true}if(isResponseError(t)){await e.controller.respondWith(t);return true}if(isResponseLike(t)){await e.controller.respondWith(t);return true}if(isObject(t)){await e.controller.errorWith(t);return true}return false};const handleResponseError=async t=>{if(t instanceof S)throw o;if(isNodeLikeError(t)){await e.controller.errorWith(t);return true}if(t instanceof Response)return await handleResponse(t);return false};const t=Promise.withResolvers();let s;let r=false;const onAbort=()=>{r=true;s=e.request.signal?.reason;t.reject(s)};if(e.request.signal){if(e.request.signal.aborted){await e.controller.errorWith(e.request.signal.reason);return}e.request.signal.addEventListener("abort",onAbort,{once:true})}const[o]=await until((async()=>{const s=new Z({initiator:e.initiator,requestId:e.requestId,request:e.request,controller:e.controller});const r=e.emitter.emitAsPromise(s);await Promise.race([t.promise,r,e.controller.handled]);if(s.request!==e.request)e.request=s.request}));e.request.signal?.removeEventListener("abort",onAbort);if(r){await e.controller.errorWith(s);return}if(o){if(await handleResponseError(o))return;if(e.emitter.listenerCount("unhandledException")>0){const t=new _(e.request,{passthrough(){},async respondWith(e){await handleResponse(e)},async errorWith(t){await e.controller.errorWith(t)}});await e.emitter.emitAsPromise(new te({initiator:e.initiator,error:o,request:e.request,requestId:e.requestId,controller:t}));if(t.readyState!==_.PENDING)return}await e.controller.respondWith(createServerErrorResponse(o));return}if(e.controller.readyState===_.PENDING)return await e.controller.passthrough();return e.controller.handled}const ve=createLogger("http-request");var Me=class extends p{static{this.symbol=Symbol.for("node-http-request-source")}predicate(){return true}setup(){const e=p.singleton(x);e.apply(this);this.subscriptions.push((()=>{e.dispose(this)}));this.subscriptions.push(recordRawFetchHeaders());const t=new AbortController;this.subscriptions.push((()=>t.abort()));e.on("connection",(({connectionOptions:e,socket:t,controller:s})=>{let r;let o;let n;let i;const a=Q.getStore();const c=s[L];const l=c._destroy.bind(c);c._destroy=(e,t)=>{i?.();l(e,t)};t.on("data",(c=>{if(r===false)return;if(n&&o){o.free();o=void 0;r=void 0;s.reset()}if(o){o.execute(toBuffer(c));return}const l=c.toString();const u=l.split(" ")[0]||"";if(!b.METHODS.includes(u.toUpperCase())){r=false;return}r=true;const h=n??connectionOptionsToUrl(e,t);ve.verbose("handling http message %o",{httpMessage:l,httpMethod:u,baseUrl:h});const d=Q.getStore()??a;const p=d?.initiator||t;o=new Le({connectionOptions:{method:u,url:h},onRequest:async(e,r)=>{const o=d?.transformRequest?.(e)??e;if(s["readyState"]!==M.PENDING)s.reset();const a=createRequestId();const c=d?.logger??ve;ve.verbose("received a parsed HTTP request %o",{method:o.method,url:o.url});const l=new _(o,{respondWith:async e=>{ve.verbose("respondWith() %o",{status:e.status,statusText:e.statusText,hasBody:e.body!=null});if(t.destroyed)return;s.claim();const r=N.from(e,{url:o.url});if(o.method==="CONNECT"&&r.ok)n=new URL(`http://${o.url}`);const i=isResponseError(r)?null:r.clone();const respond=()=>this.respondWith({socket:s[L],request:u.request,response:r});if(i)await this.emitter.emitAsPromise(new ee({initiator:p,requestId:a,request:u.request,response:i,responseType:"mock"}));if(t.connecting)t.once("connect",respond);else await respond()},errorWith:e=>{if(e instanceof Error)t.destroy(e)},passthrough:()=>{const e=s.passthrough(this.#te(u.request));if(this.emitter.listenerCount("response")>0){ve.verbose('found "response" listener, corking socket reads');s.corkReads();const t=new we({onResponse:async e=>{ve.verbose("HTTP response parser parsed: %d %s",e.status,e.statusText);if(isResponseError(e)){ve.verbose("response is an error response, uncorking socket reads...");s.uncorkReads();return}N.setUrl(o.url,e);try{ve.verbose('emitting "response" event');await this.emitter.emitAsPromise(new ee({initiator:p,requestId:a,request:u.request,response:e,responseType:"original"}))}finally{ve.verbose("uncorking socket reads");s.uncorkReads();if(e.status<200&&e.status!==101)s.corkReads()}}});e.on("data",(e=>t.execute(e))).on("close",(()=>t.free()))}}},{logger:c,requestId:a});invariant(s["readyState"]===M.PENDING,"CANNOT HANDLE ALREADY HANDLED REQUEST",o.method,o.url,s["readyState"]);const u={initiator:p,requestId:a,request:o,controller:l,emitter:this.emitter,logger:c};i=()=>{if(l.readyState===_.PENDING)r.abort()};try{await handleRequest(u)}finally{i=void 0}}});o.execute(toBuffer(c))}));t.on("close",(()=>o?.free()))}),{signal:t.signal})}async respondWith(e){const{socket:t,request:s,response:r}=e;if(t.destroyed)return;if(isResponseError(r)){t.destroy(Object.defineProperty(new TypeError("Network error"),O,{value:r,enumerable:false}));return}invariant(!t.connecting,'Failed to mock a response for "%s %s": socket has not connected',s.method,s.url);const o=new b.IncomingMessage(t);o.method=s.method;const n=new b.ServerResponse(o);const i=new k.Socket;i._writeGeneric=(e,s,r,o)=>{unwrapPendingData(s,((e,s)=>{t.push(toBuffer(e),s)}));o?.()};i._destroy=(e,s)=>{if(e)t.destroy();s(null)};i.on("drain",(()=>n.emit("drain")));n.assignSocket(i);n.removeHeader("connection");n.removeHeader("date");const a=getRawFetchHeaders(r.headers);n.writeHead(r.status,r.statusText||b.STATUS_CODES[r.status],a);t._destroy=function(e,t){if(e)queueMicrotask((()=>this.emit("error",e)));t(null);process.nextTick((()=>this.emit("close",e!=null)))};if(r.body){const e=r.body.getReader();try{while(true){const{done:t,value:s}=await e.read();if(t){n.end();break}if(!n.write(s))await new Promise((e=>{n.once("drain",e)}))}}catch{await new Promise((e=>process.nextTick(e)));t.destroy();return}}else n.end();const c=s.method==="HEAD"||r.headers.has("content-length")||r.headers.has("transfer-encoding")||!N.isResponseWithBody(r.status);if(s.method!=="CONNECT"&&!c){await new Promise((e=>process.nextTick(e)));t.push(null)}}#te(e){const transformRequestMessage=(t,s)=>{if(s==="buffer")return t;const r=t.toString(s).split("\r\n");const o=r.findIndex((e=>e===""));const n=r.slice(1,o);const i=n.map((e=>{const t=e.indexOf(": ");return[e.slice(0,t),e.slice(t+2)]}));const a=getRawFetchHeaders(e.headers);if(i.length===a.length&&i.every(((e,t)=>{const s=a[t];return e[0]===s[0]&&e[1]===s[1]})))return t;const c=N.parseRawHeaders(n.flatMap((e=>e.split(": "))));const l=new Set;for(const[t]of a){const s=t.toLowerCase();if(l.has(s))continue;l.add(s);const r=e.headers.get(t);if(r===null)continue;c.set(t,r)}l.clear();const u=Array.from(c).map((([e,t])=>`${e}: ${t}`)).join("\r\n");r.splice(1,o-1,u);return r.join("\r\n")};return(e,t,s)=>{if(Array.isArray(e))e[0].chunk=transformRequestMessage(e[0].chunk,e[0].encoding);else e=transformRequestMessage(e,t);s(e)}}};var Ue=require("node:https");var qe=class extends p{static{this.symbol=Symbol.for("client-request-interceptor")}predicate(){return true}setup(){const e=p.singleton(Me);const t=this.logger;e.apply(this);this.subscriptions.push((()=>{e.dispose(this)}));this.subscriptions.push(forwardHttpEvents({source:e,emitter:this.emitter,predicate:e=>e instanceof b.ClientRequest}));this.subscriptions.push(H.applyPatch(b,"ClientRequest",(e=>new Proxy(e,{construct(e,s,r){return runInRequestContext((()=>Reflect.construct(e,s,r)),t)}}))),H.applyPatch(b,"get",(e=>function mockHttpGet(...s){return runInRequestContext((()=>e(...s)),t)})),H.applyPatch(b,"request",(e=>function mockHttpRequest(...s){return runInRequestContext((()=>e(...s)),t)})),H.applyPatch(Ue,"get",(e=>function mockHttpsGet(...s){return runInRequestContext((()=>e(...s)),t)})),H.applyPatch(Ue,"request",(e=>function mockHttpsRequest(...s){return runInRequestContext((()=>e(...s)),t)})))}}}};var t={};function __nccwpck_require__(s){var r=t[s];if(r!==undefined){return r.exports}var o=t[s]={exports:{}};var n=true;try{e[s](o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete t[s]}return o.exports}!function(){__nccwpck_require__.d=function(e,t){for(var s in t){if(__nccwpck_require__.o(t,s)&&!__nccwpck_require__.o(e,s)){Object.defineProperty(e,s,{enumerable:true,get:t[s]})}}}}();!function(){__nccwpck_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}}();!function(){__nccwpck_require__.r=function(e){if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}}();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(349);module.exports=s})(); |
@@ -434,3 +434,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; | ||
| "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && | ||
@@ -437,0 +437,0 @@ "function" === |
@@ -225,2 +225,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; |
@@ -348,3 +348,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; | ||
| })(); |
@@ -161,2 +161,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; |
@@ -75,6 +75,6 @@ { | ||
| "dependencies": { | ||
| "scheduler": "0.0.0-experimental-28cd4bb0-20260723" | ||
| "scheduler": "0.0.0-experimental-756fdd47-20260727" | ||
| }, | ||
| "peerDependencies": { | ||
| "react": "0.0.0-experimental-28cd4bb0-20260723" | ||
| "react": "0.0.0-experimental-756fdd47-20260727" | ||
| }, | ||
@@ -81,0 +81,0 @@ "browser": { |
@@ -434,3 +434,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; | ||
| "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && | ||
@@ -437,0 +437,0 @@ "function" === |
@@ -225,2 +225,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; |
@@ -348,3 +348,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; | ||
| })(); |
@@ -161,2 +161,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; |
@@ -70,6 +70,6 @@ { | ||
| "dependencies": { | ||
| "scheduler": "0.28.0-canary-28cd4bb0-20260723" | ||
| "scheduler": "0.28.0-canary-756fdd47-20260727" | ||
| }, | ||
| "peerDependencies": { | ||
| "react": "19.3.0-canary-28cd4bb0-20260723" | ||
| "react": "19.3.0-canary-756fdd47-20260727" | ||
| }, | ||
@@ -76,0 +76,0 @@ "browser": { |
@@ -1394,3 +1394,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; | ||
| "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && | ||
@@ -1397,0 +1397,0 @@ "function" === |
@@ -616,2 +616,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; |
@@ -1064,3 +1064,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; | ||
| })(); |
@@ -582,2 +582,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-experimental-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-experimental-756fdd47-20260727"; |
| { | ||
| "name": "react-is", | ||
| "version": "19.3.0-canary-28cd4bb0-20260723", | ||
| "version": "19.3.0-canary-756fdd47-20260727", | ||
| "description": "Brand checking of React Elements.", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -51,5 +51,5 @@ { | ||
| "peerDependencies": { | ||
| "react": "0.0.0-experimental-28cd4bb0-20260723", | ||
| "react-dom": "0.0.0-experimental-28cd4bb0-20260723" | ||
| "react": "0.0.0-experimental-756fdd47-20260727", | ||
| "react-dom": "0.0.0-experimental-756fdd47-20260727" | ||
| } | ||
| } |
@@ -51,5 +51,5 @@ { | ||
| "peerDependencies": { | ||
| "react": "19.3.0-canary-28cd4bb0-20260723", | ||
| "react-dom": "19.3.0-canary-28cd4bb0-20260723" | ||
| "react": "19.3.0-canary-756fdd47-20260727", | ||
| "react-dom": "19.3.0-canary-756fdd47-20260727" | ||
| } | ||
| } |
@@ -55,6 +55,6 @@ { | ||
| "peerDependencies": { | ||
| "react": "0.0.0-experimental-28cd4bb0-20260723", | ||
| "react-dom": "0.0.0-experimental-28cd4bb0-20260723", | ||
| "react": "0.0.0-experimental-756fdd47-20260727", | ||
| "react-dom": "0.0.0-experimental-756fdd47-20260727", | ||
| "webpack": "^5.59.0" | ||
| } | ||
| } |
@@ -55,6 +55,6 @@ { | ||
| "peerDependencies": { | ||
| "react": "19.3.0-canary-28cd4bb0-20260723", | ||
| "react-dom": "19.3.0-canary-28cd4bb0-20260723", | ||
| "react": "19.3.0-canary-756fdd47-20260727", | ||
| "react-dom": "19.3.0-canary-756fdd47-20260727", | ||
| "webpack": "^5.59.0" | ||
| } | ||
| } |
@@ -1325,3 +1325,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; | ||
| "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && | ||
@@ -1328,0 +1328,0 @@ "function" === |
@@ -565,2 +565,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; |
@@ -877,3 +877,3 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; | ||
| })(); |
@@ -436,2 +436,2 @@ /** | ||
| }; | ||
| exports.version = "19.3.0-canary-28cd4bb0-20260723"; | ||
| exports.version = "19.3.0-canary-756fdd47-20260727"; |
@@ -1,1 +0,1 @@ | ||
| (()=>{var t={840:t=>{function n(t,i){for(var _ in i)t[_]=i[_];return t}t.exports=function(t){var i=[];function u(t){for(var _=[],a=0;a<i.length;a++)i[a]===t?t=null:_.push(i[a]);i=_}function e(_,a,f){t=a?_:n(n({},t),_);for(var o=i,c=0;c<o.length;c++)o[c](t,f)}return t=t||{},{action:function(i){function r(t){e(t,!1,i)}return function(){for(var _=arguments,a=[t],f=0;f<arguments.length;f++)a.push(_[f]);var o=i.apply(this,a);if(null!=o)return o.then?o.then(r):r(o)}},setState:e,subscribe:function(t){return i.push(t),function(){u(t)}},unsubscribe:u,getState:function(){return t}}}}};var i={};function __nccwpck_require__(_){var a=i[_];if(a!==undefined){return a.exports}var f=i[_]={exports:{}};var o=true;try{t[_](f,f.exports,__nccwpck_require__);o=false}finally{if(o)delete i[_]}return f.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var _=__nccwpck_require__(840);module.exports=_})(); | ||
| (()=>{var t={396:t=>{function n(t,i){for(var _ in i)t[_]=i[_];return t}t.exports=function(t){var i=[];function u(t){for(var _=[],a=0;a<i.length;a++)i[a]===t?t=null:_.push(i[a]);i=_}function e(_,a,f){t=a?_:n(n({},t),_);for(var o=i,c=0;c<o.length;c++)o[c](t,f)}return t=t||{},{action:function(i){function r(t){e(t,!1,i)}return function(){for(var _=arguments,a=[t],f=0;f<arguments.length;f++)a.push(_[f]);var o=i.apply(this,a);if(null!=o)return o.then?o.then(r):r(o)}},setState:e,subscribe:function(t){return i.push(t),function(){u(t)}},unsubscribe:u,getState:function(){return t}}}}};var i={};function __nccwpck_require__(_){var a=i[_];if(a!==undefined){return a.exports}var f=i[_]={exports:{}};var o=true;try{t[_](f,f.exports,__nccwpck_require__);o=false}finally{if(o)delete i[_]}return f.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var _=__nccwpck_require__(396);module.exports=_})(); |
@@ -16,7 +16,7 @@ --- | ||
| Beyond the docs, Next.js gives agents [runtime visibility](#runtime-visibility) into the running dev server, with forwarded browser logs, an [MCP server](/docs/app/guides/mcp), and a browser they can drive. [Skills](#skills-for-multi-step-workflows) package multi-step workflows like adopting Cache Components. | ||
| Point agents at the bundled docs, give them [runtime visibility](#step-2-give-agents-runtime-visibility) into the dev server, let [errors drive the fixes](#step-3-let-errors-drive-the-fixes), and hand multi-step workflows to [skills](#step-4-hand-multi-step-workflows-to-skills). | ||
| ## How it works | ||
| ## Step 1: Point agents at the bundled docs | ||
| When you install `next`, the Next.js documentation is bundled at `node_modules/next/dist/docs/`. The bundled docs mirror the structure of the [Next.js documentation site](https://nextjs.org/docs): | ||
| Make sure `AGENTS.md` exists at your project root and directs agents to the bundled docs. When you install `next`, the Next.js documentation is bundled at `node_modules/next/dist/docs/`, mirroring the structure of the [Next.js documentation site](https://nextjs.org/docs): | ||
@@ -34,8 +34,4 @@ ```txt | ||
| This means agents always have access to docs that match your installed version, with no network request or external lookup required. [Upgrading Next.js](/docs/app/getting-started/upgrading) also upgrades the bundled docs, including new guidance for existing features. | ||
| Agents always have access to docs that match your installed version, with no network request or external lookup required. [Upgrading Next.js](/docs/app/getting-started/upgrading) also upgrades the bundled docs, including new guidance for existing features. Most AI coding agents, including Claude Code, Codex, Cursor, and GitHub Copilot, automatically read `AGENTS.md` when they start a session. | ||
| The `AGENTS.md` file at the root of your project tells agents to read these bundled docs before writing any code. Most AI coding agents, including Claude Code, Cursor, and GitHub Copilot, automatically read `AGENTS.md` when they start a session. | ||
| ## Getting started | ||
| ### New projects | ||
@@ -113,20 +109,54 @@ | ||
| ## Runtime visibility | ||
| ### Docs over the network | ||
| Agents also need to see what the running app is doing. Runtime errors, client-side warnings, and rendered output live in the browser, where agents can't look. Next.js surfaces two complementary views that an agent can read from the terminal. | ||
| The Next.js docs are also available as Markdown over the network, for agents that fetch pages instead of reading `node_modules`. Append `.md` to any page URL on [nextjs.org/docs](https://nextjs.org/docs) for a plain Markdown version, and clients that send an `Accept: text/markdown` header get Markdown too. This includes the per-error pages under `/docs/messages`, which are not bundled. | ||
| The index at [`/docs/llms.txt`](https://nextjs.org/docs/llms.txt) and the single-file [`/docs/llms-full.txt`](https://nextjs.org/docs/llms-full.txt) follow the [`llms.txt` convention](https://llmstxt.org/), so agents that already read `llms.txt` for other tools can discover the Next.js docs the same way. | ||
| ## Step 2: Give agents runtime visibility | ||
| Run `next dev` and let the agent work against the running server. Runtime errors, client-side warnings, and rendered output live in the browser, where agents can't look. Next.js surfaces two complementary views that an agent can read from the terminal. | ||
| First, `next dev` forwards browser console errors and warnings to the terminal (the [`logging.browserToTerminal`](/docs/app/api-reference/config/next-config-js/logging) config), so the output agents already read carries the client-side failures they're asked to fix. | ||
| The **framework's view** comes from the [Next.js MCP server](/docs/app/guides/mcp) at `/_next/mcp`: the running dev server's routes, server logs, and compilation issues. Its `get_compilation_issues` and `compile_route` tools report whether the code compiles straight from the dev server, so an agent doesn't have to run a full `next build` to find out. | ||
| `next dev` also writes its PID, port, and URL to `.next/dev/lock`. A second `next dev` in the same project prints the running server's URL and the PID to kill, so an agent connects to the existing server instead of starting a duplicate. | ||
| The **framework's view** comes from the [Next.js MCP server](/docs/app/guides/mcp) at `/_next/mcp`, which exposes the running dev server's routes, server logs, and compilation issues. Its `get_compilation_issues` and `compile_route` tools report whether the code compiles straight from the dev server, so an agent doesn't have to run a full `next build` to find out. | ||
| The **browser's view** comes from [`agent-browser`](https://github.com/vercel-labs/agent-browser), a CLI that exposes the DOM, console, network, and Web Vitals as structured text. With React DevTools enabled (pass `--enable react-devtools` to `agent-browser open`, which the `next-dev-loop` skill does for you), it also reports the component tree and which Suspense boundaries are still pending. An agent runs a command like `react tree`, reads the output, and decides what to inspect next, instead of looking at a DevTools panel it can't see. | ||
| The [`next-dev-loop` skill](#skills-for-multi-step-workflows) builds on both views, combining the framework's and the browser's perspective into a single edit-and-verify loop. | ||
| The [`next-dev-loop` skill](#next-dev-loop) builds on both views, combining the framework's and the browser's perspective into a single edit-and-verify loop. | ||
| > **Good to know:** For the story behind this tooling, see the [Next.js 16.2](https://nextjs.org/blog/next-16-2-ai) and [Next.js 16.3](https://nextjs.org/blog/next-16-3-ai-improvements) AI blog posts. | ||
| ## Skills for multi-step workflows | ||
| ## Step 3: Let errors drive the fixes | ||
| Some tasks are workflows rather than lookups, such as adopting Cache Components or Partial Prefetching across an app. [Next.js skills](https://github.com/vercel/next.js/tree/canary/skills) package these as structured instructions an agent installs and follows, sequencing the work and pointing at the relevant docs at each step. | ||
| With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, a blocking error presents labeled fixes, each making a different trade-off. The dev overlay adds a **Copy prompt** button that packages the chosen fix into a paste-ready prompt. The prompt walks the agent through reading the matching error page, applying the canonical pattern, and verifying the result at runtime. | ||
| The same menu prints in the `next dev` terminal and in `next build` output, so an agent reading CI logs sees it too: | ||
| ```txt filename="Terminal" | ||
| Route "/products/[slug]": Next.js encountered uncached data during prerendering. | ||
| `fetch(...)` or `connection()` accessed outside of `<Suspense>` prevents the route | ||
| from being prerendered, blocking the page load and leading to a slower user experience. | ||
| Ways to fix this: | ||
| - [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access | ||
| - [cache] Cache the data access with `"use cache"` (does not apply to `connection()`) | ||
| - [block] Set `export const instant = false` to allow a blocking route | ||
| Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic | ||
| at ProductPage (app/products/[slug]/page.tsx:52:32) | ||
| ... | ||
| ``` | ||
| In `next dev` the stack frame resolves to your source, in both the dev overlay and the terminal. A production build minifies server code, so when the build error alone isn't enough, [`next build --debug-prerender`](/docs/app/guides/building#debugging-build-errors) turns on server source maps and continues past the first failure. | ||
| The `Learn more` link resolves to a per-error page under [`/docs/messages`](https://nextjs.org/docs/messages/blocking-prerender-dynamic) written for agents to read. Each page follows the same shape, with the canonical patterns for every fix, the trade-offs against the other fixes, and the gotchas an agent is likely to miss on a first attempt. The [Instant navigation guide](/docs/app/guides/instant-navigation#ai-workflow) shows the full observe-fix-iterate loop an agent runs on these errors, from reading the insight to asserting on the result with an `instant()` test. | ||
| ## Step 4: Hand multi-step workflows to skills | ||
| Framework knowledge comes from the bundled docs, not from skills. [Benchmark results](https://nextjs.org/evals) show that always-available context outperforms on-demand retrieval. Skills cover the tasks that are workflows rather than lookups, such as adopting Cache Components or Partial Prefetching across an app. [Next.js skills](https://www.skills.sh/vercel/next.js) package these as structured instructions an agent installs and follows, sequencing the work and pointing at the relevant docs and [runtime tooling](#step-2-give-agents-runtime-visibility) at each step. | ||
| ### `next-dev-loop` | ||
@@ -133,0 +163,0 @@ |
@@ -475,3 +475,3 @@ --- | ||
| For agents to see what their changes actually render, pair this with [agent-browser](https://github.com/vercel-labs/agent-browser). With React DevTools enabled it reports the component tree and which `<Suspense>` boundaries are still pending, so an agent can make a change, snapshot the shell, check what landed, and adjust. See [Runtime visibility](/docs/app/guides/ai-agents#runtime-visibility) in the AI agents guide for the setup. | ||
| For agents to see what their changes actually render, pair this with [agent-browser](https://github.com/vercel-labs/agent-browser). With React DevTools enabled it reports the component tree and which `<Suspense>` boundaries are still pending, so an agent can make a change, snapshot the shell, check what landed, and adjust. See [Runtime visibility](/docs/app/guides/ai-agents#step-2-give-agents-runtime-visibility) in the AI agents guide for the setup. | ||
@@ -478,0 +478,0 @@ The [`next-cache-components-optimizer`](/docs/app/guides/ai-agents#next-cache-components-optimizer) skill packages this loop: it encodes the goal as a failing `@next/playwright` `instant()` test and works it to green one route at a time, for both initial load (hard navigation) and client-side navigation (soft navigation), then ships the test as a regression guard. |
@@ -237,8 +237,9 @@ --- | ||
| | Option | Type | Default | Description | | ||
| | -------- | --------------------------------------------- | ----------- | ---------------------------------------------------------------------- | | ||
| | `eager` | `boolean` | `false` | Import modules synchronously instead of returning thunks. | | ||
| | `import` | `string` | `undefined` | Named export to select from each matched module (e.g. `'default'`). | | ||
| | `query` | `string \| Record<string, string \| boolean>` | `undefined` | Query string (or object) to append to each import. | | ||
| | `base` | `string` | `undefined` | Override the base path used for resolving patterns and keying results. | | ||
| | Option | Type | Default | Description | | ||
| | --------------- | --------------------------------------------- | ----------- | -------------------------------------------------------------------------- | | ||
| | `eager` | `boolean` | `false` | Import modules synchronously instead of returning thunks. | | ||
| | `import` | `string` | `undefined` | Named export to select from each matched module (e.g. `'default'`). | | ||
| | `query` | `string \| Record<string, string \| boolean>` | `undefined` | Query string (or object) to append to each import. | | ||
| | `base` | `string` | `undefined` | Override the base path used for resolving patterns and keying results. | | ||
| | `caseSensitive` | `boolean` | `true` | Match glob patterns case-sensitively. Set to `false` to ignore ASCII case. | | ||
@@ -245,0 +246,0 @@ > **Note:** The `as` option (deprecated in Vite 5) is not supported. Use `query: '?raw'` or `query: '?url'` instead. The legacy `import.meta.globEager()` API is also not supported — use `import.meta.glob('...', { eager: true })` instead. |
@@ -199,2 +199,11 @@ --- | ||
| If you omit `pathname`, the query is applied to the URL shown in the browser ([`asPath`](#router-object)) rather than to the current page's route (`pathname`). This keeps [rewrites](/docs/pages/api-reference/config/next-config-js/rewrites) intact: on a page served by a rewrite, a query-only navigation preserves the URL the visitor requested instead of revealing the rewrite destination. | ||
| The two values also differ when you mask the URL yourself with the `as` parameter. Pass `pathname` explicitly in that case, otherwise the query is applied to the masked URL and can resolve to a different page: | ||
| ```jsx | ||
| // On the `/` page, with the URL masked as `/p/1` | ||
| router.push({ pathname: '/', query: { photoId: 2 } }, '/p/2', { shallow: true }) | ||
| ``` | ||
| ### router.replace | ||
@@ -201,0 +210,0 @@ |
@@ -132,2 +132,9 @@ // Import cpu-profile to start profiling early if enabled | ||
| '**/next/dist/server/lib/route-resolver*', | ||
| // The testmode interceptors bundle reads its HTTP parser WASM with a | ||
| // dynamic path, making nft trace the bundle's whole directory. Test | ||
| // proxying is not supported in standalone output, so keep the parser | ||
| // asset (and the license file picked up by the directory glob) out of | ||
| // production traces. | ||
| '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/LICENSE', | ||
| '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/llhttp/**/*', | ||
| 'next/dist/compiled/semver/semver/**/*.js', | ||
@@ -134,0 +141,0 @@ ...ciEnvironment.hasNextSupport ? [ |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/build/collect-build-traces.ts"],"sourcesContent":["// Import cpu-profile to start profiling early if enabled\nimport '../server/lib/cpu-profile'\nimport { Span } from '../trace'\nimport type { NextConfigComplete } from '../server/config-shared'\n\nimport {\n TRACE_IGNORES,\n type BuildTraceContext,\n getFilesMapFromReasons,\n} from './webpack/plugins/next-trace-entrypoints-plugin'\n\nimport path from 'path'\nimport { resolveCacheHandlerPathToFilesystem } from '../lib/format-dynamic-import-path'\nimport fs from 'fs/promises'\nimport { nonNullable } from '../lib/non-nullable'\nimport * as ciEnvironment from '../server/ci-info'\nimport debugOriginal from 'next/dist/compiled/debug'\nimport picomatch from 'next/dist/compiled/picomatch'\nimport { defaultOverrides } from '../server/require-hook'\nimport { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport isError from '../lib/is-error'\nimport type { NodeFileTraceReasons } from '@vercel/nft'\nimport type { RoutesUsingEdgeRuntime } from './utils'\n\nconst debug = debugOriginal('next:build:build-traces')\n\nexport const makeIgnoreFn = (root: string, ignores: string[]) => {\n // pre compile the ignore globs\n const isMatch = picomatch(ignores, {\n contains: true,\n dot: true,\n })\n\n return (pathname: string) => {\n if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {\n return true\n }\n\n return isMatch(pathname)\n }\n}\n\nfunction shouldIgnore(\n file: string,\n serverIgnoreFn: (file: string) => boolean,\n reasons: NodeFileTraceReasons,\n cachedIgnoreFiles: Map<string, boolean>,\n children: Set<string> = new Set()\n) {\n if (cachedIgnoreFiles.has(file)) {\n return cachedIgnoreFiles.get(file)\n }\n\n if (serverIgnoreFn(file)) {\n cachedIgnoreFiles.set(file, true)\n return true\n }\n children.add(file)\n\n const reason = reasons.get(file)\n if (!reason || reason.parents.size === 0 || reason.type.includes('initial')) {\n cachedIgnoreFiles.set(file, false)\n return false\n }\n\n // if all parents are ignored the child file\n // should be ignored as well\n let allParentsIgnored = true\n\n for (const parent of reason.parents.values()) {\n if (!children.has(parent)) {\n children.add(parent)\n if (\n !shouldIgnore(\n parent,\n serverIgnoreFn,\n reasons,\n cachedIgnoreFiles,\n children\n )\n ) {\n allParentsIgnored = false\n break\n }\n }\n }\n\n cachedIgnoreFiles.set(file, allParentsIgnored)\n return allParentsIgnored\n}\n\nexport async function collectBuildTraces({\n dir,\n config,\n distDir,\n edgeRuntimeRoutes,\n staticPages,\n nextBuildSpan = new Span({ name: 'build' }),\n buildTraceContext,\n outputFileTracingRoot,\n}: {\n dir: string\n distDir: string\n staticPages: string[]\n outputFileTracingRoot: string\n // pageInfos is serialized when this function runs in a worker.\n edgeRuntimeRoutes: RoutesUsingEdgeRuntime\n nextBuildSpan?: Span\n config: NextConfigComplete\n buildTraceContext?: BuildTraceContext\n}) {\n const startTime = Date.now()\n debug('starting build traces')\n\n const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } =\n config\n const excludeGlobKeys = Object.keys(outputFileTracingExcludes)\n const includeGlobKeys = Object.keys(outputFileTracingIncludes)\n\n await nextBuildSpan\n .traceChild('node-file-trace-build', {\n isTurbotrace: 'false', // TODO(arlyon): remove this\n })\n .traceAsyncFn(async () => {\n const nextServerTraceOutput = path.join(\n distDir,\n 'next-server.js.nft.json'\n )\n const nextMinimalTraceOutput = path.join(\n distDir,\n 'next-minimal-server.js.nft.json'\n )\n const root = outputFileTracingRoot\n\n // Under standalone mode, we need to trace the extra IPC server and\n // worker files.\n const isStandalone = config.output === 'standalone'\n const sharedEntriesSet = Object.keys(defaultOverrides).map((value) =>\n require.resolve(value, {\n paths: [require.resolve('next/dist/server/require-hook')],\n })\n )\n\n const { cacheHandler, cacheHandlers } = config\n\n // ensure we trace any dependencies needed for custom\n // incremental cache handler\n if (cacheHandler) {\n const resolvedPath = resolveCacheHandlerPathToFilesystem(cacheHandler)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n\n // Under standalone mode, we need to ensure that the cache entry debug\n // handler is traced so it can be copied. This is only used for testing,\n // and is not used in production.\n if (\n process.env.__NEXT_TEST_MODE &&\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n ) {\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS)\n ? process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n : path.join(\n dir,\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n )\n )\n )\n }\n\n if (cacheHandlers) {\n for (const handlerPath of Object.values(cacheHandlers)) {\n if (handlerPath) {\n const resolvedPath =\n resolveCacheHandlerPathToFilesystem(handlerPath)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n }\n }\n\n const serverEntries = [\n ...sharedEntriesSet,\n ...(isStandalone\n ? [\n require.resolve('next/dist/server/lib/start-server'),\n require.resolve('next/dist/server/next'),\n require.resolve('next/dist/server/require-hook'),\n ]\n : []),\n require.resolve('next/dist/server/next-server'),\n ].filter(Boolean) as string[]\n\n const minimalServerEntries = [\n ...sharedEntriesSet,\n require.resolve('next/dist/compiled/next-server/server.runtime.prod'),\n ].filter(Boolean)\n\n const additionalIgnores = new Set<string>()\n\n for (const glob of excludeGlobKeys) {\n if (picomatch(glob)('next-server')) {\n outputFileTracingExcludes[glob].forEach((exclude) => {\n additionalIgnores.add(exclude)\n })\n }\n }\n\n const sharedIgnores = [\n '**/next/dist/compiled/next-server/**/*.dev.js',\n ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']),\n '**/next/dist/compiled/webpack/*',\n '**/node_modules/webpack5/**/*',\n '**/next/dist/server/lib/route-resolver*',\n 'next/dist/compiled/semver/semver/**/*.js',\n\n ...(ciEnvironment.hasNextSupport\n ? [\n // only ignore image-optimizer code when\n // this is being handled outside of next-server\n '**/next/dist/server/image-optimizer.js',\n ]\n : []),\n\n ...(isStandalone ? [] : TRACE_IGNORES),\n ...additionalIgnores,\n ]\n\n const sharedIgnoresFn = makeIgnoreFn(root, sharedIgnores)\n\n const serverIgnores = [\n ...sharedIgnores,\n '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',\n '**/*.d.ts',\n '**/*.map',\n '**/next/dist/pages/**/*',\n ...(ciEnvironment.hasNextSupport\n ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']\n : []),\n ].filter(nonNullable)\n const serverIgnoreFn = makeIgnoreFn(root, serverIgnores)\n\n const minimalServerIgnores = [\n ...serverIgnores,\n '**/next/dist/compiled/edge-runtime/**/*',\n '**/next/dist/server/web/sandbox/**/*',\n '**/next/dist/server/post-process.js',\n ]\n const minimalServerIgnoreFn = makeIgnoreFn(root, minimalServerIgnores)\n\n const routesIgnores = [\n ...sharedIgnores,\n // server chunks are provided via next-trace-entrypoints-plugin plugin\n // as otherwise all chunks are traced here and included for all pages\n // whether they are needed or not\n '**/.next/server/chunks/**',\n '**/next/dist/server/post-process.js',\n ].filter(nonNullable)\n\n const routeIgnoreFn = makeIgnoreFn(root, routesIgnores)\n\n const serverTracedFiles = new Set<string>()\n const minimalServerTracedFiles = new Set<string>()\n\n function addToTracedFiles(base: string, file: string, dest: Set<string>) {\n dest.add(\n path.relative(distDir, path.join(base, file)).replace(/\\\\/g, '/')\n )\n }\n\n if (isStandalone) {\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/processChild'),\n serverTracedFiles\n )\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/threadChild'),\n serverTracedFiles\n )\n }\n\n {\n const chunksToTrace: string[] = [\n ...(buildTraceContext?.chunksTrace?.action.input || []),\n ...serverEntries,\n ...minimalServerEntries,\n ]\n const result = await nodeFileTrace(chunksToTrace, {\n base: outputFileTracingRoot,\n processCwd: dir,\n mixedModules: true,\n moduleSyncCatchall: true,\n async readFile(p) {\n try {\n return await fs.readFile(p, 'utf8')\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'EISDIR')) {\n // since tracing runs in parallel with static generation server\n // files might be removed from that step so tolerate ENOENT\n // errors gracefully\n return ''\n }\n throw e\n }\n },\n async readlink(p) {\n try {\n return await fs.readlink(p)\n } catch (e) {\n if (\n isError(e) &&\n (e.code === 'EINVAL' ||\n e.code === 'ENOENT' ||\n e.code === 'UNKNOWN')\n ) {\n return null\n }\n throw e\n }\n },\n async stat(p) {\n try {\n return await fs.stat(p)\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) {\n return null\n }\n throw e\n }\n },\n // handle shared ignores at top-level as it\n // avoids over-tracing when we don't need to\n // and speeds up total trace time\n ignore(p) {\n if (sharedIgnoresFn(p)) {\n return true\n }\n\n // if a chunk is attempting to be traced that isn't\n // in our initial list we need to ignore it to prevent\n // over tracing as webpack needs to be the source of\n // truth for which chunks should be included for each entry\n if (\n p.includes('.next/server/chunks') &&\n !chunksToTrace.includes(path.join(outputFileTracingRoot, p))\n ) {\n return true\n }\n return false\n },\n })\n const reasons = result.reasons\n const fileList = result.fileList\n for (const file of result.esmFileList) {\n fileList.add(file)\n }\n\n const parentFilesMap = getFilesMapFromReasons(fileList, reasons)\n const cachedLookupIgnore = new Map<string, boolean>()\n const cachedLookupIgnoreMinimal = new Map<string, boolean>()\n\n for (const [entries, tracedFiles] of [\n [serverEntries, serverTracedFiles],\n [minimalServerEntries, minimalServerTracedFiles],\n ] as Array<[string[], Set<string>]>) {\n for (const file of entries) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n tracedFiles.add(path.relative(distDir, file).replace(/\\\\/g, '/'))\n\n for (const curFile of curFiles || []) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n\n if (\n !shouldIgnore(\n curFile,\n tracedFiles === minimalServerTracedFiles\n ? minimalServerIgnoreFn\n : serverIgnoreFn,\n reasons,\n tracedFiles === minimalServerTracedFiles\n ? cachedLookupIgnoreMinimal\n : cachedLookupIgnore\n )\n ) {\n tracedFiles.add(\n path.relative(distDir, filePath).replace(/\\\\/g, '/')\n )\n }\n }\n }\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n const cachedLookupIgnoreRoutes = new Map<string, boolean>()\n\n await Promise.all(\n [\n ...(entryNameFilesMap\n ? Object.entries(entryNameFilesMap)\n : new Map()),\n ].map(async ([entryName, entryNameFiles]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(route.substring('app'.length))\n }\n if (isPages) {\n route = normalizePagePath(route.substring('pages'.length))\n }\n\n // we don't need to trace for automatically statically optimized\n // pages as they don't have server bundles, note there is\n // the caveat with flying shuttle mode as it needs this for\n // detecting changed entries\n if (staticPages.includes(route)) {\n return\n }\n const entryOutputPath = path.join(\n distDir,\n 'server',\n `${entryName}.js`\n )\n const traceOutputPath = `${entryOutputPath}.nft.json`\n const existingTrace = JSON.parse(\n await fs.readFile(traceOutputPath, 'utf8')\n ) as {\n version: number\n files: string[]\n fileHashes: Record<string, string>\n }\n const traceOutputDir = path.dirname(traceOutputPath)\n const curTracedFiles = new Set<string>()\n\n for (const file of [...entryNameFiles, entryOutputPath]) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n for (const curFile of curFiles || []) {\n if (\n !shouldIgnore(\n curFile,\n routeIgnoreFn,\n reasons,\n cachedLookupIgnoreRoutes\n )\n ) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n const outputFile = path\n .relative(traceOutputDir, filePath)\n .replace(/\\\\/g, '/')\n curTracedFiles.add(outputFile)\n }\n }\n }\n\n for (const file of existingTrace.files || []) {\n curTracedFiles.add(file)\n }\n\n await fs.writeFile(\n traceOutputPath,\n JSON.stringify({\n ...existingTrace,\n files: [...curTracedFiles].sort(),\n })\n )\n })\n )\n }\n\n const moduleTypes = ['app-page', 'pages']\n\n for (const type of moduleTypes) {\n const modulePath = require.resolve(\n `next/dist/server/route-modules/${type}/module.compiled`\n )\n const relativeModulePath = path.relative(root, modulePath)\n\n const contextDir = path.join(\n path.dirname(modulePath),\n 'vendored',\n 'contexts'\n )\n\n for (const item of await fs.readdir(contextDir)) {\n const itemPath = path.relative(root, path.join(contextDir, item))\n if (!serverIgnoreFn(itemPath)) {\n addToTracedFiles(root, itemPath, serverTracedFiles)\n addToTracedFiles(root, itemPath, minimalServerTracedFiles)\n }\n }\n addToTracedFiles(root, relativeModulePath, serverTracedFiles)\n addToTracedFiles(root, relativeModulePath, minimalServerTracedFiles)\n }\n\n const serverTracedFilesSorted = Array.from(serverTracedFiles)\n serverTracedFilesSorted.sort()\n const minimalServerTracedFilesSorted = Array.from(\n minimalServerTracedFiles\n )\n minimalServerTracedFilesSorted.sort()\n\n await Promise.all([\n fs.writeFile(\n nextServerTraceOutput,\n JSON.stringify({\n version: 1,\n files: serverTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n fs.writeFile(\n nextMinimalTraceOutput,\n JSON.stringify({\n version: 1,\n files: minimalServerTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n ])\n })\n\n // apply outputFileTracingIncludes/outputFileTracingExcludes after runTurbotrace\n const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes')\n await includeExcludeSpan.traceAsyncFn(async () => {\n const globOrig =\n require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')\n const glob = (pattern: string): Promise<string[]> => {\n return new Promise((resolve, reject) => {\n globOrig(\n pattern,\n { cwd: dir, nodir: true, dot: true },\n (err, files) => {\n if (err) {\n return reject(err)\n }\n resolve(files)\n }\n )\n })\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n await Promise.all(\n [\n ...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),\n ].map(async ([entryName]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(entryName)\n }\n if (isPages) {\n route = normalizePagePath(entryName)\n }\n\n if (staticPages.includes(route)) {\n return\n }\n\n // edge routes have no trace files\n if (edgeRuntimeRoutes.hasOwnProperty(route)) {\n return\n }\n\n const combinedIncludes = new Set<string>()\n const combinedExcludes = new Set<string>()\n for (const curGlob of includeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const include of outputFileTracingIncludes[curGlob]) {\n combinedIncludes.add(include.replace(/\\\\/g, '/'))\n }\n }\n }\n\n for (const curGlob of excludeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const exclude of outputFileTracingExcludes[curGlob]) {\n combinedExcludes.add(exclude)\n }\n }\n }\n\n if (!combinedIncludes?.size && !combinedExcludes?.size) {\n return\n }\n\n const traceFile = path.join(\n distDir,\n `server`,\n `${entryName}.js.nft.json`\n )\n const pageDir = path.dirname(traceFile)\n const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8'))\n const includes: string[] = []\n const resolvedTraceIncludes = new Map<string, string[]>()\n\n if (combinedIncludes?.size) {\n await Promise.all(\n [...combinedIncludes].map(async (includeGlob) => {\n const results = await glob(includeGlob)\n const resolvedInclude = resolvedTraceIncludes.get(\n includeGlob\n ) || [\n ...results.map((file) => {\n return path.relative(pageDir, path.join(dir, file))\n }),\n ]\n includes.push(...resolvedInclude)\n resolvedTraceIncludes.set(includeGlob, resolvedInclude)\n })\n )\n }\n const combined = new Set([...traceContent.files, ...includes])\n\n if (combinedExcludes?.size) {\n const resolvedGlobs = [...combinedExcludes].map((exclude) =>\n path.join(dir, exclude)\n )\n\n // pre compile before forEach\n const isMatch = picomatch(resolvedGlobs, {\n dot: true,\n contains: true,\n })\n\n combined.forEach((file) => {\n if (isMatch(path.join(pageDir, file))) {\n combined.delete(file)\n }\n })\n }\n\n // overwrite trace file with custom includes/excludes\n await fs.writeFile(\n traceFile,\n JSON.stringify({\n version: traceContent.version,\n files: [...combined],\n })\n )\n })\n )\n })\n\n debug(`finished build tracing ${Date.now() - startTime}ms`)\n}\n"],"names":["Span","TRACE_IGNORES","getFilesMapFromReasons","path","resolveCacheHandlerPathToFilesystem","fs","nonNullable","ciEnvironment","debugOriginal","picomatch","defaultOverrides","nodeFileTrace","normalizePagePath","normalizeAppPath","isError","debug","makeIgnoreFn","root","ignores","isMatch","contains","dot","pathname","isAbsolute","startsWith","shouldIgnore","file","serverIgnoreFn","reasons","cachedIgnoreFiles","children","Set","has","get","set","add","reason","parents","size","type","includes","allParentsIgnored","parent","values","collectBuildTraces","dir","config","distDir","edgeRuntimeRoutes","staticPages","nextBuildSpan","name","buildTraceContext","outputFileTracingRoot","startTime","Date","now","outputFileTracingIncludes","outputFileTracingExcludes","excludeGlobKeys","Object","keys","includeGlobKeys","traceChild","isTurbotrace","traceAsyncFn","nextServerTraceOutput","join","nextMinimalTraceOutput","isStandalone","output","sharedEntriesSet","map","value","require","resolve","paths","cacheHandler","cacheHandlers","resolvedPath","push","process","env","__NEXT_TEST_MODE","NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS","handlerPath","serverEntries","filter","Boolean","minimalServerEntries","additionalIgnores","glob","forEach","exclude","sharedIgnores","hasNextSupport","sharedIgnoresFn","serverIgnores","minimalServerIgnores","minimalServerIgnoreFn","routesIgnores","routeIgnoreFn","serverTracedFiles","minimalServerTracedFiles","addToTracedFiles","base","dest","relative","replace","chunksToTrace","chunksTrace","action","input","result","processCwd","mixedModules","moduleSyncCatchall","readFile","p","e","code","readlink","stat","ignore","fileList","esmFileList","parentFilesMap","cachedLookupIgnore","Map","cachedLookupIgnoreMinimal","entries","tracedFiles","curFiles","curFile","filePath","entryNameFilesMap","cachedLookupIgnoreRoutes","Promise","all","entryName","entryNameFiles","isApp","isPages","route","substring","length","entryOutputPath","traceOutputPath","existingTrace","JSON","parse","traceOutputDir","dirname","curTracedFiles","outputFile","files","writeFile","stringify","sort","moduleTypes","modulePath","relativeModulePath","contextDir","item","readdir","itemPath","serverTracedFilesSorted","Array","from","minimalServerTracedFilesSorted","version","includeExcludeSpan","globOrig","pattern","reject","cwd","nodir","err","hasOwnProperty","combinedIncludes","combinedExcludes","curGlob","include","traceFile","pageDir","traceContent","resolvedTraceIncludes","includeGlob","results","resolvedInclude","combined","resolvedGlobs","delete"],"mappings":"AAAA,yDAAyD;AACzD,OAAO,4BAA2B;AAClC,SAASA,IAAI,QAAQ,WAAU;AAG/B,SACEC,aAAa,EAEbC,sBAAsB,QACjB,kDAAiD;AAExD,OAAOC,UAAU,OAAM;AACvB,SAASC,mCAAmC,QAAQ,oCAAmC;AACvF,OAAOC,QAAQ,cAAa;AAC5B,SAASC,WAAW,QAAQ,sBAAqB;AACjD,YAAYC,mBAAmB,oBAAmB;AAClD,OAAOC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AUsL,eAAe;oBACvC1K,KAAK;oBACLD,UAAU;gBACZ;gBAEA0K,SAASlG,OAAO,CAAC,CAAClE;oBAChB,IAAIP,QAAQhB,KAAKgE,IAAI,CAACqH,SAAS9J,QAAQ;wBACrCoK,SAASE,MAAM,CAACtK;oBAClB;gBACF;YACF;YAEA,qDAAqD;YACrD,MAAMrB,GAAGuJ,SAAS,CAChB2B,WACAlC,KAAKQ,SAAS,CAAC;gBACba,SAASe,aAAaf,OAAO;gBAC7Bf,OAAO;uBAAImC;iBAAS;YACtB;QAEJ;IAEJ;IAEA/K,MAAM,CAAC,uBAAuB,EAAEwC,KAAKC,GAAG,KAAKF,UAAU,EAAE,CAAC;AAC5D","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/build/collect-build-traces.ts"],"sourcesContent":["// Import cpu-profile to start profiling early if enabled\nimport '../server/lib/cpu-profile'\nimport { Span } from '../trace'\nimport type { NextConfigComplete } from '../server/config-shared'\n\nimport {\n TRACE_IGNORES,\n type BuildTraceContext,\n getFilesMapFromReasons,\n} from './webpack/plugins/next-trace-entrypoints-plugin'\n\nimport path from 'path'\nimport { resolveCacheHandlerPathToFilesystem } from '../lib/format-dynamic-import-path'\nimport fs from 'fs/promises'\nimport { nonNullable } from '../lib/non-nullable'\nimport * as ciEnvironment from '../server/ci-info'\nimport debugOriginal from 'next/dist/compiled/debug'\nimport picomatch from 'next/dist/compiled/picomatch'\nimport { defaultOverrides } from '../server/require-hook'\nimport { nodeFileTrace } from 'next/dist/compiled/@vercel/nft'\nimport { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'\nimport { normalizeAppPath } from '../shared/lib/router/utils/app-paths'\nimport isError from '../lib/is-error'\nimport type { NodeFileTraceReasons } from '@vercel/nft'\nimport type { RoutesUsingEdgeRuntime } from './utils'\n\nconst debug = debugOriginal('next:build:build-traces')\n\nexport const makeIgnoreFn = (root: string, ignores: string[]) => {\n // pre compile the ignore globs\n const isMatch = picomatch(ignores, {\n contains: true,\n dot: true,\n })\n\n return (pathname: string) => {\n if (path.isAbsolute(pathname) && !pathname.startsWith(root)) {\n return true\n }\n\n return isMatch(pathname)\n }\n}\n\nfunction shouldIgnore(\n file: string,\n serverIgnoreFn: (file: string) => boolean,\n reasons: NodeFileTraceReasons,\n cachedIgnoreFiles: Map<string, boolean>,\n children: Set<string> = new Set()\n) {\n if (cachedIgnoreFiles.has(file)) {\n return cachedIgnoreFiles.get(file)\n }\n\n if (serverIgnoreFn(file)) {\n cachedIgnoreFiles.set(file, true)\n return true\n }\n children.add(file)\n\n const reason = reasons.get(file)\n if (!reason || reason.parents.size === 0 || reason.type.includes('initial')) {\n cachedIgnoreFiles.set(file, false)\n return false\n }\n\n // if all parents are ignored the child file\n // should be ignored as well\n let allParentsIgnored = true\n\n for (const parent of reason.parents.values()) {\n if (!children.has(parent)) {\n children.add(parent)\n if (\n !shouldIgnore(\n parent,\n serverIgnoreFn,\n reasons,\n cachedIgnoreFiles,\n children\n )\n ) {\n allParentsIgnored = false\n break\n }\n }\n }\n\n cachedIgnoreFiles.set(file, allParentsIgnored)\n return allParentsIgnored\n}\n\nexport async function collectBuildTraces({\n dir,\n config,\n distDir,\n edgeRuntimeRoutes,\n staticPages,\n nextBuildSpan = new Span({ name: 'build' }),\n buildTraceContext,\n outputFileTracingRoot,\n}: {\n dir: string\n distDir: string\n staticPages: string[]\n outputFileTracingRoot: string\n // pageInfos is serialized when this function runs in a worker.\n edgeRuntimeRoutes: RoutesUsingEdgeRuntime\n nextBuildSpan?: Span\n config: NextConfigComplete\n buildTraceContext?: BuildTraceContext\n}) {\n const startTime = Date.now()\n debug('starting build traces')\n\n const { outputFileTracingIncludes = {}, outputFileTracingExcludes = {} } =\n config\n const excludeGlobKeys = Object.keys(outputFileTracingExcludes)\n const includeGlobKeys = Object.keys(outputFileTracingIncludes)\n\n await nextBuildSpan\n .traceChild('node-file-trace-build', {\n isTurbotrace: 'false', // TODO(arlyon): remove this\n })\n .traceAsyncFn(async () => {\n const nextServerTraceOutput = path.join(\n distDir,\n 'next-server.js.nft.json'\n )\n const nextMinimalTraceOutput = path.join(\n distDir,\n 'next-minimal-server.js.nft.json'\n )\n const root = outputFileTracingRoot\n\n // Under standalone mode, we need to trace the extra IPC server and\n // worker files.\n const isStandalone = config.output === 'standalone'\n const sharedEntriesSet = Object.keys(defaultOverrides).map((value) =>\n require.resolve(value, {\n paths: [require.resolve('next/dist/server/require-hook')],\n })\n )\n\n const { cacheHandler, cacheHandlers } = config\n\n // ensure we trace any dependencies needed for custom\n // incremental cache handler\n if (cacheHandler) {\n const resolvedPath = resolveCacheHandlerPathToFilesystem(cacheHandler)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n\n // Under standalone mode, we need to ensure that the cache entry debug\n // handler is traced so it can be copied. This is only used for testing,\n // and is not used in production.\n if (\n process.env.__NEXT_TEST_MODE &&\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n ) {\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS)\n ? process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n : path.join(\n dir,\n process.env.NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS\n )\n )\n )\n }\n\n if (cacheHandlers) {\n for (const handlerPath of Object.values(cacheHandlers)) {\n if (handlerPath) {\n const resolvedPath =\n resolveCacheHandlerPathToFilesystem(handlerPath)\n sharedEntriesSet.push(\n require.resolve(\n path.isAbsolute(resolvedPath)\n ? resolvedPath\n : path.join(dir, resolvedPath)\n )\n )\n }\n }\n }\n\n const serverEntries = [\n ...sharedEntriesSet,\n ...(isStandalone\n ? [\n require.resolve('next/dist/server/lib/start-server'),\n require.resolve('next/dist/server/next'),\n require.resolve('next/dist/server/require-hook'),\n ]\n : []),\n require.resolve('next/dist/server/next-server'),\n ].filter(Boolean) as string[]\n\n const minimalServerEntries = [\n ...sharedEntriesSet,\n require.resolve('next/dist/compiled/next-server/server.runtime.prod'),\n ].filter(Boolean)\n\n const additionalIgnores = new Set<string>()\n\n for (const glob of excludeGlobKeys) {\n if (picomatch(glob)('next-server')) {\n outputFileTracingExcludes[glob].forEach((exclude) => {\n additionalIgnores.add(exclude)\n })\n }\n }\n\n const sharedIgnores = [\n '**/next/dist/compiled/next-server/**/*.dev.js',\n ...(isStandalone ? [] : ['**/next/dist/compiled/jest-worker/**/*']),\n '**/next/dist/compiled/webpack/*',\n '**/node_modules/webpack5/**/*',\n '**/next/dist/server/lib/route-resolver*',\n // The testmode interceptors bundle reads its HTTP parser WASM with a\n // dynamic path, making nft trace the bundle's whole directory. Test\n // proxying is not supported in standalone output, so keep the parser\n // asset (and the license file picked up by the directory glob) out of\n // production traces.\n '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/LICENSE',\n '**/next/dist/compiled/@mswjs/interceptors/ClientRequest/llhttp/**/*',\n 'next/dist/compiled/semver/semver/**/*.js',\n\n ...(ciEnvironment.hasNextSupport\n ? [\n // only ignore image-optimizer code when\n // this is being handled outside of next-server\n '**/next/dist/server/image-optimizer.js',\n ]\n : []),\n\n ...(isStandalone ? [] : TRACE_IGNORES),\n ...additionalIgnores,\n ]\n\n const sharedIgnoresFn = makeIgnoreFn(root, sharedIgnores)\n\n const serverIgnores = [\n ...sharedIgnores,\n '**/node_modules/react{,-dom,-dom-server-turbopack}/**/*.development.js',\n '**/*.d.ts',\n '**/*.map',\n '**/next/dist/pages/**/*',\n ...(ciEnvironment.hasNextSupport\n ? ['**/node_modules/sharp/**/*', '**/@img/sharp-libvips*/**/*']\n : []),\n ].filter(nonNullable)\n const serverIgnoreFn = makeIgnoreFn(root, serverIgnores)\n\n const minimalServerIgnores = [\n ...serverIgnores,\n '**/next/dist/compiled/edge-runtime/**/*',\n '**/next/dist/server/web/sandbox/**/*',\n '**/next/dist/server/post-process.js',\n ]\n const minimalServerIgnoreFn = makeIgnoreFn(root, minimalServerIgnores)\n\n const routesIgnores = [\n ...sharedIgnores,\n // server chunks are provided via next-trace-entrypoints-plugin plugin\n // as otherwise all chunks are traced here and included for all pages\n // whether they are needed or not\n '**/.next/server/chunks/**',\n '**/next/dist/server/post-process.js',\n ].filter(nonNullable)\n\n const routeIgnoreFn = makeIgnoreFn(root, routesIgnores)\n\n const serverTracedFiles = new Set<string>()\n const minimalServerTracedFiles = new Set<string>()\n\n function addToTracedFiles(base: string, file: string, dest: Set<string>) {\n dest.add(\n path.relative(distDir, path.join(base, file)).replace(/\\\\/g, '/')\n )\n }\n\n if (isStandalone) {\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/processChild'),\n serverTracedFiles\n )\n addToTracedFiles(\n '',\n require.resolve('next/dist/compiled/jest-worker/threadChild'),\n serverTracedFiles\n )\n }\n\n {\n const chunksToTrace: string[] = [\n ...(buildTraceContext?.chunksTrace?.action.input || []),\n ...serverEntries,\n ...minimalServerEntries,\n ]\n const result = await nodeFileTrace(chunksToTrace, {\n base: outputFileTracingRoot,\n processCwd: dir,\n mixedModules: true,\n moduleSyncCatchall: true,\n async readFile(p) {\n try {\n return await fs.readFile(p, 'utf8')\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'EISDIR')) {\n // since tracing runs in parallel with static generation server\n // files might be removed from that step so tolerate ENOENT\n // errors gracefully\n return ''\n }\n throw e\n }\n },\n async readlink(p) {\n try {\n return await fs.readlink(p)\n } catch (e) {\n if (\n isError(e) &&\n (e.code === 'EINVAL' ||\n e.code === 'ENOENT' ||\n e.code === 'UNKNOWN')\n ) {\n return null\n }\n throw e\n }\n },\n async stat(p) {\n try {\n return await fs.stat(p)\n } catch (e) {\n if (isError(e) && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) {\n return null\n }\n throw e\n }\n },\n // handle shared ignores at top-level as it\n // avoids over-tracing when we don't need to\n // and speeds up total trace time\n ignore(p) {\n if (sharedIgnoresFn(p)) {\n return true\n }\n\n // if a chunk is attempting to be traced that isn't\n // in our initial list we need to ignore it to prevent\n // over tracing as webpack needs to be the source of\n // truth for which chunks should be included for each entry\n if (\n p.includes('.next/server/chunks') &&\n !chunksToTrace.includes(path.join(outputFileTracingRoot, p))\n ) {\n return true\n }\n return false\n },\n })\n const reasons = result.reasons\n const fileList = result.fileList\n for (const file of result.esmFileList) {\n fileList.add(file)\n }\n\n const parentFilesMap = getFilesMapFromReasons(fileList, reasons)\n const cachedLookupIgnore = new Map<string, boolean>()\n const cachedLookupIgnoreMinimal = new Map<string, boolean>()\n\n for (const [entries, tracedFiles] of [\n [serverEntries, serverTracedFiles],\n [minimalServerEntries, minimalServerTracedFiles],\n ] as Array<[string[], Set<string>]>) {\n for (const file of entries) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n tracedFiles.add(path.relative(distDir, file).replace(/\\\\/g, '/'))\n\n for (const curFile of curFiles || []) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n\n if (\n !shouldIgnore(\n curFile,\n tracedFiles === minimalServerTracedFiles\n ? minimalServerIgnoreFn\n : serverIgnoreFn,\n reasons,\n tracedFiles === minimalServerTracedFiles\n ? cachedLookupIgnoreMinimal\n : cachedLookupIgnore\n )\n ) {\n tracedFiles.add(\n path.relative(distDir, filePath).replace(/\\\\/g, '/')\n )\n }\n }\n }\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n const cachedLookupIgnoreRoutes = new Map<string, boolean>()\n\n await Promise.all(\n [\n ...(entryNameFilesMap\n ? Object.entries(entryNameFilesMap)\n : new Map()),\n ].map(async ([entryName, entryNameFiles]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(route.substring('app'.length))\n }\n if (isPages) {\n route = normalizePagePath(route.substring('pages'.length))\n }\n\n // we don't need to trace for automatically statically optimized\n // pages as they don't have server bundles, note there is\n // the caveat with flying shuttle mode as it needs this for\n // detecting changed entries\n if (staticPages.includes(route)) {\n return\n }\n const entryOutputPath = path.join(\n distDir,\n 'server',\n `${entryName}.js`\n )\n const traceOutputPath = `${entryOutputPath}.nft.json`\n const existingTrace = JSON.parse(\n await fs.readFile(traceOutputPath, 'utf8')\n ) as {\n version: number\n files: string[]\n fileHashes: Record<string, string>\n }\n const traceOutputDir = path.dirname(traceOutputPath)\n const curTracedFiles = new Set<string>()\n\n for (const file of [...entryNameFiles, entryOutputPath]) {\n const curFiles = [\n ...(parentFilesMap\n .get(path.relative(outputFileTracingRoot, file))\n ?.keys() || []),\n ]\n for (const curFile of curFiles || []) {\n if (\n !shouldIgnore(\n curFile,\n routeIgnoreFn,\n reasons,\n cachedLookupIgnoreRoutes\n )\n ) {\n const filePath = path.join(outputFileTracingRoot, curFile)\n const outputFile = path\n .relative(traceOutputDir, filePath)\n .replace(/\\\\/g, '/')\n curTracedFiles.add(outputFile)\n }\n }\n }\n\n for (const file of existingTrace.files || []) {\n curTracedFiles.add(file)\n }\n\n await fs.writeFile(\n traceOutputPath,\n JSON.stringify({\n ...existingTrace,\n files: [...curTracedFiles].sort(),\n })\n )\n })\n )\n }\n\n const moduleTypes = ['app-page', 'pages']\n\n for (const type of moduleTypes) {\n const modulePath = require.resolve(\n `next/dist/server/route-modules/${type}/module.compiled`\n )\n const relativeModulePath = path.relative(root, modulePath)\n\n const contextDir = path.join(\n path.dirname(modulePath),\n 'vendored',\n 'contexts'\n )\n\n for (const item of await fs.readdir(contextDir)) {\n const itemPath = path.relative(root, path.join(contextDir, item))\n if (!serverIgnoreFn(itemPath)) {\n addToTracedFiles(root, itemPath, serverTracedFiles)\n addToTracedFiles(root, itemPath, minimalServerTracedFiles)\n }\n }\n addToTracedFiles(root, relativeModulePath, serverTracedFiles)\n addToTracedFiles(root, relativeModulePath, minimalServerTracedFiles)\n }\n\n const serverTracedFilesSorted = Array.from(serverTracedFiles)\n serverTracedFilesSorted.sort()\n const minimalServerTracedFilesSorted = Array.from(\n minimalServerTracedFiles\n )\n minimalServerTracedFilesSorted.sort()\n\n await Promise.all([\n fs.writeFile(\n nextServerTraceOutput,\n JSON.stringify({\n version: 1,\n files: serverTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n fs.writeFile(\n nextMinimalTraceOutput,\n JSON.stringify({\n version: 1,\n files: minimalServerTracedFilesSorted,\n } as {\n version: number\n files: string[]\n })\n ),\n ])\n })\n\n // apply outputFileTracingIncludes/outputFileTracingExcludes after runTurbotrace\n const includeExcludeSpan = nextBuildSpan.traceChild('apply-include-excludes')\n await includeExcludeSpan.traceAsyncFn(async () => {\n const globOrig =\n require('next/dist/compiled/glob') as typeof import('next/dist/compiled/glob')\n const glob = (pattern: string): Promise<string[]> => {\n return new Promise((resolve, reject) => {\n globOrig(\n pattern,\n { cwd: dir, nodir: true, dot: true },\n (err, files) => {\n if (err) {\n return reject(err)\n }\n resolve(files)\n }\n )\n })\n }\n\n const { entryNameFilesMap } = buildTraceContext?.chunksTrace || {}\n\n await Promise.all(\n [\n ...(entryNameFilesMap ? Object.entries(entryNameFilesMap) : new Map()),\n ].map(async ([entryName]) => {\n const isApp = entryName.startsWith('app/')\n const isPages = entryName.startsWith('pages/')\n let route = entryName\n if (isApp) {\n route = normalizeAppPath(entryName)\n }\n if (isPages) {\n route = normalizePagePath(entryName)\n }\n\n if (staticPages.includes(route)) {\n return\n }\n\n // edge routes have no trace files\n if (edgeRuntimeRoutes.hasOwnProperty(route)) {\n return\n }\n\n const combinedIncludes = new Set<string>()\n const combinedExcludes = new Set<string>()\n for (const curGlob of includeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const include of outputFileTracingIncludes[curGlob]) {\n combinedIncludes.add(include.replace(/\\\\/g, '/'))\n }\n }\n }\n\n for (const curGlob of excludeGlobKeys) {\n const isMatch = picomatch(curGlob, { dot: true, contains: true })\n if (isMatch(route)) {\n for (const exclude of outputFileTracingExcludes[curGlob]) {\n combinedExcludes.add(exclude)\n }\n }\n }\n\n if (!combinedIncludes?.size && !combinedExcludes?.size) {\n return\n }\n\n const traceFile = path.join(\n distDir,\n `server`,\n `${entryName}.js.nft.json`\n )\n const pageDir = path.dirname(traceFile)\n const traceContent = JSON.parse(await fs.readFile(traceFile, 'utf8'))\n const includes: string[] = []\n const resolvedTraceIncludes = new Map<string, string[]>()\n\n if (combinedIncludes?.size) {\n await Promise.all(\n [...combinedIncludes].map(async (includeGlob) => {\n const results = await glob(includeGlob)\n const resolvedInclude = resolvedTraceIncludes.get(\n includeGlob\n ) || [\n ...results.map((file) => {\n return path.relative(pageDir, path.join(dir, file))\n }),\n ]\n includes.push(...resolvedInclude)\n resolvedTraceIncludes.set(includeGlob, resolvedInclude)\n })\n )\n }\n const combined = new Set([...traceContent.files, ...includes])\n\n if (combinedExcludes?.size) {\n const resolvedGlobs = [...combinedExcludes].map((exclude) =>\n path.join(dir, exclude)\n )\n\n // pre compile before forEach\n const isMatch = picomatch(resolvedGlobs, {\n dot: true,\n contains: true,\n })\n\n combined.forEach((file) => {\n if (isMatch(path.join(pageDir, file))) {\n combined.delete(file)\n }\n })\n }\n\n // overwrite trace file with custom includes/excludes\n await fs.writeFile(\n traceFile,\n JSON.stringify({\n version: traceContent.version,\n files: [...combined],\n })\n )\n })\n )\n })\n\n debug(`finished build tracing ${Date.now() - startTime}ms`)\n}\n"],"names":["Span","TRACE_IGNORES","getFilesMapFromReasons","path","resolveCacheHandlerPathToFilesystem","fs","nonNullable","ciEnvironment","debugOriginal","picomatch","defaultOverrides","nodeFileTrace","normalizePagePath","normalizeAppPath","isError","debug","makeIgnoreFn","root","ignores","isMatch","contains","dot","pathname","isAbsolute","startsWith","shouldIgnore","file","serverIgnoreFn","reasons","cachedIgnoreFiles","children","Set","has","get","set","add","reason","parents","size","type","includes","allParentsIgnored","parent","values","collectBuildTraces","dir","config","distDir","edgeRuntimeRoutes","staticPages","nextBuildSpan","name","buildTraceContext","outputFileTracingRoot","startTime","Date","now","outputFileTracingIncludes","outputFileTracingExcludes","excludeGlobKeys","Object","keys","includeGlobKeys","traceChild","isTurbotrace","traceAsyncFn","nextServerTraceOutput","join","nextMinimalTraceOutput","isStandalone","output","sharedEntriesSet","map","value","require","resolve","paths","cacheHandler","cacheHandlers","resolvedPath","push","process","env","__NEXT_TEST_MODE","NEXT_PRIVATE_DEBUG_CACHE_ENTRY_HANDLERS","handlerPath","serverEntries","filter","Boolean","minimalServerEntries","additionalIgnores","glob","forEach","exclude","sharedIgnores","hasNextSupport","sharedIgnoresFn","serverIgnores","minimalServerIgnores","minimalServerIgnoreFn","routesIgnores","routeIgnoreFn","serverTracedFiles","minimalServerTracedFiles","addToTracedFiles","base","dest","relative","replace","chunksToTrace","chunksTrace","action","input","result","processCwd","mixedModules","moduleSyncCatchall","readFile","p","e","code","readlink","stat","ignore","fileList","esmFileList","parentFilesMap","cachedLookupIgnore","Map","cachedLookupIgnoreMinimal","entries","tracedFiles","curFiles","curFile","filePath","entryNameFilesMap","cachedLookupIgnoreRoutes","Promise","all","entryName","entryNameFiles","isApp","isPages","route","substring","length","entryOutputPath","traceOutputPath","existingTrace","JSON","parse","traceOutputDir","dirname","curTracedFiles","outputFile","files","writeFile","stringify","sort","moduleTypes","modulePath","relativeModulePath","contextDir","item","readdir","itemPath","serverTracedFilesSorted","Array","from","minimalServerTracedFilesSorted","version","includeExcludeSpan","globOrig","pattern","reject","cwd","nodir","err","hasOwnProperty","combinedIncludes","combinedExcludes","curGlob","include","traceFile","pageDir","traceContent","resolvedTraceIncludes","includeGlob","results","resolvedInclude","combined","resolvedGlobs","delete"],"mappings":"AAAA,yDAAyD;AACzD,OAAO,4BAA2B;AAClC,SAASA,IAAI,QAAQ,WAAU;AAG/B,SACEC,aAAa,EAEbC,sBAAsB,QACjB,kDAAiD;AAExD,OAAOC,UAAU,OAAM;AACvB,SAASC,mCAAmC,QAAQ,oCAAmC;AACvF,OAAOC,QAAQ,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AAI,EAAE;gBAC1B,MAAMyJ,gBAAgB;uBAAIX;iBAAiB,CAAC5G,GAAG,CAAC,CAACqB,UAC/C1F,KAAKgE,IAAI,CAACtB,KAAKgD;gBAGjB,6BAA6B;gBAC7B,MAAM1E,UAAUV,UAAUsL,eAAe;oBACvC1K,KAAK;oBACLD,UAAU;gBACZ;gBAEA0K,SAASlG,OAAO,CAAC,CAAClE;oBAChB,IAAIP,QAAQhB,KAAKgE,IAAI,CAACqH,SAAS9J,QAAQ;wBACrCoK,SAASE,MAAM,CAACtK;oBAClB;gBACF;YACF;YAEA,qDAAqD;YACrD,MAAMrB,GAAGuJ,SAAS,CAChB2B,WACAlC,KAAKQ,SAAS,CAAC;gBACba,SAASe,aAAaf,OAAO;gBAC7Bf,OAAO;uBAAImC;iBAAS;YACtB;QAEJ;IAEJ;IAEA/K,MAAM,CAAC,uBAAuB,EAAEwC,KAAKC,GAAG,KAAKF,UAAU,EAAE,CAAC;AAC5D","ignoreList":[0]} |
@@ -14,3 +14,3 @@ import path from 'path'; | ||
| }({}); | ||
| const nextVersion = "16.3.0-canary.97"; | ||
| const nextVersion = "16.3.0-canary.99"; | ||
| const ArchName = arch(); | ||
@@ -17,0 +17,0 @@ const PlatformName = platform(); |
@@ -69,3 +69,3 @@ import path from 'path'; | ||
| isPersistentCachingEnabled: persistentCaching, | ||
| nextVersion: "16.3.0-canary.97" | ||
| nextVersion: "16.3.0-canary.99" | ||
| }, { | ||
@@ -72,0 +72,0 @@ turbopackMemoryEviction: config.experimental.turbopackMemoryEvictionMode, |
@@ -87,3 +87,3 @@ // Import cpu-profile first to start profiling early if enabled | ||
| deferredEntries: config.experimental.deferredEntries, | ||
| nextVersion: "16.3.0-canary.97" | ||
| nextVersion: "16.3.0-canary.99" | ||
| }; | ||
@@ -90,0 +90,0 @@ const sharedTurboOptions = { |
@@ -8,3 +8,3 @@ /** | ||
| import { setAttributesFromProps } from './set-attributes-from-props'; | ||
| const version = "16.3.0-canary.97"; | ||
| const version = "16.3.0-canary.99"; | ||
| window.next = { | ||
@@ -11,0 +11,0 @@ version, |
@@ -5,3 +5,3 @@ import { createHrefFromUrl } from './create-href-from-url'; | ||
| import { createInitialCacheNodeForHydration } from './ppr-navigations'; | ||
| import { convertRootFlightRouterStateToRouteTree, getStaleAt, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache, writePrerenderResponseIntoCache } from '../segment-cache/cache'; | ||
| import { convertRootFlightRouterStateToRouteTree, resolveStaleAt, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache, writePrerenderResponseIntoCache } from '../segment-cache/cache'; | ||
| import { FetchStrategy } from '../segment-cache/types'; | ||
@@ -61,3 +61,3 @@ import { UnknownDynamicStaleTime, computeDynamicStaleAt } from '../segment-cache/bfcache'; | ||
| const now = Date.now(); | ||
| const staleAt = await getStaleAt(now, staticStageResponse.s); | ||
| const staleAt = await resolveStaleAt(now, staticStageResponse.s); | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, staticStageResponse.f, undefined, staticStageResponse.h, staticStageResponse.r ?? null, staleAt, initialTree, initialRenderedSearch, true // isResponsePartial | ||
@@ -76,3 +76,3 @@ ); | ||
| const now = Date.now(); | ||
| getStaleAt(now, initialStaleTime).then((staleAt)=>{ | ||
| resolveStaleAt(now, initialStaleTime).then((staleAt)=>{ | ||
| writePrerenderResponseIntoCache(now, FetchStrategy.PPR, initialFlightData, undefined, initialHeadVaryParams, initialRootVaryParams ?? null, staleAt, initialTree, initialRenderedSearch, false // isResponsePartial | ||
@@ -79,0 +79,0 @@ ); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { getFlightDataPartsFromPath } from '../../flight-data-helpers'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n convertRootFlightRouterStateToRouteTree,\n getStaleAt,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n f: initialFlightData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n h: initialHeadVaryParams,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const normalizedFlightData = getFlightDataPartsFromPath(initialFlightData[0])\n const {\n tree: initialTree,\n seedData: initialSeedData,\n head: initialHead,\n } = normalizedFlightData\n // For the SSR render, seed data should always be available (we only send back a `null` response\n // in the case of a `loading` segment, pre-PPR.)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Convert the initial FlightRouterState into the RouteTree type.\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the FlightRouterState\n // baked into the initial RSC payload won't have the correct segment inlining\n // hints because those are computed after the pre-render. The server marks\n // these trees with InliningHintsStale, which causes the route cache entry\n // to be immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = convertRootFlightRouterStateToRouteTree(\n initialTree,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialSeedData,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialSeedData !== null && initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await getStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n getStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialFlightData,\n undefined, // buildId — not applicable for initial HTML\n initialHeadVaryParams,\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","getFlightDataPartsFromPath","createInitialCacheNodeForHydration","convertRootFlightRouterStateToRouteTree","getStaleAt","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","FetchStrategy","UnknownDynamicStaleTime","computeDynamicStaleAt","decodeStageUntilBoundary","discoverKnownRoute","createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","f","initialFlightData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","h","initialHeadVaryParams","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","normalizedFlightData","tree","initialTree","seedData","initialSeedData","head","initialHead","canonicalUrl","acc","metadataVaryPath","initialRouteTree","initialTask","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","staleAt","PPR","catch","cancel","processed","PPRRuntime","flightDatas","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","previousNextUrl","debugInfo"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gCAAgC,QAAQ,yBAAwB;AAGzE,SAASC,0BAA0B,QAAQ,4BAA2B;AACtE,SAASC,kCAAkC,QAAQ,oBAAmB;AACtE,SACEC,uCAAuC,EACvCC,UAAU,EACVC,4BAA4B,EAC5BC,mCAAmC,EACnCC,+BAA+B,QAC1B,yBAAwB;AAC/B,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SACEC,uBAAuB,EACvBC,qBAAqB,QAChB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,0BAAyB;AAClE,SAASC,kBAAkB,QAAQ,qCAAoC;AAUvE,OAAO,SAASC,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,iBAAiB,EACpBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGxB;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OAAO,EACjBI,UAAUO,cAAc,EACxB;gBAEJ;YACF,GACCT,KAAK,CAAC;YACL,qEAAqE;YACrE,8CAA8C;YAChD;QACJ;IACF;IAEA,8EAA8E;IAC9E,0EAA0E;IAC1E,YAAY;IACZ,EAAE;IACF,6EAA6E;IAC7E,8EAA8E;IAC9E,gEAAgE;IAChE,EAAE;IACF,yEAAyE;IACzE,8EAA8E;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMU,eAAe;QACnBjC,MAAMU,YAAYwB,KAAK;QACvBC,OAAOzB,YAAY0B,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,mBAAmB;YACjBC,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAvC;QACAwC,gBAAgBlE;QAChB,sEAAsE;QACtEmE,SACE,AAAC1F,CAAAA,iCAAiC4C,gBAAgB3B,UAAUuC,QAAO,KACnE;QACFmC,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOhB;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/router-reducer/create-initial-router-state.ts"],"sourcesContent":["import type { InitialRSCPayload } from '../../../shared/lib/app-router-types'\n\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { extractPathFromFlightRouterState } from './compute-changed-path'\n\nimport type { AppRouterState } from './router-reducer-types'\nimport { getFlightDataPartsFromPath } from '../../flight-data-helpers'\nimport { createInitialCacheNodeForHydration } from './ppr-navigations'\nimport {\n convertRootFlightRouterStateToRouteTree,\n resolveStaleAt,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n writePrerenderResponseIntoCache,\n} from '../segment-cache/cache'\nimport { FetchStrategy } from '../segment-cache/types'\nimport {\n UnknownDynamicStaleTime,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\nimport { decodeStageUntilBoundary } from './fetch-server-response'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\n\nexport interface InitialRouterStateParameters {\n navigatedAt: number\n initialRSCPayload: InitialRSCPayload\n initialFlightStreamForCache?: ReadableStream<Uint8Array> | null\n location: Location | null\n}\n\nexport function createInitialRouterState({\n navigatedAt,\n initialRSCPayload,\n initialFlightStreamForCache,\n location,\n}: InitialRouterStateParameters): AppRouterState {\n const {\n c: initialCanonicalUrlParts,\n f: initialFlightData,\n q: initialRenderedSearch,\n i: initialCouldBeIntercepted,\n S: initialSupportsPerSegmentPrefetching,\n s: initialStaleTime,\n l: initialStaticStageByteLength,\n h: initialHeadVaryParams,\n r: initialRootVaryParams,\n p: initialRuntimePrefetchStream,\n d: initialDynamicStaleTimeSeconds,\n } = initialRSCPayload\n\n // When initialized on the server, the canonical URL is provided as an array of parts.\n // This is to ensure that when the RSC payload streamed to the client, crawlers don't interpret it\n // as a URL that should be crawled.\n const initialCanonicalUrl = initialCanonicalUrlParts.join('/')\n\n const normalizedFlightData = getFlightDataPartsFromPath(initialFlightData[0])\n const {\n tree: initialTree,\n seedData: initialSeedData,\n head: initialHead,\n } = normalizedFlightData\n // For the SSR render, seed data should always be available (we only send back a `null` response\n // in the case of a `loading` segment, pre-PPR.)\n\n const canonicalUrl =\n // location.href is read as the initial value for canonicalUrl in the browser\n // This is safe to do as canonicalUrl can't be rendered, it's only used to control the history updates in the useEffect further down in this file.\n location\n ? // window.location does not have the same type as URL but has all the fields createHrefFromUrl needs.\n createHrefFromUrl(location)\n : initialCanonicalUrl\n\n // Convert the initial FlightRouterState into the RouteTree type.\n // NOTE: The metadataVaryPath isn't used for anything currently because the\n // head is embedded into the CacheNode tree, but eventually we'll lift it out\n // and store it on the top-level state object.\n //\n // For statically-generated-at-build-time HTML pages, the FlightRouterState\n // baked into the initial RSC payload won't have the correct segment inlining\n // hints because those are computed after the pre-render. The server marks\n // these trees with InliningHintsStale, which causes the route cache entry\n // to be immediately expired. The next prefetch will re-fetch the tree with\n // correct hints from the /_tree response.\n const acc = { metadataVaryPath: null }\n const initialRouteTree = convertRootFlightRouterStateToRouteTree(\n initialTree,\n initialRenderedSearch as NormalizedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n const initialTask = createInitialCacheNodeForHydration(\n navigatedAt,\n initialRouteTree,\n initialSeedData,\n initialHead,\n computeDynamicStaleAt(\n navigatedAt,\n initialDynamicStaleTimeSeconds ?? UnknownDynamicStaleTime\n )\n )\n\n // The following only applies in the browser (location !== null) since neither\n // route learning nor segment cache state persists from SSR to client.\n if (location !== null && metadataVaryPath !== null) {\n // Learn the route pattern so we can predict it for future navigations.\n discoverKnownRoute(\n Date.now(),\n location.pathname,\n location.search as NormalizedSearch,\n null, // nextUrl — initial render is never an interception\n null, // No pending entry\n initialRouteTree,\n metadataVaryPath,\n initialCouldBeIntercepted,\n canonicalUrl,\n initialSupportsPerSegmentPrefetching,\n false // hasDynamicRewrite\n )\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the Cached\n // Navigations behavior should work in combination with App Shells.\n\n // Write the initial seed data into the segment cache so subsequent\n // navigations to the initial page can serve cached segments instantly.\n if (initialSeedData !== null && initialStaleTime !== undefined) {\n if (\n initialStaticStageByteLength !== undefined &&\n initialFlightStreamForCache != null\n ) {\n // Partially static page — truncate the cloned Flight stream at the\n // static stage byte boundary, decode, and cache the static subset.\n // Promise.resolve wraps the Flight-deserialized thenable into a\n // native Promise so we can chain `.then` on it safely.\n Promise.resolve(initialStaticStageByteLength)\n .then(async (byteLength) => {\n const staticStageResponse =\n await decodeStageUntilBoundary<InitialRSCPayload>(\n initialFlightStreamForCache,\n byteLength,\n undefined\n )\n const now = Date.now()\n const staleAt = await resolveStaleAt(now, staticStageResponse.s)\n\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n undefined, // no build ID mismatch check for initial HTML\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n true // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n } else {\n // Fully static page — cache the entire decoded seed data as-is. We're\n // not using the initial response here (which would allow us to combine\n // the two branches) to avoid unnecessary decoding of the Flight data,\n // since we can just take the seed data that we already decoded during\n // hydration and write it into the cache directly.\n const now = Date.now()\n\n resolveStaleAt(now, initialStaleTime)\n .then((staleAt) => {\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n initialFlightData,\n undefined, // buildId — not applicable for initial HTML\n initialHeadVaryParams,\n initialRootVaryParams ?? null,\n staleAt,\n initialTree,\n initialRenderedSearch,\n false // isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the page\n // rendered normally, we just won't write into the cache.\n })\n\n // Cancel the stream clone — fully static path doesn't need it.\n initialFlightStreamForCache?.cancel()\n }\n } else {\n // No caching — cancel the unused stream clone.\n initialFlightStreamForCache?.cancel()\n }\n\n // If the initial RSC payload includes an embedded runtime prefetch stream,\n // decode it and write the runtime data into the segment cache. This allows\n // subsequent navigations to serve runtime-prefetchable content from cache\n // without a separate prefetch request.\n if (initialRuntimePrefetchStream != null) {\n processRuntimePrefetchStream(\n Date.now(),\n initialRuntimePrefetchStream,\n initialTree,\n initialRenderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n Date.now(),\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // Runtime prefetch cache write failed. Not fatal — the page rendered\n // normally, we just won't cache runtime data.\n })\n }\n }\n\n // NOTE: We intentionally don't check if any data needs to be fetched from the\n // server. We assume the initial hydration payload is sufficient to render\n // the page.\n //\n // The completeness of the initial data is an important property that we rely\n // on as a last-ditch mechanism for recovering the app; we must always be able\n // to reload a fresh HTML document to get to a consistent state.\n //\n // In the future, there may be cases where the server intentionally sends\n // partial data and expects the client to fill in the rest, in which case this\n // logic may change. (There already is a similar case where the server sends\n // _no_ hydration data in the HTML document at all, and the client fetches it\n // separately, but that's different because we still end up hydrating with a\n // complete tree.)\n\n const initialState = {\n tree: initialTask.route,\n cache: initialTask.node,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // First render needs to preserve the previous window.history.state\n // to avoid it being overwritten on navigation back/forward with MPA Navigation.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: {\n scrollRef: null,\n forceScroll: false,\n onlyHashChange: false,\n hashFragment: null,\n },\n canonicalUrl,\n renderedSearch: initialRenderedSearch,\n // the || operator is intentional, the pathname can be an empty string\n nextUrl:\n (extractPathFromFlightRouterState(initialTree) || location?.pathname) ??\n null,\n previousNextUrl: null,\n debugInfo: null,\n }\n\n return initialState\n}\n"],"names":["createHrefFromUrl","extractPathFromFlightRouterState","getFlightDataPartsFromPath","createInitialCacheNodeForHydration","convertRootFlightRouterStateToRouteTree","resolveStaleAt","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","writePrerenderResponseIntoCache","FetchStrategy","UnknownDynamicStaleTime","computeDynamicStaleAt","decodeStageUntilBoundary","discoverKnownRoute","createInitialRouterState","navigatedAt","initialRSCPayload","initialFlightStreamForCache","location","c","initialCanonicalUrlParts","f","initialFlightData","q","initialRenderedSearch","i","initialCouldBeIntercepted","S","initialSupportsPerSegmentPrefetching","s","initialStaleTime","l","initialStaticStageByteLength","h","initialHeadVaryParams","r","initialRootVaryParams","p","initialRuntimePrefetchStream","d","initialDynamicStaleTimeSeconds","initialCanonicalUrl","join","normalizedFlightData","tree","initialTree","seedData","initialSeedData","head","initialHead","canonicalUrl","acc","metadataVaryPath","initialRouteTree","initialTask","Date","now","pathname","search","undefined","Promise","resolve","then","byteLength","staticStageResponse","staleAt","PPR","catch","cancel","processed","PPRRuntime","flightDatas","buildId","isResponsePartial","headVaryParams","rootVaryParamsIterable","navigationSeed","initialState","route","cache","node","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","scrollRef","forceScroll","onlyHashChange","hashFragment","renderedSearch","nextUrl","previousNextUrl","debugInfo"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,gCAAgC,QAAQ,yBAAwB;AAGzE,SAASC,0BAA0B,QAAQ,4BAA2B;AACtE,SAASC,kCAAkC,QAAQ,oBAAmB;AACtE,SACEC,uCAAuC,EACvCC,cAAc,EACdC,4BAA4B,EAC5BC,mCAAmC,EACnCC,+BAA+B,QAC1B,yBAAwB;AAC/B,SAASC,aAAa,QAAQ,yBAAwB;AACtD,SACEC,uBAAuB,EACvBC,qBAAqB,QAChB,2BAA0B;AACjC,SAASC,wBAAwB,QAAQ,0BAAyB;AAClE,SAASC,kBAAkB,QAAQ,qCAAoC;AAUvE,OAAO,SAASC,yBAAyB,EACvCC,WAAW,EACXC,iBAAiB,EACjBC,2BAA2B,EAC3BC,QAAQ,EACqB;IAC7B,MAAM,EACJC,GAAGC,wBAAwB,EAC3BC,GAAGC,iBAAiB,EACpBC,GAAGC,qBAAqB,EACxBC,GAAGC,yBAAyB,EAC5BC,GAAGC,oCAAoC,EACvCC,GAAGC,gBAAgB,EACnBC,GAAGC,4BAA4B,EAC/BC,GAAGC,qBAAqB,EACxBC,GAAGC,qBAAqB,EACxBC,GAAGC,4BAA4B,EAC/BC,GAAGC,8BAA8B,EAClC,GAAGxB;IAEJ,sFAAsF;IACtF,kGAAkG;IAClG,mCAAmC;IACnC,MAAMyB,sBAAsBrB,yBAAyBsB,IAAI,CAAC;IAE1D,MAAMC,uBAAuBzC,2BAA2BoB,iBAAiB,CAAC,EAAE;IAC5E,MAAM,EACJsB,MAAMC,WAAW,EACjBC,UAAUC,eAAe,EACzBC,MAAMC,WAAW,EAClB,GAAGN;IACJ,gG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;IAC9E,4EAA4E;IAC5E,6EAA6E;IAC7E,4EAA4E;IAC5E,kBAAkB;IAElB,MAAMU,eAAe;QACnBjC,MAAMU,YAAYwB,KAAK;QACvBC,OAAOzB,YAAY0B,IAAI;QACvBC,SAAS;YACPC,aAAa;YACbC,eAAe;YACf,mEAAmE;YACnE,gFAAgF;YAChFC,4BAA4B;QAC9B;QACAC,mBAAmB;YACjBC,WAAW;YACXC,aAAa;YACbC,gBAAgB;YAChBC,cAAc;QAChB;QACAvC;QACAwC,gBAAgBlE;QAChB,sEAAsE;QACtEmE,SACE,AAAC1F,CAAAA,iCAAiC4C,gBAAgB3B,UAAUuC,QAAO,KACnE;QACFmC,iBAAiB;QACjBC,WAAW;IACb;IAEA,OAAOhB;AACT","ignoreList":[0]} |
@@ -6,3 +6,3 @@ import { PrefetchHint, SubtreePrefetchHints, propagateSubtreeBits } from '../../../shared/lib/app-router-types'; | ||
| import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'; | ||
| import { EntryStatus, readRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry, convertRootFlightRouterStateToRouteTree, getStaleAt, writePrerenderResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache } from './cache'; | ||
| import { EntryStatus, readRouteCacheEntry, deprecated_requestOptimisticRouteCacheEntry, convertRootFlightRouterStateToRouteTree, resolveStaleAt, writePrerenderResponseIntoCache, processRuntimePrefetchStream, writeDynamicRenderResponseIntoCache } from './cache'; | ||
| import { discoverKnownRoute } from './optimistic-routes'; | ||
@@ -255,3 +255,3 @@ import { createCacheKey } from './cache-key'; | ||
| // subsequent navigations can serve cached static segments instantly. | ||
| getStaleAt(now, staticStageResponse.s).then((staleAt)=>{ | ||
| resolveStaleAt(now, staticStageResponse.s).then((staleAt)=>{ | ||
| const buildId = responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? staticStageResponse.b; | ||
@@ -258,0 +258,0 @@ // TODO: Implement Shell extraction as part of Cached Navigations. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData } from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n convertRootFlightRouterStateToRouteTree,\n getStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type RouteTree,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { PageVaryPath } from './vary-path'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.data,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n data: null,\n head: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n flightData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n createHrefFromUrl(canonicalUrl),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n getStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n buildId,\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n// TODO: The rest of this file is related to converting the server response into\n// the data structures used by the client. Probably should move to a\n// separate module.\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree\n metadataVaryPath: PageVaryPath | null\n data: CacheNodeSeedData | null\n head: HeadData | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n flightData: Array<NormalizedFlightData> | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n\n let baseTree: FlightRouterState = currentTree\n let baseData: CacheNodeSeedData | null = null\n let head: HeadData | null = null\n if (flightData !== null) {\n for (const {\n segmentPath,\n tree: treePatch,\n seedData: dataPatch,\n head: headPatch,\n } of flightData) {\n const result = convertServerPatchToFullTreeImpl(\n baseTree,\n baseData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n 0\n )\n baseTree = result.tree\n baseData = result.data\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch\n }\n }\n\n const finalFlightRouterState = baseTree\n\n // Convert the final FlightRouterState into a RouteTree type.\n //\n // TODO: Eventually, FlightRouterState will evolve to being a transport format\n // only. The RouteTree type will become the main type used for dealing with\n // routes on the client, and we'll store it in the state directly.\n const acc = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n finalFlightRouterState,\n renderedSearch as NormalizedSearch,\n acc\n )\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n data: baseData,\n renderedSearch,\n head,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n baseRouterState: FlightRouterState,\n baseData: CacheNodeSeedData | null,\n treePatch: FlightRouterState,\n dataPatch: CacheNodeSeedData | null,\n segmentPath: FlightSegmentPath,\n renderedSearch: string,\n index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch,\n }\n }\n\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey: string = segmentPath[index]\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n const baseTreeChildren = baseRouterState[1]\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n const newTreeChildren: Record<string, FlightRouterState> = {}\n const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n for (const parallelRouteKey in baseTreeChildren) {\n const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n const childBaseSeedData =\n baseSeedDataChildren !== null\n ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n : null\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(\n childBaseRouterState,\n childBaseSeedData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2\n )\n\n newTreeChildren[parallelRouteKey] = result.tree\n newSeedDataChildren[parallelRouteKey] = result.data\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n }\n }\n\n let clonedTree: FlightRouterState\n let clonedSeedData: CacheNodeSeedData\n // Clone all the fields except the children.\n\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [baseRouterState[0], newTreeChildren]\n if (2 in baseRouterState) {\n const compressedRefreshState = baseRouterState[2]\n if (\n compressedRefreshState !== undefined &&\n compressedRefreshState !== null\n ) {\n // Since this part of the tree was patched with new data, any parent\n // refresh states should be updated to reflect the new rendered search\n // value. (The refresh state acts like a \"context provider\".) All pages\n // within the same server response share the same renderedSearch value,\n // but the same RouteTree could be composed from multiple different\n // routes, and multiple responses.\n clonedTree[2] = [compressedRefreshState[0], renderedSearch]\n }\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3]\n }\n // Recompute the propagated \"subtree\" prefetch hints for this segment. Mirrors\n // the propagation done on the server in\n // createFlightRouterStateFromLoaderTree.\n let prefetchHints = (baseRouterState[4] ?? 0) & ~SubtreePrefetchHints\n for (const parallelRouteKey in newTreeChildren) {\n const childHints = newTreeChildren[parallelRouteKey][4]\n if (childHints !== undefined) {\n prefetchHints = propagateSubtreeBits(prefetchHints, childHints)\n }\n }\n if (prefetchHints !== 0) {\n clonedTree[4] = prefetchHints\n }\n\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n null,\n ]\n\n return {\n tree: clonedTree,\n data: clonedSeedData,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves once it has spawned every request and all of them have fulfilled,\n // so the navigation below reads present data rather than a still-in-flight\n // entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["PrefetchHint","SubtreePrefetchHints","propagateSubtreeBits","fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","beginLockedNavigation","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","convertRootFlightRouterStateToRouteTree","getStaleAt","writePrerenderResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","createLinkPrefetchPartialError","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","fetchStrategy","Full","routeTree","prefetchHints","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","metadataVaryPath","data","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","flightData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","search","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","f","h","r","processed","PPRRuntime","flightDatas","headVaryParams","rootVaryParamsIterable","revealAfter","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","currentTree","dynamicStaleTimeSeconds","baseTree","baseData","segmentPath","treePatch","seedData","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","acc","baseRouterState","index","length","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","parallelRouteKey","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","childHints","isEmptySeedDataPartial","beginNavigationLockPrefetch","navigationLockPr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AE,GACnC1J,QAAQ;IACV,MAAM2J,yBAAyBD;IAC/BpL,qBACEgC,UACAhB,0BACAmC,eACAlD,iBAAiBwF,OAAO,EACxB,MACA4F;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBC,OAAO;IACtC;IAEA,uEAAuE;IACvE,wCAAwC;IACxC,MAAMtF,SAAS,MAAMpE,aACnBjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;IAGF,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAAC2E,OAAOiC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAEoD,uBAAuB,EAAE,GAC/B7J,QAAQ;QACV6J,wBAAwBvK,0BAA0BgF,OAAOd,IAAI;IAC/D;IAEA,OAAOc;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/client/components/segment-cache/navigation.ts"],"sourcesContent":["import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData } from '../../../shared/lib/app-router-types'\nimport {\n PrefetchHint,\n SubtreePrefetchHints,\n propagateSubtreeBits,\n} from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n beginLockedNavigation,\n type NavigationLock,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n convertRootFlightRouterStateToRouteTree,\n resolveStaleAt,\n writePrerenderResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type RouteTree,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { PageVaryPath } from './vary-path'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\nimport { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n let navigationLock: NavigationLock | null = null\n\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n // Signal that a new locked navigation is starting. This force-resolves the\n // previous locked navigation's withheld data (so a reused shared segment\n // no longer carries a pending deferred rsc) and returns this navigation's\n // own withheld-data gate.\n navigationLock = beginLockedNavigation()\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route,\n navigationLock\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute,\n navigationLock\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null,\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n signal: AbortSignal | undefined\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n if (\n process.env.NODE_ENV !== 'production' &&\n process.env.__NEXT_CACHE_COMPONENTS\n ) {\n // Warn when navigating via a `<Link prefetch={true}>` to a route that has\n // not opted into Partial Prefetching. Such a link does a legacy \"full\"\n // prefetch that includes the route's dynamic data, defeating the\n // static/dynamic split that Cache Components provides.\n //\n // This runs at navigation time (rather than prefetch time) so that, in dev\n // where we don't prefetch, the warning only appears when you actually\n // navigate to the route — existing apps with many `prefetch={true}` links\n // aren't flooded with warnings the moment they enable Cache Components.\n //\n // The warning is suppressed if any segment on the target route exports\n // `instant = false`, which is the explicit API for opting a route out of\n // this validation.\n const link = getLinkForCurrentNavigation()\n if (\n link !== null &&\n link.fetchStrategy === FetchStrategy.Full &&\n (navigationSeed.routeTree.prefetchHints &\n (PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasInstantFalse)) ===\n 0\n ) {\n const error = createLinkPrefetchPartialError(url.pathname)\n const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined\n if (ownerStack === undefined) {\n console.error(\n '' +\n 'Cannot associate the \"prefetch={true}\" warning with a specific <Link> making it harder to find the cause of the following warning. ' +\n 'This is a bug in Next.js.'\n )\n } else if (ownerStack !== null) {\n // Replace the (useless) stack captured at the throw site — which\n // points into router internals — with the Owner Stack captured when\n // the <Link> rendered. That way the dev overlay associates this\n // warning with the JSX that created the link, not with\n // navigation.ts.\n error.stack = `${error.name}: ${error.message}${ownerStack}`\n }\n console.error(error)\n }\n }\n\n // Instant Navigation Testing API: when the lock is held, restrict segment\n // reads to shell entries if the target route would only have prefetched\n // its shell.\n let restrictToShell = false\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { shouldRestrictNavigationToShell } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const link = getLinkForCurrentNavigation()\n restrictToShell = shouldRestrictNavigationToShell(\n navigationSeed.routeTree.prefetchHints,\n link !== null ? link.fetchStrategy : FetchStrategy.PPR\n )\n }\n\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.data,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation,\n restrictToShell\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType,\n navigationLock,\n signal\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry,\n navigationLock: NavigationLock | null\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n data: null,\n head: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n null,\n route,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n flightData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n url.search as NormalizedSearch,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n createHrefFromUrl(canonicalUrl),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n resolveStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n // TODO: Implement Shell extraction as part of Cached Navigations.\n // Intentionally holding off on doing this until we decide how the\n // Cached Navigations behavior should work in combination with App\n // Shells.\n writePrerenderResponseIntoCache(\n now,\n FetchStrategy.PPR,\n staticStageResponse.f,\n buildId,\n staticStageResponse.h,\n staticStageResponse.r ?? null,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.rootVaryParamsIterable,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n // In the streaming dev render, this single response's seed content may still\n // be streaming when we build the tree below. An unknown-route navigation\n // places that content inline (it has no prior cache entry, so the server\n // sends a full seed rather than the dynamic-only delta a known route gets),\n // and that inline content is not gated like a known route's deferred RSCs. So\n // React could read a still-pending chunk and flash a Suspense fallback\n // (wanted on a cold cache, but not on a warm one). Wait for the shell to\n // flush (`revealAfter`) first, so the inline seed content is decoded by the\n // time React reads it, the same way the known-route path gates its deferred\n // RSCs. `revealAfter` is null outside the streaming dev render. On a cache\n // miss it resolves early, so the cold-cache fallback is still shown.\n if (result.revealAfter !== null) {\n await result.revealAfter\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n navigationLock,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null,\n // Not an HMR refresh, so there's no request generation to cancel.\n undefined\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n// TODO: The rest of this file is related to converting the server response into\n// the data structures used by the client. Probably should move to a\n// separate module.\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree\n metadataVaryPath: PageVaryPath | null\n data: CacheNodeSeedData | null\n head: HeadData | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n flightData: Array<NormalizedFlightData> | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n\n let baseTree: FlightRouterState = currentTree\n let baseData: CacheNodeSeedData | null = null\n let head: HeadData | null = null\n if (flightData !== null) {\n for (const {\n segmentPath,\n tree: treePatch,\n seedData: dataPatch,\n head: headPatch,\n } of flightData) {\n const result = convertServerPatchToFullTreeImpl(\n baseTree,\n baseData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n 0\n )\n baseTree = result.tree\n baseData = result.data\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch\n }\n }\n\n const finalFlightRouterState = baseTree\n\n // Convert the final FlightRouterState into a RouteTree type.\n //\n // TODO: Eventually, FlightRouterState will evolve to being a transport format\n // only. The RouteTree type will become the main type used for dealing with\n // routes on the client, and we'll store it in the state directly.\n const acc = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n finalFlightRouterState,\n renderedSearch as NormalizedSearch,\n acc\n )\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n data: baseData,\n renderedSearch,\n head,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n baseRouterState: FlightRouterState,\n baseData: CacheNodeSeedData | null,\n treePatch: FlightRouterState,\n dataPatch: CacheNodeSeedData | null,\n segmentPath: FlightSegmentPath,\n renderedSearch: string,\n index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch,\n }\n }\n\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey: string = segmentPath[index]\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n const baseTreeChildren = baseRouterState[1]\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n const newTreeChildren: Record<string, FlightRouterState> = {}\n const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n for (const parallelRouteKey in baseTreeChildren) {\n const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n const childBaseSeedData =\n baseSeedDataChildren !== null\n ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n : null\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(\n childBaseRouterState,\n childBaseSeedData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2\n )\n\n newTreeChildren[parallelRouteKey] = result.tree\n newSeedDataChildren[parallelRouteKey] = result.data\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n }\n }\n\n let clonedTree: FlightRouterState\n let clonedSeedData: CacheNodeSeedData\n // Clone all the fields except the children.\n\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [baseRouterState[0], newTreeChildren]\n if (2 in baseRouterState) {\n const compressedRefreshState = baseRouterState[2]\n if (\n compressedRefreshState !== undefined &&\n compressedRefreshState !== null\n ) {\n // Since this part of the tree was patched with new data, any parent\n // refresh states should be updated to reflect the new rendered search\n // value. (The refresh state acts like a \"context provider\".) All pages\n // within the same server response share the same renderedSearch value,\n // but the same RouteTree could be composed from multiple different\n // routes, and multiple responses.\n clonedTree[2] = [compressedRefreshState[0], renderedSearch]\n }\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3]\n }\n // Recompute the propagated \"subtree\" prefetch hints for this segment. Mirrors\n // the propagation done on the server in\n // createFlightRouterStateFromLoaderTree.\n let prefetchHints = (baseRouterState[4] ?? 0) & ~SubtreePrefetchHints\n for (const parallelRouteKey in newTreeChildren) {\n const childHints = newTreeChildren[parallelRouteKey][4]\n if (childHints !== undefined) {\n prefetchHints = propagateSubtreeBits(prefetchHints, childHints)\n }\n }\n if (prefetchHints !== 0) {\n clonedTree[4] = prefetchHints\n }\n\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n null,\n ]\n\n return {\n tree: clonedTree,\n data: clonedSeedData,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n navigationLock: NavigationLock | null\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n // Create this navigation's \"wait for prefetch to fulfill\" state and schedule\n // the prefetch as a locked-navigation prefetch. The prefetch's promise\n // resolves once it has spawned every request and all of them have fulfilled,\n // so the navigation below reads present data rather than a still-in-flight\n // entry.\n const { beginNavigationLockPrefetch } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n const navigationLockPrefetch = beginNavigationLockPrefetch()\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n navigationLockPrefetch\n )\n if (navigationLockPrefetch !== null) {\n await navigationLockPrefetch.promise\n }\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n navigationLock\n )\n\n // Only transition to captured-SPA once the navigation is known to be an SPA.\n // If the result is an MPA navigation, leave the cookie pending and let the new\n // document load transition it to captured-MPA.\n if (!result.pushRef.mpaNavigation) {\n const { updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n }\n\n return result\n}\n"],"names":["PrefetchHint","SubtreePrefetchHints","propagateSubtreeBits","fetchServerResponse","startPPRNavigation","spawnDynamicRequests","FreshnessPolicy","beginLockedNavigation","createHrefFromUrl","NEXT_NAV_DEPLOYMENT_ID_HEADER","EntryStatus","readRouteCacheEntry","deprecated_requestOptimisticRouteCacheEntry","convertRootFlightRouterStateToRouteTree","resolveStaleAt","writePrerenderResponseIntoCache","processRuntimePrefetchStream","writeDynamicRenderResponseIntoCache","discoverKnownRoute","createCacheKey","schedulePrefetchTask","PrefetchPriority","FetchStrategy","getLinkForCurrentNavigation","ScrollBehavior","computeChangedPath","isJavaScriptURLString","UnknownDynamicStaleTime","computeDynamicStaleAt","createLinkPrefetchPartialError","navigate","state","url","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","nextUrl","freshnessPolicy","scrollBehavior","navigateType","navigationLock","process","env","__NEXT_EXPOSE_TESTING_API","isNavigationLocked","require","ensurePrefetchThenNavigate","navigateImpl","now","Date","href","cacheKey","route","status","Fulfilled","navigateUsingPrefetchedRouteTree","__NEXT_OPTIMISTIC_ROUTING","Rejected","optimisticRoute","navigateToUnknownRoute","catch","navigateToKnownRoute","canonicalUrl","navigationSeed","debugInfo","routeCacheEntry","signal","NODE_ENV","__NEXT_CACHE_COMPONENTS","link","fetchStrategy","Full","routeTree","prefetchHints","SubtreeHasPartialPrefetching","SubtreeHasInstantFalse","error","pathname","ownerStack","undefined","console","stack","name","message","restrictToShell","shouldRestrictNavigationToShell","PPR","accumulation","separateRefreshUrls","scrollRef","isSamePageNavigation","task","metadataVaryPath","data","head","dynamicStaleAt","Gesture","completeSoftNavigation","node","renderedSearch","completeHardNavigation","tree","hash","prefetchSeed","metadata","varyPath","DynamicRequestTreeForEntireRoute","dynamicRequestTree","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","flightRouterState","result","redirectUrl","URL","location","origin","flightData","couldBeIntercepted","supportsPerSegmentPrefetching","dynamicStaleTime","staticStageData","runtimePrefetchStream","responseHeaders","convertServerPatchToFullTree","search","response","staticStageResponse","isResponsePartial","s","then","staleAt","buildId","get","b","f","h","r","processed","PPRRuntime","flightDatas","headVaryParams","rootVaryParamsIterable","revealAfter","newState","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","cache","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","changedPath","nextUrlForNewRoute","oldUrl","onlyHashChange","activeScrollRef","forceScroll","NoScroll","current","oldScrollRef","hashFragment","decodeURIComponent","slice","completeTraverseNavigation","currentTree","dynamicStaleTimeSeconds","baseTree","baseData","segmentPath","treePatch","seedData","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","acc","baseRouterState","index","length","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","parallelRouteKey","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","childHints","isEmptySeedDataPartial","beginNavigationLockPrefetch","navigationLockPrefetch","promise","updateCapturedSPAToTree"],"mappings":"AAQA,SACEA,YAAY,EACZC,oBAAoB,EACpBC,oBAAoB,QACf,uCAAsC;AAE7C,SAASC,mBAAmB,QAAQ,0CAAyC;AAC7E,SACEC,kBAAkB,EAClBC,oBAAoB,EACpBC,eAAe,EACfC,qBAAqB,QAGhB,oCAAmC;AAC1C,SAASC,iBAAiB,QAAQ,yCAAwC;AAC1E,SAASC,6BAA6B,QAAQ,yBAAwB;AACtE,SACEC,WAAW,EACXC,mBAAmB,EACnBC,2CAA2C,EAC3CC,uCAAuC,EACvCC,cAAc,EACdC,+BAA+B,EAC/BC,4BAA4B,EAC5BC,mCAAmC,QAG9B,UAAS;AAChB,SAASC,kBAAkB,QAAQ,sBAAqB;AACxD,SAASC,cAAc,QAA+B,cAAa;AACnE,SAASC,oBAAoB,QAAQ,cAAa;AAClD,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,UAAS;AACzD,SAASC,2BAA2B,QAAQ,WAAU;AAGtD,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,qBAAqB,QAAQ,2BAA0B;A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QACAQ;QACA;KACD;IAED,OAAO;QACLjG,MAAM6F;QACNrG,MAAMsG;IACR;AACF;AAEA;;;;;;;CAOC,GACD,eAAerJ,2BACbhB,KAAqB,EACrBC,GAAQ,EACRC,UAAe,EACfC,qBAA6B,EAC7BC,gBAAkC,EAClCC,wBAA2C,EAC3CC,OAAsB,EACtBC,eAAgC,EAChCC,cAA8B,EAC9BC,YAAgC,EAChCC,cAAqC;IAErC,MAAM6B,OAAO/C;IACb,MAAMgD,gBAAgBD,SAAS,OAAOA,KAAKC,aAAa,GAAGjD,cAAciE,GAAG;IAE5E,MAAMnC,WAAWjC,eAAea,IAAImB,IAAI,EAAEd;IAE1C,6EAA6E;IAC7E,uEAAuE;IACvE,6EAA6E;IAC7E,2EAA2E;IAC3E,SAAS;IACT,MAAM,EAAEmK,2BAA2B,EAAE,GACnC1J,QAAQ;IACV,MAAM2J,yBAAyBD;IAC/BpL,qBACEgC,UACAhB,0BACAmC,eACAlD,iBAAiBwF,OAAO,EACxB,MACA4F;IAEF,IAAIA,2BAA2B,MAAM;QACnC,MAAMA,uBAAuBC,OAAO;IACtC;IAEA,uEAAuE;IACvE,wCAAwC;IACxC,MAAMtF,SAAS,MAAMpE,aACnBjB,OACAC,KACAC,YACAC,uBACAC,kBACAC,0BACAC,SACAC,iBACAC,gBACAC,cACAC;IAGF,6EAA6E;IAC7E,+EAA+E;IAC/E,+CAA+C;IAC/C,IAAI,CAAC2E,OAAOiC,OAAO,CAACE,aAAa,EAAE;QACjC,MAAM,EAAEoD,uBAAuB,EAAE,GAC/B7J,QAAQ;QACV6J,wBAAwBvK,0BAA0BgF,OAAOd,IAAI;IAC/D;IAEA,OAAOc;AACT","ignoreList":[0]} |
@@ -28,3 +28,3 @@ /* global location */ // imports polyfill from `@next/polyfill-module` after build. | ||
| import { isNextRouterError } from './components/is-next-router-error'; | ||
| export const version = "16.3.0-canary.97"; | ||
| export const version = "16.3.0-canary.99"; | ||
| export let router; | ||
@@ -31,0 +31,0 @@ export const emitter = mitt(); |
@@ -20,3 +20,3 @@ import { readFileSync, writeFileSync } from 'fs'; | ||
| const data = await res.json(); | ||
| const versionData = data.versions["16.3.0-canary.97"]; | ||
| const versionData = data.versions["16.3.0-canary.99"]; | ||
| return { | ||
@@ -54,3 +54,3 @@ os: versionData.os, | ||
| lockfileParsed.dependencies[pkg] = { | ||
| version: "16.3.0-canary.97", | ||
| version: "16.3.0-canary.99", | ||
| resolved: pkgData.tarball, | ||
@@ -63,3 +63,3 @@ integrity: pkgData.integrity, | ||
| lockfileParsed.packages[pkg] = { | ||
| version: "16.3.0-canary.97", | ||
| version: "16.3.0-canary.99", | ||
| resolved: pkgData.tarball, | ||
@@ -66,0 +66,0 @@ integrity: pkgData.integrity, |
@@ -1,3 +0,3 @@ | ||
| export { }; | ||
| export { getRequestInsightKey, getRequestInsightKind } from '../../shared/lib/request-insights'; | ||
| //# sourceMappingURL=request-insights.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/next-devtools/shared/request-insights.ts"],"sourcesContent":["type RequestInsightAttributeValue =\n | string\n | number\n | boolean\n | Array<null | undefined | string>\n | Array<null | undefined | number>\n | Array<null | undefined | boolean>\n\nexport type RequestInsightSpan = {\n name: string\n startTime: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n attributes?: Record<string, RequestInsightAttributeValue>\n links?: Array<{\n traceId: string\n spanId: string\n attributes?: Record<string, RequestInsightAttributeValue>\n }>\n events?: Array<{\n name: string\n timestamp: number\n attributes?: Record<string, RequestInsightAttributeValue>\n }>\n error?: {\n type?: string\n message?: string\n }\n}\n\nexport type RequestInsightFetch = {\n url?: string\n method?: string\n statusCode?: number\n startTime?: number\n durationMs?: number\n cacheStatus?: string\n cacheReason?: string\n index?: number\n}\n\nexport type RequestInsight = {\n requestId: string\n htmlRequestId: string\n route?: string\n url?: string\n startTime: number\n durationMs?: number\n status: 'ok' | 'error' | 'pending'\n spans: RequestInsightSpan[]\n fetches: RequestInsightFetch[]\n}\n\nexport type RequestInsightsSnapshot = {\n requests: RequestInsight[]\n}\n"],"names":[],"mappings":"AAwDA,WAEC","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/next-devtools/shared/request-insights.ts"],"sourcesContent":["import type { RequestInsightKind } from '../../shared/lib/request-insights'\n\nexport {\n getRequestInsightKey,\n getRequestInsightKind,\n type RequestInsightIdentity,\n type RequestInsightKind,\n} from '../../shared/lib/request-insights'\n\ntype RequestInsightAttributeValue =\n | string\n | number\n | boolean\n | Array<null | undefined | string>\n | Array<null | undefined | number>\n | Array<null | undefined | boolean>\n\nexport type RequestInsightSpan = {\n name: string\n startTime: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n attributes?: Record<string, RequestInsightAttributeValue>\n links?: Array<{\n traceId: string\n spanId: string\n attributes?: Record<string, RequestInsightAttributeValue>\n }>\n events?: Array<{\n name: string\n timestamp: number\n attributes?: Record<string, RequestInsightAttributeValue>\n }>\n error?: {\n type?: string\n message?: string\n }\n}\n\nexport type RequestInsightFetch = {\n url?: string\n method?: string\n statusCode?: number\n startTime?: number\n durationMs?: number\n cacheStatus?: string\n cacheReason?: string\n index?: number\n}\n\nexport type RequestInsight = {\n requestId: string\n kind?: RequestInsightKind\n htmlRequestId: string\n route?: string\n url?: string\n startTime: number\n durationMs?: number\n status: 'ok' | 'error' | 'pending'\n spans: RequestInsightSpan[]\n fetches: RequestInsightFetch[]\n}\n\nexport type RequestInsightsSnapshot = {\n requests: RequestInsight[]\n}\n"],"names":["getRequestInsightKey","getRequestInsightKind"],"mappings":"AAEA,SACEA,oBAAoB,EACpBC,qBAAqB,QAGhB,oCAAmC","ignoreList":[0]} |
| /* eslint-disable @next/internal/no-ambiguous-jsx -- Bundled in entry-base so it gets the right JSX runtime. */ import { jsx as _jsx } from "react/jsx-runtime"; | ||
| import { PrefetchHint, StaticPrefetchDisabled } from '../../shared/lib/app-router-types'; | ||
| import { readVaryParams } from '../../shared/lib/segment-cache/vary-params-decoding'; | ||
| // eslint-disable-next-line import/no-extraneous-dependencies | ||
@@ -8,5 +7,8 @@ import { createFromReadableStream } from 'react-server-dom-webpack/client'; | ||
| import { prerender } from 'react-server-dom-webpack/static'; | ||
| // eslint-disable-next-line import/no-extraneous-dependencies | ||
| import { renderToReadableStream } from 'react-server-dom-webpack/server'; | ||
| import { streamFromBuffer, streamToBuffer } from '../stream-utils/node-web-streams-helper'; | ||
| import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'; | ||
| import { waitAtLeastOneReactRenderTask } from '../../lib/scheduler'; | ||
| import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'; | ||
| import { createSegmentRequestKeyPart, appendSegmentRequestKeyPart, ROOT_SEGMENT_REQUEST_KEY, HEAD_REQUEST_KEY } from '../../shared/lib/segment-cache/segment-value-encoding'; | ||
@@ -57,4 +59,17 @@ import { getDigestForWellKnownError } from './create-error-handler'; | ||
| // | ||
| // The warm-up decode also tells us the page's own shell byte boundary (its | ||
| // `a` field): a byte offset into fullPageDataBuffer marking the end of the | ||
| // page's shell stage, null if the shell is identical to the full static | ||
| // response, or undefined if the render wasn't staged (no shell exists). | ||
| // | ||
| // And it tells us whether the render accessed runtime data (cookies, | ||
| // headers, fallback params, searchParams, ...): the settled value of the | ||
| // page's embedded access flag (its `u` field). Conservatively true when | ||
| // the page carries no flag (legacy render paths) or the decode fails. | ||
| let pageShellByteLength = undefined; | ||
| let runtimeDataAccessed = true; | ||
| try { | ||
| await createFromReadableStream(streamFromBuffer(fullPageDataBuffer), { | ||
| const pagePayload = await createFromReadableStream(// Use a stream that never closes so pending references (dynamic | ||
| // holes) can't error the decode. | ||
| createUnclosingPrefetchStream(streamFromBuffer(fullPageDataBuffer)), { | ||
| findSourceMapURL, | ||
@@ -64,3 +79,45 @@ serverConsumerManifest | ||
| await waitAtLeastOneReactRenderTask(); | ||
| // `a` is a promise resolved mid-stream; the whole buffer is present, so | ||
| // it resolves. undefined means the render wasn't staged (no shell). | ||
| if (pagePayload.a !== undefined) { | ||
| pageShellByteLength = await pagePayload.a; | ||
| } | ||
| if (pagePayload.u !== undefined) { | ||
| runtimeDataAccessed = readRuntimeDataAccessed(pagePayload.u); | ||
| } | ||
| } catch {} | ||
| // All segment responses of a page share one decode of the page buffer, and | ||
| // one `release` promise that coordinates the two serialization stages: it | ||
| // resolves when the coordinator lets the shell-stage bytes settle into the | ||
| // rest of the page data (see renderSegmentPrefetch, which measures each | ||
| // response's shell boundary at that moment). Its resolved value is true | ||
| // when the page's shell is identical to its full static response — then so | ||
| // is every segment's, so each resolves `a` to null instead of a boundary. | ||
| // | ||
| // When the page has a real shell boundary the decode is staged: only the | ||
| // shell byte prefix is enqueued now, the rest held until the release. With | ||
| // no boundary there's nothing to stage on, so the whole buffer is decoded | ||
| // at once and the release is resolved eagerly (segment boundaries then fall | ||
| // out as 0 or null without any measurement). | ||
| const release = createPromiseWithResolvers(); | ||
| let pageDataStream; | ||
| if (typeof pageShellByteLength === 'number') { | ||
| const prefixLength = pageShellByteLength; | ||
| pageDataStream = new ReadableStream({ | ||
| async start (controller) { | ||
| // The shell byte prefix decodes to the page's shell variant: | ||
| // everything the staged page render serialized after its shell stage | ||
| // stays a pending reference until the release enqueues the rest. | ||
| controller.enqueue(fullPageDataBuffer.subarray(0, prefixLength)); | ||
| await release.promise; | ||
| controller.enqueue(fullPageDataBuffer.subarray(prefixLength)); | ||
| // Intentionally never closed, like createUnclosingPrefetchStream: | ||
| // the page stream may hold references that never resolve (dynamic | ||
| // holes), and Flight errors if the stream closes while any are pending. | ||
| } | ||
| }); | ||
| } else { | ||
| pageDataStream = createUnclosingPrefetchStream(streamFromBuffer(fullPageDataBuffer)); | ||
| release.resolve(pageShellByteLength === null); | ||
| } | ||
| // Create an abort controller that we'll use to stop the stream. | ||
@@ -80,22 +137,48 @@ const abortController = new AbortController(); | ||
| const segmentTasks = []; | ||
| const { prelude: treeStream } = await prerender(// RootTreePrefetch is not a valid return type for a React component, but | ||
| // we need to use a component so that when we decode the original stream | ||
| // inside of it, the side effects are transferred to the new stream. | ||
| // @ts-expect-error | ||
| /*#__PURE__*/ _jsx(PrefetchTreeData, { | ||
| isClientParamParsingEnabled: isCacheComponentsEnabled, | ||
| fullPageDataBuffer: fullPageDataBuffer, | ||
| serverConsumerManifest: serverConsumerManifest, | ||
| clientModules: clientModules, | ||
| staleTime: staleTime, | ||
| segmentTasks: segmentTasks, | ||
| onCompletedProcessingRouteTree: onCompletedProcessingRouteTree, | ||
| prefetchInlining: prefetchInlining, | ||
| hints: hints, | ||
| isUpgradeableISRFallback: isUpgradeableISRFallback | ||
| }), clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError: onSegmentPrerenderError | ||
| }); | ||
| let treeStream; | ||
| try { | ||
| const prerenderResult = await prerender(// RootTreePrefetch is not a valid return type for a React component, but | ||
| // we need to use a component so that when we decode the original stream | ||
| // inside of it, the side effects are transferred to the new stream. | ||
| // @ts-expect-error | ||
| /*#__PURE__*/ _jsx(PrefetchTreeData, { | ||
| isClientParamParsingEnabled: isCacheComponentsEnabled, | ||
| pageDataStream: pageDataStream, | ||
| serverConsumerManifest: serverConsumerManifest, | ||
| clientModules: clientModules, | ||
| staleTime: staleTime, | ||
| segmentTasks: segmentTasks, | ||
| onCompletedProcessingRouteTree: onCompletedProcessingRouteTree, | ||
| prefetchInlining: prefetchInlining, | ||
| hints: hints, | ||
| isUpgradeableISRFallback: isUpgradeableISRFallback, | ||
| runtimeDataAccessed: runtimeDataAccessed, | ||
| shellStageRelease: release.promise | ||
| }), clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError: onSegmentPrerenderError | ||
| }); | ||
| treeStream = prerenderResult.prelude; | ||
| // The tree walk has spawned every segment render, each against the fully | ||
| // available shell prefix; one task later they've flushed their shells and | ||
| // are blocked on the release for the rest. | ||
| await waitAtLeastOneReactRenderTask(); | ||
| } catch (error) { | ||
| // The release still fires (finally below), so the spawned tasks run to | ||
| // completion — but the throw skips the Promise.all that observes them. | ||
| // Absorb their rejections so a failing task can't crash as an unhandled | ||
| // rejection and mask this error. | ||
| void Promise.allSettled(segmentTasks); | ||
| throw error; | ||
| } finally{ | ||
| // Start the second stage: settle the rest of the page data into the | ||
| // decode so each render can measure its boundary and finish. Runs on | ||
| // failure too, so a tree-render error can't strand the spawned tasks on | ||
| // a release that never comes. (false is inert here: a staged page's shell | ||
| // is always a strict prefix, and an unstaged release already resolved.) | ||
| // TODO: I don't think it's really necessary to unblock the spawned tasks. | ||
| // It's fine if they hang indefinitely; the tasks will be garbage collected. | ||
| release.resolve(false); | ||
| } | ||
| // Write the route tree to a special `/_tree` segment. | ||
@@ -106,5 +189,4 @@ const treeBuffer = await streamToBuffer(treeStream); | ||
| resultMap.set('/_full', fullPageDataBuffer); | ||
| // Now that we've finished rendering the route tree, all the segment tasks | ||
| // should have been spawned. Await them in parallel and write the segment | ||
| // prefetches to the result map. | ||
| // Await the segment tasks in parallel and write the segment prefetches to | ||
| // the result map. | ||
| let hasPageSegment = false; | ||
@@ -139,3 +221,16 @@ for (const [segmentPath, buffer] of (await Promise.all(segmentTasks))){ | ||
| * are output as separate entries vs. inlined into their parent. | ||
| */ export async function collectPrefetchHints(fullPageDataBuffer, staleTime, clientModules, serverConsumerManifest, maxSize, maxBundleSize) { | ||
| * | ||
| * `shouldAttemptStaticPrefetch` (computed by the caller from the prerender's | ||
| * runtime-data tracking) is folded onto every node of the result, so the | ||
| * manifest delivers it to every response like the other hint bits. It's | ||
| * independent of the inlining feature: when `inlining` is false the sizing | ||
| * pass is skipped entirely — no inlining bits are emitted — and only the | ||
| * tree shape carrying the static-prefetch hint is built. | ||
| * | ||
| * Both kinds of hint have the same structure and the same lifetime — one | ||
| * bitmask per node of the route tree, measured once per build and constant | ||
| * for the deployment. They differ only in what they're derived from: the | ||
| * inlining bits from the size of each segment's encoded response, the | ||
| * static-prefetch bit from what the decoded body turned out to access. | ||
| */ export async function collectPrefetchHints(fullPageDataBuffer, staleTime, clientModules, serverConsumerManifest, inlining, shouldAttemptStaticPrefetch) { | ||
| // Warm up the module cache, same as collectSegmentData. | ||
@@ -162,12 +257,36 @@ try { | ||
| const { buildId, flightRouterState, seedData, head } = flightData; | ||
| // Root params are emitted once at the top level; readVaryParams unions them | ||
| // into the head, and the iterable is threaded down so every segment below | ||
| // unions it too. | ||
| // The hints every node starts from. The static-prefetch-attempt hint is | ||
| // page-global (the tracking that feeds it is), so it goes on every node, | ||
| // non-propagating — the client reads it per segment, and the runtime | ||
| // hint merging walks the manifest tree node-by-node. | ||
| const baseHints = shouldAttemptStaticPrefetch ? PrefetchHint.ShouldAttemptStaticPrefetch : 0; | ||
| if (inlining === false) { | ||
| // Prefetch inlining is disabled: nothing to measure, and no inlining | ||
| // bits may be emitted (the client would act on them even though the | ||
| // responses aren't bundled). Just mirror the route tree's shape with | ||
| // the base hints on every node. | ||
| return createUniformHintTree(flightRouterState, baseHints); | ||
| } | ||
| const { maxSize, maxBundleSize } = inlining; | ||
| // Root params are forwarded once at the top level of each segment | ||
| // response, same as the page response's own root vary params; the client | ||
| // unions them into each segment's set at read time. | ||
| const rootVaryParamsIterable = initialRSCPayload.r ?? null; | ||
| // The page's staleTime iterable, forwarded into each segment response. When | ||
| // Cache Components is off the page carries no `s`, so wrap the eager value. | ||
| const staleTimeIterable = initialRSCPayload.s ?? createStaleTimeIterable(staleTime); | ||
| // The page's runtime-data-access flag, forwarded into each segment | ||
| // response's `needsRuntimeRequest`. This pass only measures sizes, so a | ||
| // conservative already-resolved `true` stands in when the page carries | ||
| // no `u`. | ||
| const needsRuntimeRequest = initialRSCPayload.u ?? Promise.resolve(true); | ||
| // This pass only measures gzip sizes for inlining hints, so nothing is | ||
| // staged (each response's `a` falls out as the no-shell sentinel, 0), but | ||
| // the responses are byte-identical in shape to the real ones — the point | ||
| // of measuring. Pre-resolving false is the "nothing staged" release. | ||
| const shellStageRelease = Promise.resolve(false); | ||
| // Measure the head (metadata/viewport) gzip size so the main traversal | ||
| // can decide whether to inline it into a page's bundle. | ||
| const headVaryParams = readVaryParams(initialRSCPayload.h, rootVaryParamsIterable); | ||
| const [, headBuffer] = await renderSegmentPrefetch(buildId, staleTime, head, HEAD_REQUEST_KEY, headVaryParams, clientModules, null, // This pass only measures gzip sizes for inlining hints; fallback-ness | ||
| // doesn't affect size, so pass false. | ||
| false); | ||
| const [, headBuffer] = await renderSegmentPrefetch(buildId, staleTimeIterable, head, HEAD_REQUEST_KEY, initialRSCPayload.h, rootVaryParamsIterable, clientModules, null, // Fallback-ness doesn't affect size, so pass false. | ||
| false, needsRuntimeRequest, shellStageRelease); | ||
| const headGzipSize = await getGzipSize(headBuffer); | ||
@@ -186,3 +305,3 @@ // Mutable accumulator: the first segment that accepts the head sets this | ||
| // Walk the tree with the parent-first, child-decides algorithm. | ||
| const { node } = await collectPrefetchHintsImpl(flightRouterState, buildId, staleTime, seedData, clientModules, ROOT_SEGMENT_REQUEST_KEY, null, maxSize, maxBundleSize, headGzipSize, headInlineState, subtreeHasRuntimePrefetch, rootVaryParamsIterable); | ||
| const { node } = await collectPrefetchHintsImpl(flightRouterState, buildId, staleTimeIterable, seedData, clientModules, ROOT_SEGMENT_REQUEST_KEY, null, baseHints, maxSize, maxBundleSize, headGzipSize, headInlineState, subtreeHasRuntimePrefetch, rootVaryParamsIterable, needsRuntimeRequest, shellStageRelease); | ||
| if (!headInlineState.inlined) { | ||
@@ -220,7 +339,9 @@ // No page could accept the head. Set HeadOutlined on the root so the | ||
| // parent) in a single pass. | ||
| async function collectPrefetchHintsImpl(route, buildId, staleTime, seedData, clientModules, // TODO: Consider persisting the computed requestKey into the hints output | ||
| async function collectPrefetchHintsImpl(route, buildId, staleTimeIterable, seedData, clientModules, // TODO: Consider persisting the computed requestKey into the hints output | ||
| // so it doesn't need to be recomputed during the build. This might also | ||
| // suggest renaming prefetch-hints.json to something like | ||
| // segment-manifest.json, since it would contain more than just hints. | ||
| requestKey, parentGzipSize, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable) { | ||
| requestKey, parentGzipSize, // Hints every node starts from (the page-global static-prefetch-attempt | ||
| // hint); the inlining bits computed here are OR'd on top. | ||
| baseHints, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable, needsRuntimeRequest, shellStageRelease) { | ||
| // Check if static prefetching is disabled for this segment (runtime | ||
@@ -238,5 +359,4 @@ // prefetch or instant = false). Such segments act as transparent | ||
| if (!isStaticPrefetchDisabled && seedData !== null) { | ||
| const varyParams = readVaryParams(seedData[4], rootVaryParamsIterable); | ||
| const [, buffer] = await renderSegmentPrefetch(buildId, staleTime, seedData[0], requestKey, varyParams, clientModules, null, // Size-measurement pass only; fallback-ness is irrelevant here. | ||
| false); | ||
| const [, buffer] = await renderSegmentPrefetch(buildId, staleTimeIterable, seedData[0], requestKey, seedData[4], rootVaryParamsIterable, clientModules, null, // Size-measurement pass only; fallback-ness is irrelevant here. | ||
| false, needsRuntimeRequest, shellStageRelease); | ||
| currentGzipSize = await getGzipSize(buffer); | ||
@@ -278,4 +398,4 @@ } | ||
| const sizeToOfferChild = isStaticPrefetchDisabled ? parentGzipSize : sizeToInline; | ||
| const childResult = await collectPrefetchHintsImpl(childRoute, buildId, staleTime, childSeedData, clientModules, childRequestKey, // Once a child has accepted us, stop offering to remaining siblings. | ||
| didInlineIntoChild ? null : sizeToOfferChild, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable); | ||
| const childResult = await collectPrefetchHintsImpl(childRoute, buildId, staleTimeIterable, childSeedData, clientModules, childRequestKey, // Once a child has accepted us, stop offering to remaining siblings. | ||
| didInlineIntoChild ? null : sizeToOfferChild, baseHints, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable, needsRuntimeRequest, shellStageRelease); | ||
| if (slots === null) { | ||
@@ -306,3 +426,3 @@ slots = {}; | ||
| // data is included in the accepting child's response instead. | ||
| let hints = 0; | ||
| let hints = baseHints; | ||
| if (didInlineIntoChild) { | ||
@@ -389,2 +509,23 @@ hints |= PrefetchHint.InlinedIntoChild; | ||
| } | ||
| // Mirrors the route tree's shape with the same hints on every node. Used by | ||
| // collectPrefetchHints when prefetch inlining is disabled: there are no sizes | ||
| // to measure, but the static-prefetch-attempt hint still needs a manifest | ||
| // tree — the client reads the bit per node, and the runtime hint merging | ||
| // (createFlightRouterStateFromLoaderTree) walks the manifest tree in parallel | ||
| // with the loader tree, so a bit that's missing from a node never reaches the | ||
| // corresponding segment. | ||
| function createUniformHintTree(route, hints) { | ||
| let slots = null; | ||
| const children = route[1]; | ||
| for(const parallelRouteKey in children){ | ||
| if (slots === null) { | ||
| slots = {}; | ||
| } | ||
| slots[parallelRouteKey] = createUniformHintTree(children[parallelRouteKey], hints); | ||
| } | ||
| return { | ||
| hints, | ||
| slots | ||
| }; | ||
| } | ||
| // We use gzip size rather than raw size because it better reflects the actual | ||
@@ -404,3 +545,3 @@ // transfer cost. The inlining trade-off is about whether the overhead of an | ||
| } | ||
| async function PrefetchTreeData({ isClientParamParsingEnabled, fullPageDataBuffer, serverConsumerManifest, clientModules, staleTime, segmentTasks, onCompletedProcessingRouteTree, prefetchInlining, hints, isUpgradeableISRFallback }) { | ||
| async function PrefetchTreeData({ isClientParamParsingEnabled, pageDataStream, serverConsumerManifest, clientModules, staleTime, segmentTasks, onCompletedProcessingRouteTree, prefetchInlining, hints, isUpgradeableISRFallback, runtimeDataAccessed, shellStageRelease }) { | ||
| // We're currently rendering a Flight response for the route tree prefetch. | ||
@@ -411,3 +552,9 @@ // Inside this component, decode the Flight stream for the whole page. This is | ||
| // TODO: React needs a better way to do this. Needed for Server Actions, too. | ||
| const initialRSCPayload = await createFromReadableStream(createUnclosingPrefetchStream(streamFromBuffer(fullPageDataBuffer)), { | ||
| // | ||
| // This is the decode that everything downstream reads from: the route tree | ||
| // walk below and, through it, every segment task. When staged, the values | ||
| // extracted here hold pending references at the param-dependent holes; the | ||
| // shell byte prefix carries the full router tree and seed-data skeleton, so | ||
| // the root resolves from the prefix alone (the rest arrives at the release). | ||
| const initialRSCPayload = await createFromReadableStream(pageDataStream, { | ||
| findSourceMapURL, | ||
@@ -421,9 +568,14 @@ serverConsumerManifest | ||
| const { buildId, flightRouterState, seedData, head } = flightData; | ||
| // Root params are emitted once at the top level; readVaryParams unions them | ||
| // into the head, and the iterable is threaded down so every segment below | ||
| // unions it too. The iterables should be drained to completion by now (the | ||
| // stream is buffered); a hanging one reads as the params yielded so far. | ||
| // Root params are forwarded once at the top level of each segment | ||
| // response, same as the page response's own root vary params; the client | ||
| // unions them into each segment's set at read time. | ||
| const rootVaryParamsIterable = initialRSCPayload.r ?? null; | ||
| // Extract the head vary params from the decoded response. | ||
| const headVaryParams = readVaryParams(initialRSCPayload.h, rootVaryParamsIterable); | ||
| // The page's staleTime iterable, forwarded into each segment response. When | ||
| // Cache Components is off the page carries no `s`, so wrap the eager value. | ||
| const staleTimeIterable = initialRSCPayload.s ?? createStaleTimeIterable(staleTime); | ||
| // The page's runtime-data-access flag, forwarded into each segment | ||
| // response's `needsRuntimeRequest`. When the page carries no `u` (e.g. | ||
| // legacy render paths), wrap the flag the caller read from the warm-up | ||
| // decode in an already-resolved promise. | ||
| const needsRuntimeRequest = initialRSCPayload.u ?? Promise.resolve(runtimeDataAccessed); | ||
| // Only applies when prefetch inlining is enabled — the client doesn't | ||
@@ -438,10 +590,10 @@ // know to look for the head inside a page's response otherwise. | ||
| rsc: head, | ||
| varyParams: headVaryParams, | ||
| varyParams: initialRSCPayload.h, | ||
| next: null | ||
| } : null; | ||
| const tree = collectSegmentDataImpl(isClientParamParsingEnabled, flightRouterState, buildId, staleTime, seedData, clientModules, ROOT_SEGMENT_REQUEST_KEY, segmentTasks, prefetchInlining, hints, null, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback); | ||
| const tree = collectSegmentDataImpl(isClientParamParsingEnabled, flightRouterState, buildId, staleTimeIterable, seedData, clientModules, ROOT_SEGMENT_REQUEST_KEY, segmentTasks, prefetchInlining, hints, null, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease); | ||
| // Spawn a task to produce a prefetch response for the "head" segment, | ||
| // unless it was inlined into a page's bundle. | ||
| if (!headIsInlined) { | ||
| segmentTasks.push(waitAtLeastOneReactRenderTask().then(()=>renderSegmentPrefetch(buildId, staleTime, head, HEAD_REQUEST_KEY, headVaryParams, clientModules, null, isUpgradeableISRFallback))); | ||
| segmentTasks.push(waitAtLeastOneReactRenderTask().then(()=>renderSegmentPrefetch(buildId, staleTimeIterable, head, HEAD_REQUEST_KEY, initialRSCPayload.h, rootVaryParamsIterable, clientModules, null, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease))); | ||
| } | ||
@@ -462,3 +614,3 @@ // Notify the abort controller that we're done processing the route tree. | ||
| } | ||
| function collectSegmentDataImpl(isClientParamParsingEnabled, route, buildId, staleTime, seedData, clientModules, requestKey, segmentTasks, prefetchInlining, hintTree, parentBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback) { | ||
| function collectSegmentDataImpl(isClientParamParsingEnabled, route, buildId, staleTimeIterable, seedData, clientModules, requestKey, segmentTasks, prefetchInlining, hintTree, parentBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease) { | ||
| // Union the hints already embedded in the FlightRouterState with the | ||
@@ -476,5 +628,5 @@ // separately-computed build-time hints. During the initial build, the | ||
| const prefetchHints = ((route[4] ?? 0) | (hintTree !== null ? hintTree.hints : 0)) & ~PrefetchHint.InliningHintsStale; | ||
| // Determine which params this segment varies on, unioning in the | ||
| // response-level root params. | ||
| const varyParams = readVaryParams(seedData !== null ? seedData[4] : null, rootVaryParamsIterable); | ||
| // The params this segment's own output varies on, forwarded into its | ||
| // response as-is. Root params are forwarded separately, once per response. | ||
| const varyParams = seedData !== null ? seedData[4] : null; | ||
| // If static prefetching is disabled for this segment (runtime prefetch or | ||
@@ -519,3 +671,3 @@ // instant = false), it still participates in the bundle chain but with | ||
| } | ||
| segmentTasks.push(waitAtLeastOneReactRenderTask().then(()=>renderSegmentPrefetch(buildId, staleTime, rsc, requestKey, varyParams, clientModules, bundle, isUpgradeableISRFallback))); | ||
| segmentTasks.push(waitAtLeastOneReactRenderTask().then(()=>renderSegmentPrefetch(buildId, staleTimeIterable, rsc, requestKey, varyParams, rootVaryParamsIterable, clientModules, bundle, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease))); | ||
| } | ||
@@ -535,3 +687,3 @@ // childBundle stays null — reset the accumulator for children. | ||
| const childHintTree = hintTree !== null && hintTree.slots !== null ? hintTree.slots[parallelRouteKey] ?? null : null; | ||
| const childTree = collectSegmentDataImpl(isClientParamParsingEnabled, childRoute, buildId, staleTime, childSeedData, clientModules, childRequestKey, segmentTasks, prefetchInlining, childHintTree, childBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback); | ||
| const childTree = collectSegmentDataImpl(isClientParamParsingEnabled, childRoute, buildId, staleTimeIterable, childSeedData, clientModules, childRequestKey, segmentTasks, prefetchInlining, childHintTree, childBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease); | ||
| if (slotMetadata === null) { | ||
@@ -567,90 +719,201 @@ slotMetadata = {}; | ||
| } | ||
| async function renderSegmentPrefetch(buildId, staleTime, rsc, requestKey, varyParams, clientModules, bundle, isUpgradeableISRFallback) { | ||
| // Build the SegmentPrefetch for the terminal (requested) segment. | ||
| // The terminal always has non-null rsc data — disabled segments are | ||
| // skipped by the caller and don't reach this function. | ||
| const selfPrefetch = { | ||
| /** | ||
| * Renders one segment prefetch response, and with it a shell byte boundary | ||
| * (`a`) — the per-segment analogue of the route-level `a`. The boundary lets a | ||
| * client later truncate the buffered response and re-decode the prefix into | ||
| * the segment's shell variant (param-dependent content reduced to pending | ||
| * references) without a second request. | ||
| * | ||
| * That boundary is the whole reason this isn't a plain re-serialize. A shell | ||
| * is a temporal property of the staged page render, already collapsed by the | ||
| * time the page stream is decoded, so it can't be recovered from the settled | ||
| * values. Instead the response is serialized against a staged decode of the | ||
| * page (the caller drip-feeds it in two stages): the shell rows flush first, | ||
| * and the byte count when the rest is released is the boundary. | ||
| * | ||
| * Uses the streaming renderer, not `prerender`, because the boundary must be | ||
| * observed mid-stream — `prerender` only exposes its prelude once finished. | ||
| */ async function renderSegmentPrefetch(buildId, staleTime, rsc, requestKey, varyParams, rootVaryParams, clientModules, bundle, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease) { | ||
| const streamInfoStage = createPromiseWithResolvers(); | ||
| // Build the data array by walking the bundle list, terminal (requested) | ||
| // segment first. Always an array, even for a single segment; the terminal | ||
| // always has non-null rsc — disabled segments are skipped by the caller. | ||
| const data = []; | ||
| let node = { | ||
| rsc, | ||
| isPartial: await isPartialRSCData(rsc, clientModules), | ||
| staleTime, | ||
| varyParams | ||
| varyParams, | ||
| next: bundle | ||
| }; | ||
| // Build the data array. Always an array, even for a single segment. | ||
| const data = [ | ||
| selfPrefetch | ||
| ]; | ||
| if (bundle !== null) { | ||
| // Walk the bundle linked list and append each entry to the array. | ||
| let node = bundle; | ||
| while(node !== null){ | ||
| if (node.rsc !== null) { | ||
| data.push({ | ||
| rsc: node.rsc, | ||
| isPartial: await isPartialRSCData(node.rsc, clientModules), | ||
| staleTime, | ||
| varyParams: node.varyParams | ||
| while(node !== null){ | ||
| const elementRsc = node.rsc; | ||
| if (elementRsc === null) { | ||
| // Static prefetching disabled (runtime prefetch or instant=false): a | ||
| // null placeholder keeps the array aligned with the client's bundle | ||
| // list, which skips a cache entry for the slot. | ||
| data.push(null); | ||
| } else { | ||
| // We can determine if a segment contains only partial data if it takes | ||
| // longer than a task to encode, because dynamic data is encoded as an | ||
| // infinite promise. We must do this in a separate Flight prerender from | ||
| // the one that actually generates the prefetch stream because we need | ||
| // to include the result in the stream itself. | ||
| const contentIsComplete = new Promise(async (resolve)=>{ | ||
| // Wait for the input stream to be fully unblocked before checking if | ||
| // the data can be decoded synchronously. | ||
| await streamInfoStage.promise; | ||
| // If the data is fully static, this will resolve synchronously. | ||
| // Otherwise, the promise stays unresolved forever, and so does | ||
| // whatever field it's encoded into in the outer response. | ||
| await prerender(elementRsc, clientModules, { | ||
| filterStackFrame, | ||
| onError () {} | ||
| }); | ||
| } else { | ||
| // This segment has static prefetching disabled (runtime prefetch | ||
| // or instant = false). Emit null as a placeholder so the array | ||
| // indices stay aligned with the client's SegmentBundle linked | ||
| // list. The client will skip creating a cache entry for this slot. | ||
| data.push(null); | ||
| } | ||
| node = node.next; | ||
| resolve(); | ||
| }); | ||
| data.push({ | ||
| rsc: elementRsc, | ||
| isPartial: contentIsComplete, | ||
| staleTime, | ||
| varyParams: node.varyParams | ||
| }); | ||
| } | ||
| node = node.next; | ||
| } | ||
| const responseKey = requestKey === ROOT_SEGMENT_REQUEST_KEY ? '/_index' : requestKey; | ||
| // `a` (see SegmentPrefetchResponse['a']) is resolved below, once the shell | ||
| // stage's bytes have been counted. | ||
| let totalByteLength = 0; | ||
| const shellByteOffset = createPromiseWithResolvers(); | ||
| // Wrap in the response envelope with the build ID at the top level. | ||
| // isUpgradeableISRFallback tells the client whether this came from a fallback shell | ||
| // render (so it knows to retry — a more complete version may become | ||
| // available once the server's background regeneration finishes). | ||
| const payload = { | ||
| buildId: buildId ?? '', | ||
| data, | ||
| isUpgradeableISRFallback | ||
| isUpgradeableISRFallback, | ||
| a: shellByteOffset.promise, | ||
| rootVaryParams, | ||
| needsRuntimeRequest | ||
| }; | ||
| // Since all we're doing is decoding and re-encoding a cached prerender, if | ||
| // it takes longer than a microtask, it must because of hanging promises | ||
| // caused by dynamic data. Abort the stream at the end of the current task. | ||
| const abortController = new AbortController(); | ||
| waitAtLeastOneReactRenderTask().then(()=>abortController.abort()); | ||
| const { prelude: segmentStream } = await prerender(payload, clientModules, { | ||
| const segmentStream = renderToReadableStream(payload, clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError: onSegmentPrerenderError | ||
| onError (error) { | ||
| if (abortController.signal.aborted) { | ||
| // Expected: aborting the render "errors" every reference that is | ||
| // still pending, i.e. the dynamic holes. The corresponding error | ||
| // rows are discarded below. | ||
| return undefined; | ||
| } | ||
| return onSegmentPrerenderError(error); | ||
| } | ||
| }); | ||
| const segmentBuffer = await streamToBuffer(segmentStream); | ||
| if (requestKey === ROOT_SEGMENT_REQUEST_KEY) { | ||
| return [ | ||
| '/_index', | ||
| segmentBuffer | ||
| ]; | ||
| // Consume the stream as it's emitted, counting bytes so the shell boundary | ||
| // can be measured. Reads settle within a microtask of each enqueue, so by | ||
| // the time the release resolves (in a task after the renderer's last | ||
| // flush), every byte the renderer has emitted has been counted. | ||
| const reader = segmentStream.getReader(); | ||
| const chunksPromise = new Promise(async (resolve)=>{ | ||
| const chunks = []; | ||
| while(true){ | ||
| const { done, value } = await reader.read(); | ||
| if (done) { | ||
| break; | ||
| } | ||
| if (abortController.signal.aborted) { | ||
| continue; | ||
| } | ||
| chunks.push(value); | ||
| totalByteLength += value.byteLength; | ||
| } | ||
| resolve(chunks); | ||
| }); | ||
| // The release's value is true when the page's shell is its entire static | ||
| // response — then so is every segment's, so `a` is null (no separate shell | ||
| // to extract). Otherwise we measure. | ||
| const shellIsFullResponse = await shellStageRelease; | ||
| // The shell stage is complete: everything the render can emit from the shell | ||
| // prefix has flushed, so this is the shell's byte length. | ||
| const byteLengthAfterShellStage = totalByteLength; | ||
| // Wait one task for the rest of the segment data (past the page's own shell | ||
| // boundary) to flush, per the timing rule: one macrotask after the release | ||
| // enqueues it into the input decode, the render has emitted all of it. | ||
| await waitAtLeastOneReactRenderTask(); | ||
| // Resolve `a`: null when the page said its shell is the whole response | ||
| // (shellIsFullResponse) — then so is every segment's. Otherwise resolve the | ||
| // measured boundary, even if no segment *content* follows it: the | ||
| // stage-dependent metadata (`staleTime`, `needsRuntimeRequest`) always | ||
| // lands its post-shell values and completion rows after this point, so a | ||
| // truncated decode is meaningful for every segment of a staged page. When | ||
| // the page wasn't staged at all, the release resolved before any bytes | ||
| // flushed and the measured boundary falls out as 0, the "no shell" | ||
| // sentinel. | ||
| if (shellIsFullResponse) { | ||
| shellByteOffset.resolve(null); | ||
| } else { | ||
| return [ | ||
| requestKey, | ||
| segmentBuffer | ||
| ]; | ||
| shellByteOffset.resolve(byteLengthAfterShellStage); | ||
| } | ||
| // Now write the stream metadata (`a`, the `isPartial` promises, and a | ||
| // post-shell `needsRuntimeRequest` resolution). This is gated behind | ||
| // streamInfoStage so it lands strictly after the boundary measurement | ||
| // above — the post-shell values must not count as (or leak into) the | ||
| // shell prefix. | ||
| streamInfoStage.resolve(); | ||
| // Wait for the metadata rows to flush before halting — two macrotasks, | ||
| // each a distinct hop: | ||
| // 1. streamInfoStage unblocks the completeness probe renders; a static | ||
| // segment's probe resolves within this task (a partial one never does, | ||
| // which is how it stays pending → read as partial). | ||
| // 2. those resolutions (and the already-resolved `a`) ping the render, | ||
| // which emits their rows; the consumer reads that chunk here. | ||
| // Halting after only the first hop would drop the not-yet-flushed metadata. | ||
| await waitAtLeastOneReactRenderTask(); | ||
| await waitAtLeastOneReactRenderTask(); | ||
| // We're done writing, so we can abort the stream. | ||
| abortController.abort(); | ||
| return [ | ||
| responseKey, | ||
| Buffer.concat(await chunksPromise) | ||
| ]; | ||
| } | ||
| async function isPartialRSCData(rsc, clientModules) { | ||
| // We can determine if a segment contains only partial data if it takes longer | ||
| // than a task to encode, because dynamic data is encoded as an infinite | ||
| // promise. We must do this in a separate Flight prerender from the one that | ||
| // actually generates the prefetch stream because we need to include | ||
| // `isPartial` in the stream itself. | ||
| let isPartial = false; | ||
| const abortController = new AbortController(); | ||
| waitAtLeastOneReactRenderTask().then(()=>{ | ||
| // If we haven't yet finished the outer task, then it must be because we | ||
| // accessed dynamic data. | ||
| isPartial = true; | ||
| abortController.abort(); | ||
| }); | ||
| await prerender(rsc, clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError () {} | ||
| }); | ||
| return isPartial; | ||
| /** | ||
| * Reads the page's runtime-data-access flag (the payload's `u`) from a decode | ||
| * of the fully-settled page buffer. Because every byte is present, the | ||
| * promise's row (if the render emitted one) is already visible on its | ||
| * thenable status, so this never blocks — the same trick the client cache | ||
| * uses to read staleTime from a buffered response. | ||
| * | ||
| * - fulfilled: the recorded flag. | ||
| * - pending: `false`. A successful render always settles the flag (prerender | ||
| * completion resolves `false`), so a pending row can only appear in an | ||
| * aborted render's buffer, where it means no access was recorded before | ||
| * the abort. | ||
| * - rejected: `true`, conservatively — an abort errors rows that were still | ||
| * pending when it happened. | ||
| */ function readRuntimeDataAccessed(runtimeDataAccessed) { | ||
| const promise = runtimeDataAccessed; | ||
| // Force Flight to unwrap a received-but-not-yet-settled row. | ||
| promise.then(ignoreChunk, ignoreChunk); | ||
| switch(promise.status){ | ||
| case 'fulfilled': | ||
| return promise.value === true; | ||
| case 'rejected': | ||
| return true; | ||
| case undefined: | ||
| default: | ||
| return false; | ||
| } | ||
| } | ||
| function ignoreChunk() {} | ||
| // Wraps a known staleTime value in the same async-iterable shape as the page | ||
| // response's `s`, so segment responses carry staleTime uniformly (and | ||
| // rewindably) whether or not Cache Components supplied a real `s` iterable. | ||
| // Re-consumable: each consumer gets a fresh generator (one segment response's | ||
| // render, and there can be several). | ||
| function createStaleTimeIterable(staleTime) { | ||
| return { | ||
| async *[Symbol.asyncIterator] () { | ||
| yield staleTime; | ||
| } | ||
| }; | ||
| } | ||
| function createUnclosingPrefetchStream(originalFlightStream) { | ||
@@ -657,0 +920,0 @@ // When PPR is enabled, prefetch streams may contain references that never |
@@ -27,3 +27,3 @@ /** | ||
| import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { ClientHookDynamicError, isClientHookDynamicError, makeClientHookHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { ClientHookDynamicError, isClientHookDynamicError, makeClientHookHangingPromise, trackRuntimeDataAccessed } from '../dynamic-rendering-utils'; | ||
| import { METADATA_BOUNDARY_NAME, VIEWPORT_BOUNDARY_NAME, OUTLET_BOUNDARY_NAME, ROOT_LAYOUT_BOUNDARY_NAME } from '../../lib/framework/boundary-constants'; | ||
@@ -219,2 +219,10 @@ import { scheduleOnNextTick } from '../../lib/scheduler'; | ||
| */ export function abortAndThrowOnSynchronousRequestDataAccess(route, expression, errorWithStack, prerenderStore) { | ||
| // The synchronously accessed request data would have been available during | ||
| // a runtime prerender, which would have rendered past this point instead of | ||
| // aborting — so a runtime prefetch would produce more content than this | ||
| // render. Record that, same as when request data access creates a hanging | ||
| // promise (see makeRuntimeHangingPromise). Unlike | ||
| // `abortOnSynchronousPlatformIOAccess`, which aborts a runtime prerender | ||
| // all the same and therefore must not record anything. | ||
| trackRuntimeDataAccessed(prerenderStore); | ||
| const prerenderSignal = prerenderStore.controller.signal; | ||
@@ -221,0 +229,0 @@ if (prerenderSignal.aborted === false) { |
@@ -216,3 +216,3 @@ import { InvariantError } from '../../shared/lib/invariant-error'; | ||
| const promise = process.env.NODE_ENV === 'development' ? makeDevtoolsIOPromiseFromIOTrigger(stagePromise, displayName, resolvedValue) : stagePromise.then(()=>resolvedValue); | ||
| // Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked. | ||
| // Analogously to `makeDynamicHangingPromise`, we might reject this promise if the signal is invoked. | ||
| // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it). | ||
@@ -219,0 +219,0 @@ // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/app-render/staged-rendering.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n Before = 1,\n //\n ShellStatic = 11,\n Static = 13,\n //\n ShellRuntime = 21,\n Runtime = 23,\n //\n Dynamic = 30,\n //\n Abandoned = 40,\n}\n\nexport type AdvanceableRenderStage = Exclude<\n RenderStage,\n RenderStage.Before | RenderStage.Abandoned\n>\n\nexport const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [\n RenderStage.ShellStatic,\n RenderStage.Static,\n //\n RenderStage.ShellRuntime,\n RenderStage.Runtime,\n //\n RenderStage.Dynamic,\n]\n\nexport function getNextStage(\n stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>\n) {\n return RENDER_STAGE_ADVANCE_ORDER[\n RENDER_STAGE_ADVANCE_ORDER.indexOf(stage) + 1\n ]\n}\n\nexport function isAdvanceableRenderStage(\n stage: RenderStage\n): stage is AdvanceableRenderStage {\n return RenderStage.Before < stage && stage <= RenderStage.Dynamic\n}\n\nexport enum SyncIOMode {\n /** Sync IO does not error in any stage. */\n Untracked = 1,\n /** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */\n AllowedInRuntimeOrDynamic = 2,\n /** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */\n AllowedInDynamic = 3,\n}\n\nexport class StagedRenderingController {\n private abortSignal: AbortSignal | null\n private abandonController: AbortController | null\n private syncIOMode: SyncIOMode\n public readonly finalStage: AdvanceableRenderStage | null\n\n currentStage: RenderStage = RenderStage.Before\n\n syncInterruptReason: Error | null = null\n\n triggers: Record<AdvanceableRenderStage, StageTrigger> = {\n [RenderStage.ShellStatic]: createStageTrigger(),\n [RenderStage.Static]: createStageTrigger(),\n //\n [RenderStage.ShellRuntime]: createStageTrigger(),\n [RenderStage.Runtime]: createStageTrigger(),\n //\n [RenderStage.Dynamic]: createStageTrigger(),\n }\n\n constructor({\n abortSignal,\n abandonController,\n syncIO,\n finalStage,\n }: {\n abortSignal: AbortSignal | null\n abandonController: AbortController | null\n syncIO: SyncIOMode\n finalStage: AdvanceableRenderStage | null\n }) {\n this.abortSignal = abortSignal\n this.abandonController = abandonController\n this.syncIOMode = syncIO\n this.finalStage = finalStage\n\n if (abortSignal) {\n abortSignal.addEventListener(\n 'abort',\n () => {\n // Reject all stage promises that haven't already been resolved.\n // `cancelStageTrigger` is a noop if the trigger already resolved.\n const { reason } = abortSignal\n for (const trigger of Object.values(this.triggers)) {\n cancelStageTrigger(trigger, reason)\n }\n },\n { once: true }\n )\n }\n\n if (abandonController) {\n abandonController.signal.addEventListener(\n 'abort',\n () => {\n this.abandonRender()\n },\n { once: true }\n )\n }\n }\n\n onStage(stage: AdvanceableRenderStage, callback: () => void) {\n addSyncTriggerListener(this.triggers[stage], callback)\n }\n\n shouldTrackSyncInterrupt(): boolean {\n if (this.syncIOMode === SyncIOMode.Untracked) {\n return false\n }\n\n switch (this.currentStage) {\n case RenderStage.Before:\n // If we haven't started the render yet, it can't be interrupted.\n return false\n case RenderStage.ShellStatic:\n case RenderStage.Static:\n return true\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n switch (this.syncIOMode) {\n case SyncIOMode.AllowedInRuntimeOrDynamic: {\n // Before `partialPrefetching`: Sync IO only errors in static stages.\n return false\n }\n case SyncIOMode.AllowedInDynamic: {\n return true\n }\n }\n // NOT a fallthrough, but eslint doesn't understand that\n }\n case RenderStage.Dynamic:\n case RenderStage.Abandoned:\n return false\n default:\n this.currentStage satisfies never\n return false\n }\n }\n\n /** Note: only call this if `shouldTrackSyncInterrupt()` returned true */\n syncInterruptCurrentStageWithReason(reason: Error) {\n const { currentStage } = this\n if (\n currentStage === RenderStage.Before ||\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Not interruptible. Defensive noop.\n return\n }\n\n // If Sync IO occurs during an abandonable render, we trigger the abandon.\n // The abandon listener will call abandonRender which advances through\n // stages to let caches fill before marking as Abandoned.\n if (this.abandonController) {\n this.abandonController.abort()\n return\n }\n\n if (this.abortSignal) {\n // If this is an abortable render, we capture the interruption reason and stop advancing.\n // We don't release any more promises.\n // The caller is expected to abort the signal.\n this.syncInterruptReason = reason\n this.currentStage = RenderStage.Abandoned\n return\n }\n\n // If we're in a non-abandonable & non-abortable render,\n // we need to advance to the Dynamic stage and capture the interruption reason.\n // (in dev, this will be the restarted render)\n this.syncInterruptReason = reason\n this.advanceStage(RenderStage.Dynamic)\n }\n\n getSyncInterruptReason() {\n return this.syncInterruptReason\n }\n\n getStaticStageEndTime() {\n // The Static stage ends when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Static)].triggeredAt ?? Infinity\n )\n }\n\n getRuntimeStageEndTime() {\n // The Runtime stage ended when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Runtime)].triggeredAt ?? Infinity\n )\n }\n\n private abandonRender() {\n // In staged rendering, only the initial render is abandonable.\n // We can abandon the initial render if\n // 1. We notice a cache miss, and need to wait for caches to fill\n // 2. A sync IO error occurs, and the render should be interrupted\n // (this might be a lazy intitialization of a module,\n // so we still want to restart in this case and see if it still occurs)\n // In either case, we'll be doing another render after this one,\n // so we only want to unblock the next stage, not Dynamic, because\n // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n\n const { currentStage } = this\n\n if (currentStage === RenderStage.Before) {\n throw new InvariantError(\n \"A render that hasn't started yet cannot be abandoned\"\n )\n }\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // We shouldn't ever trigger an abandon in these. Defensive noop.\n return\n }\n\n // Resolve all stages after the current one, up to runtime (excluding dynamic)\n const nextStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const dynamicStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(\n RenderStage.Dynamic\n )\n for (let i = nextStageIx; i < dynamicStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n\n this.currentStage = RenderStage.Abandoned\n }\n\n advanceStage(targetStage: AdvanceableRenderStage) {\n if (this.finalStage !== null && targetStage > this.finalStage) {\n throw new InvariantError(\n `Attempted to advance to stage ${RenderStage[targetStage]} but the render is limited to ${RenderStage[this.finalStage]}`\n )\n }\n const { currentStage } = this\n\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Terminal stages, nowhere left to advance.\n return\n }\n\n // If we're already at the target stage or beyond, do nothing.\n if (targetStage <= currentStage) {\n return\n }\n\n this.currentStage = targetStage\n\n // Resolve all stages between the current stage and the target.\n const nextStageIx =\n currentStage === RenderStage.Before\n ? 0\n : RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const targetStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(targetStage)\n for (let i = nextStageIx; i <= targetStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n }\n\n private resolveStage(stage: AdvanceableRenderStage) {\n fireStageTrigger(this.triggers[stage])\n }\n\n private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n return this.triggers[stage].promise\n }\n\n waitForStage(stage: AdvanceableRenderStage) {\n return this.getStagePromise(stage)\n }\n\n delayUntilStage<T>(\n stage: AdvanceableRenderStage,\n displayName: string | undefined,\n resolvedValue: T\n ): Promise<T> {\n const stagePromise = this.getStagePromise(stage)\n\n const promise =\n process.env.NODE_ENV === 'development'\n ? makeDevtoolsIOPromiseFromIOTrigger(\n stagePromise,\n displayName,\n resolvedValue\n )\n : stagePromise.then(() => resolvedValue)\n\n // Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked.\n // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n if (this.abortSignal) {\n promise.catch(ignoreReject)\n }\n return promise\n }\n}\n\nfunction ignoreReject() {}\n\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger<T>(\n ioTrigger: Promise<any>,\n displayName: string | undefined,\n resolvedValue: T\n): Promise<T> {\n // If we create a `new Promise` and give it a displayName\n // (with no userspace code above us in the stack)\n // React Devtools will use it as the IO cause when determining \"suspended by\".\n // In particular, it should shadow any inner IO that resolved/rejected the promise\n // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n const promise = new Promise<T>((resolve, reject) => {\n ioTrigger.then(resolve.bind(null, resolvedValue), reject)\n })\n if (displayName !== undefined) {\n // @ts-expect-error\n promise.displayName = displayName\n }\n return promise\n}\n\ntype StageTrigger = {\n state: 'pending' | 'triggered' | 'cancelled'\n triggeredAt: number | null\n promise: Promise<void>\n _listeners: Array<() => void>\n _resolvePromise: () => void\n _rejectPromise: (reason: unknown) => void\n}\n\nfunction addSyncTriggerListener(trigger: StageTrigger, listener: () => void) {\n if (trigger.state === 'pending') {\n trigger._listeners.push(listener)\n } else {\n listener()\n }\n}\n\nfunction createStageTrigger(): StageTrigger {\n const { promise, resolve, reject } = createPromiseWithResolvers<void>()\n return {\n state: 'pending',\n triggeredAt: null,\n promise,\n _listeners: [],\n _resolvePromise: resolve,\n _rejectPromise: reject,\n }\n}\n\nfunction fireStageTrigger(trigger: StageTrigger) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'triggered'\n trigger.triggeredAt = performance.now() + performance.timeOrigin\n try {\n const { _listeners: listeners } = trigger\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n listeners.length = 0\n } finally {\n trigger._resolvePromise()\n }\n}\n\nfunction cancelStageTrigger(trigger: StageTrigger, reason: unknown) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'cancelled'\n // we didn't trigger, so don't save `triggeredAt`.\n\n // We're not gonna fire the listeners, we may as well free them.\n trigger._listeners.length = 0\n\n // Suppress unhandled rejection warnings for promises that no one is awaiting.\n trigger.promise.catch(ignoreReject)\n trigger._rejectPromise(reason)\n}\n"],"names":["InvariantError","createPromiseWithResolvers","RenderStage","RENDER_STAGE_ADVANCE_ORDER","getNextStage","stage","indexOf","isAdvanceableRenderStage","SyncIOMode","StagedRenderingController","constructor","abortSignal","abandonController","syncIO","finalStage","currentStage","syncInterruptReason","triggers","createStageTrigger","syncIOMode","addEventListener","reason","trigger","Object","values","cancelStageTrigger","once","signal","abandonRender","onStage","callback","addSyncTriggerListener","shouldTrackSyncInterrupt","syncInterruptCurrentStageWithReason","abort","advanceStage","getSyncInterruptReason","getStaticStageEndTime","triggeredAt","Infinity","getRuntimeStageEndTime","nextStageIx","dynamicStageIx","i","resolveStage","targetStage","targetStageIx","fireStageTrigger","getStagePromise","promise","waitForStage","delayUntilStage","displayName","resolvedValue","stagePromise","process","env","NODE_ENV","makeDevtoolsIOPromiseFromIOTrigger","then","catch","ignoreReject","ioTrigger","Promise","resolve","reject","bind","undefined","listener","state","_listeners","push","_resolvePromise","_rejectPromise","performance","now","timeOrigin","listeners","length"],"mappings":"AAAA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,0BAA0B,QAAQ,0CAAyC;AAEpF,OAAO,IAAA,AAAKC,qCAAAA;;IAEV,EAAE;;;IAGF,EAAE;;;IAGF,EAAE;;IAEF,EAAE;;WAVQA;MAYX;AAOD,OAAO,MAAMC,6BAAuD;;;;;;CAQnE,CAAA;AAED,OAAO,SAASC,aACdC,KAA2D;IAE3D,OAAOF,0BAA0B,CAC/BA,2BAA2BG,OAAO,CAACD,SAAS,EAC7C;AACH;AAEA,OAAO,SAASE,yBACdF,KAAkB;IAElB,OAAOH,IAAqBG,SAASA;AACvC;AAEA,OAAO,IAAA,AAAKG,oCAAAA;IACV,yCAAyC;IAEzC,4FAA4F;IAE5F,iFAAiF;WALvEA;MAOX;AAED,OAAO,MAAMC;IAoBXC,YAAY,EACVC,WAAW,EACXC,iBAAiB,EACjBC,MAAM,EACNC,UAAU,EAMX,CAAE;aAxBHC;aAEAC,sBAAoC;aAEpCC,WAAyD;YACvD,IAAyB,EAAEC;YAC3B,IAAoB,EAAEA;YACtB,EAAE;YACF,IAA0B,EAAEA;YAC5B,IAAqB,EAAEA;YACvB,EAAE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;QACAkC,UAAUC,MAAM,GAAG;IACrB,SAAU;QACRxD,QAAQkD,eAAe;IACzB;AACF;AAEA,SAAS/C,mBAAmBH,OAAqB,EAAED,MAAe;IAChE,IAAIC,QAAQ+C,KAAK,KAAK,WAAW;QAC/B;IACF;IACA/C,QAAQ+C,KAAK,GAAG;IAChB,kDAAkD;IAElD,gEAAgE;IAChE/C,QAAQgD,UAAU,CAACQ,MAAM,GAAG;IAE5B,8EAA8E;IAC9ExD,QAAQ2B,OAAO,CAACW,KAAK,CAACC;IACtBvC,QAAQmD,cAAc,CAACpD;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/app-render/staged-rendering.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n Before = 1,\n //\n ShellStatic = 11,\n Static = 13,\n //\n ShellRuntime = 21,\n Runtime = 23,\n //\n Dynamic = 30,\n //\n Abandoned = 40,\n}\n\nexport type AdvanceableRenderStage = Exclude<\n RenderStage,\n RenderStage.Before | RenderStage.Abandoned\n>\n\nexport const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [\n RenderStage.ShellStatic,\n RenderStage.Static,\n //\n RenderStage.ShellRuntime,\n RenderStage.Runtime,\n //\n RenderStage.Dynamic,\n]\n\nexport function getNextStage(\n stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>\n) {\n return RENDER_STAGE_ADVANCE_ORDER[\n RENDER_STAGE_ADVANCE_ORDER.indexOf(stage) + 1\n ]\n}\n\nexport function isAdvanceableRenderStage(\n stage: RenderStage\n): stage is AdvanceableRenderStage {\n return RenderStage.Before < stage && stage <= RenderStage.Dynamic\n}\n\nexport enum SyncIOMode {\n /** Sync IO does not error in any stage. */\n Untracked = 1,\n /** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */\n AllowedInRuntimeOrDynamic = 2,\n /** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */\n AllowedInDynamic = 3,\n}\n\nexport class StagedRenderingController {\n private abortSignal: AbortSignal | null\n private abandonController: AbortController | null\n private syncIOMode: SyncIOMode\n public readonly finalStage: AdvanceableRenderStage | null\n\n currentStage: RenderStage = RenderStage.Before\n\n syncInterruptReason: Error | null = null\n\n triggers: Record<AdvanceableRenderStage, StageTrigger> = {\n [RenderStage.ShellStatic]: createStageTrigger(),\n [RenderStage.Static]: createStageTrigger(),\n //\n [RenderStage.ShellRuntime]: createStageTrigger(),\n [RenderStage.Runtime]: createStageTrigger(),\n //\n [RenderStage.Dynamic]: createStageTrigger(),\n }\n\n constructor({\n abortSignal,\n abandonController,\n syncIO,\n finalStage,\n }: {\n abortSignal: AbortSignal | null\n abandonController: AbortController | null\n syncIO: SyncIOMode\n finalStage: AdvanceableRenderStage | null\n }) {\n this.abortSignal = abortSignal\n this.abandonController = abandonController\n this.syncIOMode = syncIO\n this.finalStage = finalStage\n\n if (abortSignal) {\n abortSignal.addEventListener(\n 'abort',\n () => {\n // Reject all stage promises that haven't already been resolved.\n // `cancelStageTrigger` is a noop if the trigger already resolved.\n const { reason } = abortSignal\n for (const trigger of Object.values(this.triggers)) {\n cancelStageTrigger(trigger, reason)\n }\n },\n { once: true }\n )\n }\n\n if (abandonController) {\n abandonController.signal.addEventListener(\n 'abort',\n () => {\n this.abandonRender()\n },\n { once: true }\n )\n }\n }\n\n onStage(stage: AdvanceableRenderStage, callback: () => void) {\n addSyncTriggerListener(this.triggers[stage], callback)\n }\n\n shouldTrackSyncInterrupt(): boolean {\n if (this.syncIOMode === SyncIOMode.Untracked) {\n return false\n }\n\n switch (this.currentStage) {\n case RenderStage.Before:\n // If we haven't started the render yet, it can't be interrupted.\n return false\n case RenderStage.ShellStatic:\n case RenderStage.Static:\n return true\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n switch (this.syncIOMode) {\n case SyncIOMode.AllowedInRuntimeOrDynamic: {\n // Before `partialPrefetching`: Sync IO only errors in static stages.\n return false\n }\n case SyncIOMode.AllowedInDynamic: {\n return true\n }\n }\n // NOT a fallthrough, but eslint doesn't understand that\n }\n case RenderStage.Dynamic:\n case RenderStage.Abandoned:\n return false\n default:\n this.currentStage satisfies never\n return false\n }\n }\n\n /** Note: only call this if `shouldTrackSyncInterrupt()` returned true */\n syncInterruptCurrentStageWithReason(reason: Error) {\n const { currentStage } = this\n if (\n currentStage === RenderStage.Before ||\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Not interruptible. Defensive noop.\n return\n }\n\n // If Sync IO occurs during an abandonable render, we trigger the abandon.\n // The abandon listener will call abandonRender which advances through\n // stages to let caches fill before marking as Abandoned.\n if (this.abandonController) {\n this.abandonController.abort()\n return\n }\n\n if (this.abortSignal) {\n // If this is an abortable render, we capture the interruption reason and stop advancing.\n // We don't release any more promises.\n // The caller is expected to abort the signal.\n this.syncInterruptReason = reason\n this.currentStage = RenderStage.Abandoned\n return\n }\n\n // If we're in a non-abandonable & non-abortable render,\n // we need to advance to the Dynamic stage and capture the interruption reason.\n // (in dev, this will be the restarted render)\n this.syncInterruptReason = reason\n this.advanceStage(RenderStage.Dynamic)\n }\n\n getSyncInterruptReason() {\n return this.syncInterruptReason\n }\n\n getStaticStageEndTime() {\n // The Static stage ends when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Static)].triggeredAt ?? Infinity\n )\n }\n\n getRuntimeStageEndTime() {\n // The Runtime stage ended when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Runtime)].triggeredAt ?? Infinity\n )\n }\n\n private abandonRender() {\n // In staged rendering, only the initial render is abandonable.\n // We can abandon the initial render if\n // 1. We notice a cache miss, and need to wait for caches to fill\n // 2. A sync IO error occurs, and the render should be interrupted\n // (this might be a lazy intitialization of a module,\n // so we still want to restart in this case and see if it still occurs)\n // In either case, we'll be doing another render after this one,\n // so we only want to unblock the next stage, not Dynamic, because\n // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n\n const { currentStage } = this\n\n if (currentStage === RenderStage.Before) {\n throw new InvariantError(\n \"A render that hasn't started yet cannot be abandoned\"\n )\n }\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // We shouldn't ever trigger an abandon in these. Defensive noop.\n return\n }\n\n // Resolve all stages after the current one, up to runtime (excluding dynamic)\n const nextStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const dynamicStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(\n RenderStage.Dynamic\n )\n for (let i = nextStageIx; i < dynamicStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n\n this.currentStage = RenderStage.Abandoned\n }\n\n advanceStage(targetStage: AdvanceableRenderStage) {\n if (this.finalStage !== null && targetStage > this.finalStage) {\n throw new InvariantError(\n `Attempted to advance to stage ${RenderStage[targetStage]} but the render is limited to ${RenderStage[this.finalStage]}`\n )\n }\n const { currentStage } = this\n\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Terminal stages, nowhere left to advance.\n return\n }\n\n // If we're already at the target stage or beyond, do nothing.\n if (targetStage <= currentStage) {\n return\n }\n\n this.currentStage = targetStage\n\n // Resolve all stages between the current stage and the target.\n const nextStageIx =\n currentStage === RenderStage.Before\n ? 0\n : RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const targetStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(targetStage)\n for (let i = nextStageIx; i <= targetStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n }\n\n private resolveStage(stage: AdvanceableRenderStage) {\n fireStageTrigger(this.triggers[stage])\n }\n\n private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n return this.triggers[stage].promise\n }\n\n waitForStage(stage: AdvanceableRenderStage) {\n return this.getStagePromise(stage)\n }\n\n delayUntilStage<T>(\n stage: AdvanceableRenderStage,\n displayName: string | undefined,\n resolvedValue: T\n ): Promise<T> {\n const stagePromise = this.getStagePromise(stage)\n\n const promise =\n process.env.NODE_ENV === 'development'\n ? makeDevtoolsIOPromiseFromIOTrigger(\n stagePromise,\n displayName,\n resolvedValue\n )\n : stagePromise.then(() => resolvedValue)\n\n // Analogously to `makeDynamicHangingPromise`, we might reject this promise if the signal is invoked.\n // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n if (this.abortSignal) {\n promise.catch(ignoreReject)\n }\n return promise\n }\n}\n\nfunction ignoreReject() {}\n\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger<T>(\n ioTrigger: Promise<any>,\n displayName: string | undefined,\n resolvedValue: T\n): Promise<T> {\n // If we create a `new Promise` and give it a displayName\n // (with no userspace code above us in the stack)\n // React Devtools will use it as the IO cause when determining \"suspended by\".\n // In particular, it should shadow any inner IO that resolved/rejected the promise\n // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n const promise = new Promise<T>((resolve, reject) => {\n ioTrigger.then(resolve.bind(null, resolvedValue), reject)\n })\n if (displayName !== undefined) {\n // @ts-expect-error\n promise.displayName = displayName\n }\n return promise\n}\n\ntype StageTrigger = {\n state: 'pending' | 'triggered' | 'cancelled'\n triggeredAt: number | null\n promise: Promise<void>\n _listeners: Array<() => void>\n _resolvePromise: () => void\n _rejectPromise: (reason: unknown) => void\n}\n\nfunction addSyncTriggerListener(trigger: StageTrigger, listener: () => void) {\n if (trigger.state === 'pending') {\n trigger._listeners.push(listener)\n } else {\n listener()\n }\n}\n\nfunction createStageTrigger(): StageTrigger {\n const { promise, resolve, reject } = createPromiseWithResolvers<void>()\n return {\n state: 'pending',\n triggeredAt: null,\n promise,\n _listeners: [],\n _resolvePromise: resolve,\n _rejectPromise: reject,\n }\n}\n\nfunction fireStageTrigger(trigger: StageTrigger) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'triggered'\n trigger.triggeredAt = performance.now() + performance.timeOrigin\n try {\n const { _listeners: listeners } = trigger\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n listeners.length = 0\n } finally {\n trigger._resolvePromise()\n }\n}\n\nfunction cancelStageTrigger(trigger: StageTrigger, reason: unknown) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'cancelled'\n // we didn't trigger, so don't save `triggeredAt`.\n\n // We're not gonna fire the listeners, we may as well free them.\n trigger._listeners.length = 0\n\n // Suppress unhandled rejection warnings for promises that no one is awaiting.\n trigger.promise.catch(ignoreReject)\n trigger._rejectPromise(reason)\n}\n"],"names":["InvariantError","createPromiseWithResolvers","RenderStage","RENDER_STAGE_ADVANCE_ORDER","getNextStage","stage","indexOf","isAdvanceableRenderStage","SyncIOMode","StagedRenderingController","constructor","abortSignal","abandonController","syncIO","finalStage","currentStage","syncInterruptReason","triggers","createStageTrigger","syncIOMode","addEventListener","reason","trigger","Object","values","cancelStageTrigger","once","signal","abandonRender","onStage","callback","addSyncTriggerListener","shouldTrackSyncInterrupt","syncInterruptCurrentStageWithReason","abort","advanceStage","getSyncInterruptReason","getStaticStageEndTime","triggeredAt","Infinity","getRuntimeStageEndTime","nextStageIx","dynamicStageIx","i","resolveStage","targetStage","targetStageIx","fireStageTrigger","getStagePromise","promise","waitForStage","delayUntilStage","displayName","resolvedValue","stagePromise","process","env","NODE_ENV","makeDevtoolsIOPromiseFromIOTrigger","then","catch","ignoreReject","ioTrigger","Promise","resolve","reject","bind","undefined","listener","state","_listeners","push","_resolvePromise","_rejectPromise","performance","now","timeOrigin","listeners","length"],"mappings":"AAAA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SAASC,0BAA0B,QAAQ,0CAAyC;AAEpF,OAAO,IAAA,AAAKC,qCAAAA;;IA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AAK,KAAK,WAAW;QAC/B/C,QAAQgD,UAAU,CAACC,IAAI,CAACH;IAC1B,OAAO;QACLA;IACF;AACF;AAEA,SAASlD;IACP,MAAM,EAAE+B,OAAO,EAAEe,OAAO,EAAEC,MAAM,EAAE,GAAGhE;IACrC,OAAO;QACLoE,OAAO;QACP/B,aAAa;QACbW;QACAqB,YAAY,EAAE;QACdE,iBAAiBR;QACjBS,gBAAgBR;IAClB;AACF;AAEA,SAASlB,iBAAiBzB,OAAqB;IAC7C,IAAIA,QAAQ+C,KAAK,KAAK,WAAW;QAC/B;IACF;IACA/C,QAAQ+C,KAAK,GAAG;IAChB/C,QAAQgB,WAAW,GAAGoC,YAAYC,GAAG,KAAKD,YAAYE,UAAU;IAChE,IAAI;QACF,MAAM,EAAEN,YAAYO,SAAS,EAAE,GAAGvD;QAClC,IAAK,IAAIqB,IAAI,GAAGA,IAAIkC,UAAUC,MAAM,EAAEnC,IAAK;YACzCkC,SAAS,CAAClC,EAAE;QACd;QACAkC,UAAUC,MAAM,GAAG;IACrB,SAAU;QACRxD,QAAQkD,eAAe;IACzB;AACF;AAEA,SAAS/C,mBAAmBH,OAAqB,EAAED,MAAe;IAChE,IAAIC,QAAQ+C,KAAK,KAAK,WAAW;QAC/B;IACF;IACA/C,QAAQ+C,KAAK,GAAG;IAChB,kDAAkD;IAElD,gEAAgE;IAChE/C,QAAQgD,UAAU,CAACQ,MAAM,GAAG;IAE5B,8EAA8E;IAC9ExD,QAAQ2B,OAAO,CAACW,KAAK,CAACC;IACtBvC,QAAQmD,cAAc,CAACpD;AACzB","ignoreList":[0]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n needsSessionShell?: boolean // DEV-only\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["workUnitAsyncStorageInstance","InvariantError","workUnitAsyncStorage","throwForMissingRequestStore","callingExpression","Error","throwInvariantForMissingStore","getResumeDataCache","workUnitStore","type","resumeDataCache","getHmrRefreshHash","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","isHmrRefresh","getServerComponentsHmrCache","serverComponentsHmrCache","getDraftModeProviderForCacheScope","workStore","isDraftMode","draftMode","getStagedRenderingController","stagedRendering","getCacheSignal","cacheSignal","getVaryParamsAccumulator","varyParamsAccumulator"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,4BAA4B,QAAQ,0CAA0C;IAAE,wBAAwB;AAAc,EAAC;AAShI,SAASC,cAAc,QAAQ,mCAAkC;AAqXjE,SAASD,gCAAgCE,oBAAoB,GAAE;AAE/D,OAAO,SAASC,4BAA4BC,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEA,OAAO,SAASE;IACd,MAAM,qBAAoE,CAApE,IAAIL,eAAe,mDAAnB,qBAAA;eAAA;oBAAA;sBAAA;IAAmE;AAC3E;AAEA;;;;CAIC,GACD,OAAO,SAASM,mBACdC,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcE,eAAe;QACtC,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOF;IACX;AACF;AAEA,OAAO,SAASG,kBACdH,aAA4B;IAE5B,IAAII,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QACjC,OAAQN,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOD,cAAcO,cAAc;YACrC,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEP;QACJ;IACF;IAEA,OAAOQ;AACT;AAEA,OAAO,SAASC,aAAaT,aAA4B;IACvD,IAAII,QAAQC,GAA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,OAAOD,cAAcmB,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAInB,cAAcmB,WAAW,EAAE;oBAC7B,OAAOnB,cAAcmB,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOnB;IACX;AACF;AAEA,OAAO,SAASoB,yBACdpB,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAcqB,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACErB;YACA,OAAO;IACX;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n needsSessionShell?: boolean // DEV-only\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["workUnitAsyncStorageInstance","InvariantError","workUnitAsyncStorage","throwForMissingRequestStore","callingExpression","Error","throwInvariantForMissingStore","getResumeDataCache","workUnitStore","type","resumeDataCache","getHmrRefreshHash","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","isHmrRefresh","getServerComponentsHmrCache","serverComponentsHmrCache","getDraftModeProviderForCacheScope","workStore","isDraftMode","draftMode","getStagedRenderingController","stagedRendering","getCacheSignal","cacheSignal","getVaryParamsAccumulator","varyParamsAccumulator"],"mappings":"AAUA,qDAAqD;AACrD,SAASA,4BAA4B,QAAQ,0CAA0C;IAAE,wBAAwB;AAAc,EAAC;AAShI,SAASC,cAAc,QAAQ,mCAAkC;AAuajE,SAASD,gCAAgCE,oBAAoB,GAAE;AAE/D,OAAO,SAASC,4BAA4BC,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oB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OAAO;QACT;YACErB;YACA,OAAO;IACX;AACF","ignoreList":[0]} |
@@ -98,6 +98,6 @@ import { addRequestMeta, getRequestMeta } from '../request-meta'; | ||
| this.staticPathsCache = new LRUCache(// 5MB | ||
| 5 * 1024 * 1024, function length(value) { | ||
| 5 * 1024 * 1024, function length(value, cacheKey) { | ||
| var _JSON_stringify; | ||
| // Ensure minimum size of 1 for LRU eviction to work correctly | ||
| return ((_JSON_stringify = JSON.stringify(value.staticPaths)) == null ? void 0 : _JSON_stringify.length) || 1; | ||
| return cacheKey.length + (((_JSON_stringify = JSON.stringify(value.staticPaths)) == null ? void 0 : _JSON_stringify.length) || 1); | ||
| }); | ||
@@ -111,4 +111,4 @@ const { pagesDir, appDir } = findPagesDir(this.dir); | ||
| const hmrCacheSize = Math.max(this.nextConfig.cacheMaxMemorySize, defaultConfig.cacheMaxMemorySize); | ||
| this.serverComponentsHmrCache = new LRUCache(hmrCacheSize, function length(value) { | ||
| return JSON.stringify(value).length; | ||
| this.serverComponentsHmrCache = new LRUCache(hmrCacheSize, function length(value, cacheKey) { | ||
| return cacheKey.length + JSON.stringify(value).length; | ||
| }); | ||
@@ -115,0 +115,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return JSON.stringify(value.staticPaths)?.length || 1\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value) {\n return JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["addRequestMeta","getRequestMeta","React","fs","Worker","installUseCacheProbe","installDevValidationWorker","join","pathJoin","PUBLIC_DIR_MIDDLEWARE_CONFLICT","findPagesDir","PHASE_DEVELOPMENT_SERVER","PAGES_MANIFEST","APP_PATHS_MANIFEST","COMPILER_NAMES","PRERENDER_MANIFEST","Server","WrappedBuildError","normalizePagePath","pathHasPrefix","removePathPrefix","Telemetry","hrtimeToEpochNanoseconds","setGlobal","trace","traceGlobals","findPageFile","getFormattedNodeOptionsWithoutInspect","withCoalescedInvoke","loadDefaultErrorComponents","DecodeError","MiddlewareNotFoundError","Log","isError","getProperError","defaultConfig","isMiddlewareFile","formatServerError","DevRouteMatcherManager","DevPagesRouteMatcherProvider","DevPagesAPIRouteMatcherProvider","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","NodeManifestLoader","BatchedFileReader","DefaultFileReader","LRUCache","getMiddlewareRouteMatcher","DetachedPromise","isPostpone","generateInterceptionRoutesRewrites","buildCustomRoute","decorateServerError","logRequests","FallbackMode","fallbackModeToFallbackField","ensureInstrumentationRegistered","getInstrumentationModule","getRouteRegex","HMR_MESSAGE_SENT_TO_BROWSER","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","createElement","DevServer","getStaticPathsWorker","worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","conf","bundlerService","startServerSpan","renderOpts","ErrorDebug","staticPathsCache","length","value","JSON","stringify","staticPaths","pagesDir","appDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","extensions","pageExtensions","extensionsExpression","RegExp","fileReader","pathnameFilter","test","push","localeNormalizer","ignorePartFilter","part","startsWith","isTurbopack","getBuildId","prepareImpl","existingTelemetry","get","telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","logErrorWithOriginalStack","err","hasPage","normalizedPath","console","error","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","requestStart","hrtime","bigint","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","devRequestTimingInternalsEnd","manualTraceChild","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","existsSync","publicDir","sent","__NEXT_PAGE","internalErr","body","send","type","getPagesManifest","serverDistDir","getAppPathsManifest","enabledDirectories","app","rewrites","Object","keys","appPathRoutes","map","route","regex","output","exit","getMiddleware","middleware","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","message","runInstrumentationHookIfAvailable","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":"AAWA,SACEA,cAAc,EACdC,cAAc,QAGT,kBAAiB;AAQxB,YAAYC,WAAW,QAAO;AAC9B,OAAOC,QAAQ,KAAI;AACnB,SAASC,MAAM,QAAQ,iCAAgC;AACvD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,0BAA0B,QAAQ,+BAA8B;AACzE,SAASC,QAAQC,QAAQ,QAAQ,OAAM;AACvC,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SACEC,wBAAwB,EACxBC,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,QACb,6BAA4B;AACnC,OAAOC,UAAUC,iBAAiB,QAAQ,iBAAgB;AAC1D,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,0BAAyB;AACnD,SAEEC,wBAAwB,EACxBC,SAAS,EACTC,KAAK,QACA,cAAa;AACpB,SAASC,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EA,MAAgB+M,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACpL,SAASqL,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACtL,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value, cacheKey) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return (\n cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)\n )\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value, cacheKey) {\n return cacheKey.length + JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["addRequestMeta","getRequestMeta","React","fs","Worker","installUseCacheProbe","installDevValidationWorker","join","pathJoin","PUBLIC_DIR_MIDDLEWARE_CONFLICT","findPagesDir","PHASE_DEVELOPMENT_SERVER","PAGES_MANIFEST","APP_PATHS_MANIFEST","COMPILER_NAMES","PRERENDER_MANIFEST","Server","WrappedBuildError","normalizePagePath","pathHasPrefix","removePathPrefix","Telemetry","hrtimeToEpochNanoseconds","setGlobal","trace","traceGlobals","findPageFile","getFormattedNodeOptionsWithoutInspect","withCoalescedInvoke","loadDefaultErrorComponents","DecodeError","MiddlewareNotFoundError","Log","isError","getProperError","defaultConfig","isMiddlewareFile","formatServerError","DevRouteMatcherManager","DevPagesRouteMatcherProvider","DevPagesAPIRouteMatcherProvider","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","NodeManifestLoader","BatchedFileReader","DefaultFileReader","LRUCache","getMiddlewareRouteMatcher","DetachedPromise","isPostpone","generateInterceptionRoutesRewrites","buildCustomRoute","decorateServerError","logRequests","FallbackMode","fallbackModeToFallbackField","ensureInstrumentationRegistered","getInstrumentationModule","getRouteRegex","HMR_MESSAGE_SENT_TO_BROWSER","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","createElement","DevServer","getStaticPathsWorker","worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","conf","bundlerService","startServerSpan","renderOpts","ErrorDebug","staticPathsCache","length","value","cacheKey","JSON","stringify","staticPaths","pagesDir","appDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","extensions","pageExtensions","extensionsExpression","RegExp","fileReader","pathnameFilter","test","push","localeNormalizer","ignorePartFilter","part","startsWith","isTurbopack","getBuildId","prepareImpl","existingTelemetry","get","telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","logErrorWithOriginalStack","err","hasPage","normalizedPath","console","error","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","requestStart","hrtime","bigint","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","devRequestTimingInternalsEnd","manualTraceChild","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","existsSync","publicDir","sent","__NEXT_PAGE","internalErr","body","send","type","getPagesManifest","serverDistDir","getAppPathsManifest","enabledDirectories","app","rewrites","Object","keys","appPathRoutes","map","route","regex","output","exit","getMiddleware","middleware","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","message","runInstrumentationHookIfAvailable","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":"AAWA,SACEA,cAAc,EACdC,cAAc,QAGT,kBAAiB;AAQxB,YAAYC,WAAW,QAAO;AAC9B,OAAOC,QAAQ,KAAI;AACnB,SAASC,MAAM,QAAQ,iCAAgC;AACvD,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,0BAA0B,QAAQ,+BAA8B;AACzE,SAASC,QAAQC,QAAQ,QAAQ,OAAM;AACvC,SAASC,8BAA8B,QAAQ,sBAAqB;AACpE,SAASC,YAAY,QAAQ,2BAA0B;AACvD,SACEC,wBAAwB,EACxBC,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,QACb,6BAA4B;AACnC,OAAOC,UAAUC,iBAAiB,QAAQ,iBAAgB;AAC1D,SAASC,iBAAiB,QAAQ,iDAAgD;AAClF,SAASC,aAAa,QAAQ,gDAA+C;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,0BAAyB;AACnD,SAEEC,wBAAwB,EACxBC,SAAS,EACTC,KAAK,QACA,cAAa;AACpB,SAASC,YAAY,QAAQ,qBAAoB;AACjD,SAASC,YAAY,QAAQ,wBAAuB;AACpD,SAASC,qCAAqC,QAAQ,eAAc;AACpE,SAASC,mBAAmB,QAAQ,+BAA8B;AAClE,SACEC,0BAA0B,QAErB,mCAAkC;AACzC,SAASC,WAAW,EAAEC,uBAAuB,QAAQ,yBAAwB;AAC7E,YAAYC,SAAS,yBAAwB;AAC7C,OAAOC,WAAWC,cAAc,QAAQ,qBAAoB;AAC5D,SAASC,aAAa,QAAiC,mBAAkB;AACzE,SAASC,gBAAgB,QAAQ,oBAAmB;AACpD,SAASC,iBAAiB,QAAQ,gCAA+B;AACjE,SAASC,sBAAsB,QAAQ,sDAAqD;AAC5F,SAASC,4BAA4B,QAAQ,kEAAiE;AAC9G,SAASC,+BAA+B,QAAQ,sEAAq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N,WAAW,IAAI,EACf+E,YAAY,EACZtM,GAAG,EAWJ,EAAwC;YACjC;QAAN,QAAM,cAAA,IAAI,CAACrC,KAAK,qBAAV,YAAY+G,OAAO;QAEzB,MAAM6H,iBAAiB,MAAM,IAAI,CAACC,mBAAmB,CAAC1M;QACtD,IAAIyM,gBAAgB;YAClB,wDAAwD;YACxD,MAAM,IAAIvT,kBAAkBuT;QAC9B;QACA,IAAID,gBAAgB,IAAI,CAACG,aAAa,CAACC,YAAY,EAAE;YACnD,MAAM,IAAI,CAAC9M,UAAU,CAAC;gBACpBE;gBACAyH;gBACAxH,YAAY;gBACZF,YAAY9D;gBACZiE;YACF;QACF;QAEA,IAAI,CAAC2M,gBAAgB,GAAG,KAAK,CAAC9F;QAE9B,OAAO,MAAM,KAAK,CAACsF,mBAAmB;YACpCrM;YACAuM;YACAjK;YACAgK;YACAvE;YACAyE;YACAtM;QACF;IACF;IAEA,MAAgB4M,2BACd5M,GAAY,EAC2C;QACvD,MAAM,IAAI,CAACnC,cAAc,CAAC+O,0BAA0B,CAAC5M;QACrD,OAAO,MAAMpG,2BAA2B,IAAI,CAACoF,OAAO;IACtD;IAEA,MAAMwN,oBAAoB1M,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACjC,cAAc,CAAC2O,mBAAmB,CAAC1M;IACvD;IAEA,MAAgB+M,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACpL,SAASqL,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAACtL,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} |
@@ -35,10 +35,164 @@ import { RenderStage } from './app-render/staged-rendering'; | ||
| /** | ||
| * This function constructs a promise that will never resolve. This is primarily | ||
| * useful for cacheComponents where we use promise resolution timing to determine which | ||
| * parts of a render can be included in a prerender. | ||
| * Constructs a promise that never resolves, standing in for *dynamic* data: | ||
| * data that is only available during a real dynamic request and hangs in | ||
| * every kind of prerender — `io()`, `connection()`, uncached `fetch()`. | ||
| * | ||
| * This is primarily useful for cacheComponents where we use promise | ||
| * resolution timing to determine which parts of a render can be included in a | ||
| * prerender. | ||
| * | ||
| * Records nothing on the prerender store: the promise's holes are only ever | ||
| * filled by a real dynamic request, so a runtime prefetch response would have | ||
| * the same holes as the static one. If the data source would resolve during a | ||
| * runtime prerender, use `makeRuntimeHangingPromise` instead. | ||
| * | ||
| * @internal | ||
| */ export function makeHangingPromise(signal, route, expression) { | ||
| */ export function makeDynamicHangingPromise(signal, route, expression) { | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| /** | ||
| * Constructs a promise that never resolves, standing in for *runtime* data: | ||
| * data that hangs during a static prerender but is available during a runtime | ||
| * prerender (the kind that backs a runtime prefetch request: request data | ||
| * like cookies and headers is available, but the render is still not a real | ||
| * dynamic request). Examples: cookies, headers, fallback params, | ||
| * searchParams, and cache entries that are excluded only from static | ||
| * prerenders. | ||
| * | ||
| * Creating one of these during a static prerender records on the prerender | ||
| * store that a runtime prefetch would produce more content than the static | ||
| * response (`runtimeDataAccessed`), which the segment prefetch encoding uses | ||
| * to tell the client whether a runtime prefetch request could be skipped. | ||
| * | ||
| * When unsure whether data is dynamic or runtime, prefer this method — the | ||
| * cost of over-recording is a redundant runtime prefetch request; the cost of | ||
| * under-recording is a permanently missing one. | ||
| * | ||
| * `workUnitStore` may be null ONLY when the caller tracks the access itself | ||
| * at observation time instead of creation time. This is for promises the | ||
| * framework creates eagerly whether or not anything reads them (e.g. the | ||
| * `searchParams` prop constructed for every page): recording at creation | ||
| * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed` | ||
| * from every path that observes the promise (e.g. the proxy traps for | ||
| * `then`/`status`), against the work unit store active at access time. | ||
| * | ||
| * For fallback-param data — data a concrete (ISR-upgraded) prerender would | ||
| * resolve — use `makeFallbackParamsHangingPromise` instead, so the access | ||
| * is recorded with the right effect on the static-prefetch hint. | ||
| * | ||
| * @internal | ||
| */ export function makeRuntimeHangingPromise(signal, route, expression, workUnitStore) { | ||
| if (workUnitStore !== null) { | ||
| trackRuntimeDataAccessed(workUnitStore); | ||
| } | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| /** | ||
| * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback | ||
| * route params and values derived solely from them (`params`, `rootParams`, | ||
| * `pathname` during a fallback prerender). Like every runtime data access it | ||
| * records the access on the prerender store's response-level flag, but its | ||
| * effect on the build-time static-prefetch hint differs — on a | ||
| * fallback-upgradeable route the access is transient (a concrete prerender | ||
| * resolves it), so it leaves the hint intact. See | ||
| * `trackFallbackParamsAccessed`. | ||
| * | ||
| * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when | ||
| * the caller tracks the access itself at observation time instead of creation | ||
| * time, by calling `trackFallbackParamsAccessed` from every path that | ||
| * observes the promise. | ||
| * | ||
| * @internal | ||
| */ export function makeFallbackParamsHangingPromise(signal, route, expression, workUnitStore) { | ||
| if (workUnitStore !== null) { | ||
| trackFallbackParamsAccessed(workUnitStore); | ||
| } | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| /** | ||
| * Constructs a promise that never resolves, standing in for data that is only | ||
| * accessible in a later *stage* of rendering than this render reaches — e.g. | ||
| * a prefetchable short-stale cache entry that's excluded from shells when the | ||
| * render ends at the shell stage, or params during a runtime-prefetch render | ||
| * that stops before the stage where params resolve. | ||
| * | ||
| * A render that runs through the later stage would include the data; in | ||
| * particular a runtime prefetch renders through its later stages, so on a | ||
| * static prerender store this records `runtimeDataAccessed`, same as | ||
| * `makeRuntimeHangingPromise`. | ||
| * | ||
| * @internal | ||
| */ export function makeStageHangingPromise(signal, route, expression, workUnitStore) { | ||
| trackRuntimeDataAccessed(workUnitStore); | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| /** | ||
| * Records on a static prerender store that the render accessed a data source | ||
| * which would have resolved during a runtime prerender. No-op for all other | ||
| * store types. | ||
| * | ||
| * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this | ||
| * automatically; call it directly only where the access is observed | ||
| * separately from the promise's creation (see the null `workUnitStore` case | ||
| * of `makeRuntimeHangingPromise`), or where the prerender is aborted | ||
| * synchronously instead of hanging. | ||
| * | ||
| * For fallback-param data, use `trackFallbackParamsAccessed` instead. When | ||
| * unsure, this is the conservative choice: it unconditionally clears the | ||
| * static-prefetch hint. | ||
| */ export function trackRuntimeDataAccessed(workUnitStore) { | ||
| trackRuntimeDataAccessedImpl(workUnitStore, false); | ||
| } | ||
| /** | ||
| * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of | ||
| * fallback route params and values derived solely from them. It records the | ||
| * response-level flag all the same, but only clears the build-time | ||
| * static-prefetch hint when the route is not fallback-upgradeable — on an | ||
| * upgradeable route the access is transient, since ISR later produces a | ||
| * concrete prerender that resolves it. | ||
| */ export function trackFallbackParamsAccessed(workUnitStore) { | ||
| trackRuntimeDataAccessedImpl(workUnitStore, true); | ||
| } | ||
| function trackRuntimeDataAccessedImpl(workUnitStore, isFallbackParamAccess) { | ||
| switch(workUnitStore.type){ | ||
| case 'prerender': | ||
| { | ||
| var // Response-level flag (the payload's `u`, forwarded to segment | ||
| // responses as `needsRuntimeRequest`): resolved for every kind of | ||
| // access — a pre-upgrade fallback response must keep reporting that | ||
| // a runtime request would return more. The fulfillment row lands at | ||
| // the current position in the Flight stream, which is what makes the | ||
| // value rewindable per stage. Promise resolution is idempotent, so | ||
| // repeated accesses are free. | ||
| _workUnitStore_runtimeDataAccessed; | ||
| (_workUnitStore_runtimeDataAccessed = workUnitStore.runtimeDataAccessed) == null ? void 0 : _workUnitStore_runtimeDataAccessed.resolve(true); | ||
| // Hint cell (holds the build-constant | ||
| // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a | ||
| // fallback-param access is transient when the route is | ||
| // fallback-upgradeable — ISR later produces the concrete prerender a | ||
| // static prefetch attempt would hit — so it leaves the hint intact. | ||
| // (Until that upgrade, the response-level flag above keeps directing | ||
| // the client to a runtime fallback; the hint only costs a wasted | ||
| // static attempt in the interim.) Every other access clears it. | ||
| const hintCell = workUnitStore.shouldAttemptStaticPrefetch; | ||
| if (hintCell !== null && (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)) { | ||
| hintCell.current = false; | ||
| } | ||
| break; | ||
| } | ||
| case 'prerender-client': | ||
| case 'prerender-ppr': | ||
| case 'prerender-legacy': | ||
| case 'prerender-runtime': | ||
| case 'validation-client': | ||
| case 'request': | ||
| case 'cache': | ||
| case 'private-cache': | ||
| case 'unstable-cache': | ||
| case 'generate-static-params': | ||
| break; | ||
| default: | ||
| workUnitStore; | ||
| } | ||
| } | ||
| export function makeClientHookHangingPromise(signal, error) { | ||
@@ -45,0 +199,0 @@ return makeHangingPromiseWithError(signal, error); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type { RequestStore } from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * This function constructs a promise that will never resolve. This is primarily\n * useful for cacheComponents where we use promise resolution timing to determine which\n * parts of a render can be included in a prerender.\n *\n * @internal\n */\nexport function makeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["RenderStage","workUnitAsyncStorage","getServerReact","getClientReact","isHangingPromiseRejectionError","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","ClientHookDynamicError","isClientHookDynamicError","abortListenersBySignal","WeakMap","makeHangingPromise","signal","makeHangingPromiseWithError","makeClientHookHangingPromise","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","makePromiseFromTrigger","trigger","value","promise","then","makeDevtoolsIOAwarePromise","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","resolve","setTimeout","RENDER_STAGES_BY_DATA_KIND","sessionData","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","applyOwnerStack","process","env","NODE_ENV","ownerStack","workUnitStore","getStore","innerOwnerStack","captureOwnerStack","type","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":"AAAA,SACEA,WAAW,QAEN,gCAA+B;AAEtC,SAASC,oBAAoB,QAAQ,gDAA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AGR;QACpD;IACF;IAEA,OAAOnD;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["RenderStage","workUnitAsyncStorage","getServerReact","getClientReact","isHangingPromiseRejectionError","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","ClientHookDynamicError","isClientHookDynamicError","abortListenersBySignal","WeakMap","makeDynamicHangingPromise","signal","makeHangingPromiseWithError","makeRuntimeHangingPromise","workUnitStore","trackRuntimeDataAccessed","makeFallbackParamsHangingPromise","trackFallbackParamsAccessed","makeStageHangingPromise","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","makeClientHookHangingPromise","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","makePromiseFromTrigger","trigger","value","promise","then","makeDevtoolsIOAwarePromise","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","RENDER_STAGES_BY_DATA_KIND","sessionData","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","applyOwnerStack","process","env","NODE_ENV","ownerStack","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":"AAAA,SACEA,WAAW,QAEN,gCAA+B;AAKtC,SAASC,oBAAoB,QAAQ,gDAA+C;AACpF,SAASC,cAAc,EAAEC,cAAc,QAAQ,4BAA2B;AAE1E,OAAO,SAASC,+BACdC,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,KAAK,CACH,CAAC,qBAAqB,EAAEA,WAAW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@ import { loadEnvConfig } from '@next/env'; | ||
| const versionSuffix = logBundler ? ` (${bundlerName(getBundlerFromEnv())})` : ''; | ||
| Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.0-canary.97"}`))}${versionSuffix}`); | ||
| Log.bootstrap(`${bold(purple(`${Log.prefixes.ready} Next.js ${"16.3.0-canary.99"}`))}${versionSuffix}`); | ||
| if (appUrl) { | ||
@@ -17,0 +17,0 @@ Log.bootstrap(`- Local: ${appUrl}`); |
@@ -29,3 +29,3 @@ /** | ||
| } | ||
| const memoryCache = new LRUCache(maxSize, (entry)=>entry.size); | ||
| const memoryCache = new LRUCache(maxSize, (entry, cacheKey)=>entry.size + cacheKey.length); | ||
| const pendingSets = new Map(); | ||
@@ -32,0 +32,0 @@ const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE ? console.debug.bind(console, 'DefaultCacheHandler:') : undefined; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/cache-handlers/default.ts"],"sourcesContent":["/**\n * This is the default \"use cache\" handler it defaults to an in-memory store.\n * 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, we also\n * don't want to reuse a stale entry for too long so stale entries should be\n * considered expired/missing in such cache handlers.\n *\n * The dev server (`next dev`) is the exception: to keep reloads fast it serves\n * stale entries until they expire, relying on the wrapper's\n * stale-while-revalidate path to warm a fresh entry in the background. See\n * `get` for where this branches.\n */\n\nimport { LRUCache } from '../lru-cache'\nimport type { CacheEntry, CacheHandler } from './types'\nimport {\n areTagsExpired,\n areTagsStale,\n tagsManifest,\n type TagManifestEntry,\n} from '../incremental-cache/tags-manifest.external'\nimport { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'\n\ntype PrivateCacheEntry = {\n entry: CacheEntry\n\n // For the default cache we store errored cache\n // entries and allow them to be used up to 3 times\n // after that we want to dispose it and try for fresh\n\n // If an entry is errored we return no entry\n // three times so that we retry hitting origin (MISS)\n // and then if it still fails to set after the third we\n // return the errored content and use expiration of\n // Math.min(30, entry.expiration)\n isErrored: boolean\n errorRetryCount: number\n\n // compute size on set since we need to read size\n // of the ReadableStream for LRU evicting\n size: number\n}\n\nexport function createDefaultCacheHandler(maxSize: number): CacheHandler {\n // If the max size is 0, return a cache handler that doesn't cache anything,\n // this avoids an unnecessary LRUCache instance and potential memory\n // allocation.\n if (maxSize === 0) {\n return {\n get: () => Promise.resolve(undefined),\n set: () => Promise.resolve(),\n refreshTags: () => Promise.resolve(),\n getExpiration: () => Promise.resolve(0),\n updateTags: () => Promise.resolve(),\n }\n }\n\n const memoryCache = new LRUCache<PrivateCacheEntry>(\n maxSize,\n (entry) => entry.size\n )\n const pendingSets = new Map<string, Promise<void>>()\n\n const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? console.debug.bind(console, 'DefaultCacheHandler:')\n : undefined\n\n return {\n async get(cacheKey) {\n const pendingPromise = pendingSets.get(cacheKey)\n\n if (pendingPromise) {\n debug?.('get', cacheKey, 'pending')\n await pendingPromise\n }\n\n const privateEntry = memoryCache.get(cacheKey)\n\n if (!privateEntry) {\n debug?.('get', cacheKey, 'not found')\n return undefined\n }\n\n const entry = privateEntry.entry\n\n // A negative `expire` is an eviction sentinel: the tiered cache handler\n // (dev-only) marks a front entry for deletion by overwriting it with a\n // negative `expire`, since the cache-handler interface has no per-key\n // delete. Treat it as missing here, independently of the minimum\n // retention below (which would otherwise keep it alive). This is distinct\n // from `revalidate = -1` below, which keeps serving the entry but forces\n // a revalidation.\n if (entry.expire < 0) {\n debug?.('get', cacheKey, 'evicted')\n return undefined\n }\n\n // The dev server serves stale entries until they expire (see the file\n // overview); production drops them once past the revalidate time. In dev,\n // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that\n // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`\n // client-only cache) still linger long enough that a reload hits the\n // cache. That minimum is the same threshold below which the \"use cache\"\n // wrapper treats an entry as dynamic, so it only extends the retention of\n // entries that are dynamic anyway. It affects retention only; the\n // returned entry keeps its real `expire`, so staging decisions are\n // unchanged.\n const maxAgeSeconds = process.env.__NEXT_DEV_SERVER\n ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)\n : entry.revalidate\n\n if (\n performance.timeOrigin + performance.now() >\n entry.timestamp + maxAgeSeconds * 1000\n ) {\n debug?.('get', cacheKey, 'expired')\n\n return undefined\n }\n\n let revalidate = entry.revalidate\n\n if (areTagsExpired(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had expired tag')\n return undefined\n }\n\n if (areTagsStale(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had stale tag')\n revalidate = -1\n }\n\n const [returnStream, newSaved] = entry.value.tee()\n entry.value = newSaved\n\n debug?.('get', cacheKey, 'found', {\n tags: entry.tags,\n timestamp: entry.timestamp,\n expire: entry.expire,\n revalidate,\n })\n\n return {\n ...entry,\n revalidate,\n value: returnStream,\n }\n },\n\n async set(cacheKey, pendingEntry) {\n debug?.('set', cacheKey, 'start')\n\n let resolvePending: () => void = () => {}\n const pendingPromise = new Promise<void>((resolve) => {\n resolvePending = resolve\n })\n pendingSets.set(cacheKey, pendingPromise)\n\n const entry = await pendingEntry\n\n let size = 0\n\n try {\n // In production an `expire: 0` entry is dynamic: the \"use cache\"\n // wrapper regenerates it on every read instead of serving the stored\n // copy, so persisting it would be a wasted write of a value that is\n // never served back. Skip storing it so the next read is a plain miss.\n // The dev server keeps it, because its minimum retention serves the\n // previously cached value across reloads. The `finally` below still\n // resolves the pending set.\n if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {\n debug?.('set', cacheKey, 'skipped dynamic entry')\n return\n }\n\n const [value, clonedValue] = entry.value.tee()\n entry.value = value\n const reader = clonedValue.getReader()\n\n for (let chunk; !(chunk = await reader.read()).done; ) {\n size += Buffer.from(chunk.value).byteLength\n }\n\n memoryCache.set(cacheKey, {\n entry,\n isErrored: false,\n errorRetryCount: 0,\n size,\n })\n\n debug?.('set', cacheKey, 'done')\n } catch (err) {\n // TODO: store partial buffer with error after we retry 3 times\n debug?.('set', cacheKey, 'failed', err)\n } finally {\n resolvePending()\n pendingSets.delete(cacheKey)\n }\n },\n\n async refreshTags() {\n // Nothing to do for an in-memory cache handler.\n },\n\n async getExpiration(tags) {\n const expirations = tags.map((tag) => {\n const entry = tagsManifest.get(tag)\n if (!entry) return 0\n // Return the most recent timestamp (either expired or stale)\n return entry.expired || 0\n })\n\n const expiration = Math.max(...expirations, 0)\n\n debug?.('getExpiration', { tags, expiration })\n\n return expiration\n },\n\n async updateTags(tags, durations) {\n const now = Math.round(performance.timeOrigin + performance.now())\n debug?.('updateTags', { tags, timestamp: now })\n\n for (const tag of tags) {\n // TODO: update file-system-cache?\n const existingEntry = tagsManifest.get(tag) || {}\n\n if (durations) {\n // Use provided durations directly\n const updates: TagManifestEntry = { ...existingEntry }\n\n // mark as stale immediately\n updates.stale = now\n\n if (durations.expire !== undefined) {\n updates.expired = now + durations.expire * 1000 // Convert seconds to ms\n }\n\n tagsManifest.set(tag, updates)\n } else {\n // Update expired field for immediate expiration (default behavior when no durations provided)\n tagsManifest.set(tag, { ...existingEntry, expired: now })\n }\n }\n },\n }\n}\n"],"names":["LRUCache","areTagsExpired","areTagsStale","tagsManifest","MIN_PRERENDERABLE_EXPIRE","createDefaultCacheHandler","maxSize","get","Promise","resolve","undefined","set","refreshTags","getExpiration","updateTags","memoryCache","entry","size","pendingSets","Map","debug","process","env","NEXT_PRIVATE_DEBUG_CACHE","console","bind","cacheKey","pendingPromise","privateEntry","expire","maxAgeSeconds","__NEXT_DEV_SERVER","Math","max","revalidate","performance","timeOrigin","now","timestamp","tags","returnStream","newSaved","value","tee","pendingEntry","resolvePending","clonedValue","reader","getReader","chunk","read","done","Buffer","from","byteLength","isErrored","errorRetryCount","err","delete","expirations","map","tag","expired","expiration","durations","round","existingEntry","updates","stale"],"mappings":"AAAA;;;;;;;;;;;;CA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;YAC9B,MAAM3B,MAAML,KAAKiC,KAAK,CAAC9B,YAAYC,UAAU,GAAGD,YAAYE,GAAG;YAC/DjB,yBAAAA,MAAQ,cAAc;gBAAEmB;gBAAMD,WAAWD;YAAI;YAE7C,KAAK,MAAMwB,OAAOtB,KAAM;gBACtB,kCAAkC;gBAClC,MAAM2B,gBAAgB/D,aAAaI,GAAG,CAACsD,QAAQ,CAAC;gBAEhD,IAAIG,WAAW;oBACb,kCAAkC;oBAClC,MAAMG,UAA4B;wBAAE,GAAGD,aAAa;oBAAC;oBAErD,4BAA4B;oBAC5BC,QAAQC,KAAK,GAAG/B;oBAEhB,IAAI2B,UAAUnC,MAAM,KAAKnB,WAAW;wBAClCyD,QAAQL,OAAO,GAAGzB,MAAM2B,UAAUnC,MAAM,GAAG,KAAK,wBAAwB;;oBAC1E;oBAEA1B,aAAaQ,GAAG,CAACkD,KAAKM;gBACxB,OAAO;oBACL,8FAA8F;oBAC9FhE,aAAaQ,GAAG,CAACkD,KAAK;wBAAE,GAAGK,aAAa;wBAAEJ,SAASzB;oBAAI;gBACzD;YACF;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/cache-handlers/default.ts"],"sourcesContent":["/**\n * This is the default \"use cache\" handler it defaults to an in-memory store.\n * 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, we also\n * don't want to reuse a stale entry for too long so stale entries should be\n * considered expired/missing in such cache handlers.\n *\n * The dev server (`next dev`) is the exception: to keep reloads fast it serves\n * stale entries until they expire, relying on the wrapper's\n * stale-while-revalidate path to warm a fresh entry in the background. See\n * `get` for where this branches.\n */\n\nimport { LRUCache } from '../lru-cache'\nimport type { CacheEntry, CacheHandler } from './types'\nimport {\n areTagsExpired,\n areTagsStale,\n tagsManifest,\n type TagManifestEntry,\n} from '../incremental-cache/tags-manifest.external'\nimport { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'\n\ntype PrivateCacheEntry = {\n entry: CacheEntry\n\n // For the default cache we store errored cache\n // entries and allow them to be used up to 3 times\n // after that we want to dispose it and try for fresh\n\n // If an entry is errored we return no entry\n // three times so that we retry hitting origin (MISS)\n // and then if it still fails to set after the third we\n // return the errored content and use expiration of\n // Math.min(30, entry.expiration)\n isErrored: boolean\n errorRetryCount: number\n\n // compute size on set since we need to read size\n // of the ReadableStream for LRU evicting\n size: number\n}\n\nexport function createDefaultCacheHandler(maxSize: number): CacheHandler {\n // If the max size is 0, return a cache handler that doesn't cache anything,\n // this avoids an unnecessary LRUCache instance and potential memory\n // allocation.\n if (maxSize === 0) {\n return {\n get: () => Promise.resolve(undefined),\n set: () => Promise.resolve(),\n refreshTags: () => Promise.resolve(),\n getExpiration: () => Promise.resolve(0),\n updateTags: () => Promise.resolve(),\n }\n }\n\n const memoryCache = new LRUCache<PrivateCacheEntry>(\n maxSize,\n (entry, cacheKey) => entry.size + cacheKey.length\n )\n const pendingSets = new Map<string, Promise<void>>()\n\n const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? console.debug.bind(console, 'DefaultCacheHandler:')\n : undefined\n\n return {\n async get(cacheKey) {\n const pendingPromise = pendingSets.get(cacheKey)\n\n if (pendingPromise) {\n debug?.('get', cacheKey, 'pending')\n await pendingPromise\n }\n\n const privateEntry = memoryCache.get(cacheKey)\n\n if (!privateEntry) {\n debug?.('get', cacheKey, 'not found')\n return undefined\n }\n\n const entry = privateEntry.entry\n\n // A negative `expire` is an eviction sentinel: the tiered cache handler\n // (dev-only) marks a front entry for deletion by overwriting it with a\n // negative `expire`, since the cache-handler interface has no per-key\n // delete. Treat it as missing here, independently of the minimum\n // retention below (which would otherwise keep it alive). This is distinct\n // from `revalidate = -1` below, which keeps serving the entry but forces\n // a revalidation.\n if (entry.expire < 0) {\n debug?.('get', cacheKey, 'evicted')\n return undefined\n }\n\n // The dev server serves stale entries until they expire (see the file\n // overview); production drops them once past the revalidate time. In dev,\n // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that\n // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`\n // client-only cache) still linger long enough that a reload hits the\n // cache. That minimum is the same threshold below which the \"use cache\"\n // wrapper treats an entry as dynamic, so it only extends the retention of\n // entries that are dynamic anyway. It affects retention only; the\n // returned entry keeps its real `expire`, so staging decisions are\n // unchanged.\n const maxAgeSeconds = process.env.__NEXT_DEV_SERVER\n ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)\n : entry.revalidate\n\n if (\n performance.timeOrigin + performance.now() >\n entry.timestamp + maxAgeSeconds * 1000\n ) {\n debug?.('get', cacheKey, 'expired')\n\n return undefined\n }\n\n let revalidate = entry.revalidate\n\n if (areTagsExpired(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had expired tag')\n return undefined\n }\n\n if (areTagsStale(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had stale tag')\n revalidate = -1\n }\n\n const [returnStream, newSaved] = entry.value.tee()\n entry.value = newSaved\n\n debug?.('get', cacheKey, 'found', {\n tags: entry.tags,\n timestamp: entry.timestamp,\n expire: entry.expire,\n revalidate,\n })\n\n return {\n ...entry,\n revalidate,\n value: returnStream,\n }\n },\n\n async set(cacheKey, pendingEntry) {\n debug?.('set', cacheKey, 'start')\n\n let resolvePending: () => void = () => {}\n const pendingPromise = new Promise<void>((resolve) => {\n resolvePending = resolve\n })\n pendingSets.set(cacheKey, pendingPromise)\n\n const entry = await pendingEntry\n\n let size = 0\n\n try {\n // In production an `expire: 0` entry is dynamic: the \"use cache\"\n // wrapper regenerates it on every read instead of serving the stored\n // copy, so persisting it would be a wasted write of a value that is\n // never served back. Skip storing it so the next read is a plain miss.\n // The dev server keeps it, because its minimum retention serves the\n // previously cached value across reloads. The `finally` below still\n // resolves the pending set.\n if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {\n debug?.('set', cacheKey, 'skipped dynamic entry')\n return\n }\n\n const [value, clonedValue] = entry.value.tee()\n entry.value = value\n const reader = clonedValue.getReader()\n\n for (let chunk; !(chunk = await reader.read()).done; ) {\n size += Buffer.from(chunk.value).byteLength\n }\n\n memoryCache.set(cacheKey, {\n entry,\n isErrored: false,\n errorRetryCount: 0,\n size,\n })\n\n debug?.('set', cacheKey, 'done')\n } catch (err) {\n // TODO: store partial buffer with error after we retry 3 times\n debug?.('set', cacheKey, 'failed', err)\n } finally {\n resolvePending()\n pendingSets.delete(cacheKey)\n }\n },\n\n async refreshTags() {\n // Nothing to do for an in-memory cache handler.\n },\n\n async getExpiration(tags) {\n const expirations = tags.map((tag) => {\n const entry = tagsManifest.get(tag)\n if (!entry) return 0\n // Return the most recent timestamp (either expired or stale)\n return entry.expired || 0\n })\n\n const expiration = Math.max(...expirations, 0)\n\n debug?.('getExpiration', { tags, expiration })\n\n return expiration\n },\n\n async updateTags(tags, durations) {\n const now = Math.round(performance.timeOrigin + performance.now())\n debug?.('updateTags', { tags, timestamp: now })\n\n for (const tag of tags) {\n // TODO: update file-system-cache?\n const existingEntry = tagsManifest.get(tag) || {}\n\n if (durations) {\n // Use provided durations directly\n const updates: TagManifestEntry = { ...existingEntry }\n\n // mark as stale immediately\n updates.stale = now\n\n if (durations.expire !== undefined) {\n updates.expired = now + durations.expire * 1000 // Convert seconds to ms\n }\n\n tagsManifest.set(tag, updates)\n } else {\n // Update expired field for immediate expiration (default behavior when no durations provided)\n tagsManifest.set(tag, { ...existingEntry, expired: now })\n }\n }\n },\n }\n}\n"],"names":["LRUCache","areTagsExpired","areTagsStale","tagsManifest","MIN_PRERENDERABLE_EXPIRE","createDefaultCacheHandler","maxSize","get","Promise","resolve","undefined","set","refreshTags","getExpiration","updateTags","memoryCache","entry","cacheKey","size","length","pendingSets","Map","debug","process","env","NEXT_PRIVATE_DEBUG_CACHE","console","bind","pendingPromise","privateEntry","expire","maxAgeSeconds","__NEXT_DEV_SERVER","Math","max","revalidate","performance","timeOrigin","now","timestamp","tags","returnStream","newSaved","value","tee","pendingEntry","resolvePending","clonedValue","reader","getReader","chunk","read","done","Buffer","from","byteLength","isErrored","errorRetryCount","err","delete","expirations","map","tag","expired","expiration","durations","round","existingEntry","updates","stale"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAED,SAASA,QAAQ,QAAQ,eAAc;AAEvC,SACEC,cAAc,EACdC,YAAY,EACZC,YAAY,QAEP,8CAA6C;AACpD,SAASC,wBAAwB,QAAQ,4BAA2B;AAsBpE,OAAO,SAASC,0BAA0BC,OAAe;IACvD,4EAA4E;IAC5E,oEAAoE;IACpE,cAAc;IACd,IAAIA,YAAY,GAAG;QACjB,OAAO;YACLC,KAAK,IAAMC,QAAQC,OAAO,CAACC;YAC3BC,KAAK,IAAMH,QAAQC,OAAO;YAC1BG,aAAa,IAAMJ,QAAQC,OAAO;YAClCI,eAAe,IAAML,QAAQC,OAAO,CAAC;YACrCK,YAAY,IAAMN,QAAQC,OAAO;QACnC;IACF;IAEA,MAAMM,cAAc,IAAIf,SACtBM,SACA,CAACU,OAAOC,WAAaD,MAAME,IAAI,GAAGD,SAASE,MAAM;IAEnD,MAAMC,cAAc,IAAIC;IAExB,MAAMC,QAAQC,QAAQC,GAAG,CAACC,wBAAwB,GAC9CC,QAAQJ,KAAK,CAACK,IAAI,CAACD,SAAS,0BAC5BhB;IAEJ,OAAO;QACL,MAAMH,KAAIU,QAAQ;YAChB,MAAMW,iBAAiBR,YAAYb,GAAG,CAACU;YAEvC,IAAIW,gBAAgB;gBAClBN,yBAAAA,MAAQ,OAAOL,UAAU;gBACzB,MAAMW;YACR;YAEA,MAAMC,eAAed,YAAYR,GAAG,CAACU;YAErC,IAAI,CAACY,cAAc;gBACjBP,yBAAAA,MAAQ,OAAOL,UAAU;gBACzB,OAAOP;YACT;YAEA,MAAMM,QAAQa,aAAab,KAAK;YAEhC,wEAAwE;YACxE,uEAAuE;YACvE,sEAAsE;YACtE,iEAAiE;YACjE,0EAA0E;YAC1E,yEAAyE;YACzE,kBAAkB;YAClB,IAAIA,M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MAAMC,aAAa/B,KAAKC,GAAG,IAAI0B,aAAa;YAE5CtC,yBAAAA,MAAQ,iBAAiB;gBAAEkB;gBAAMwB;YAAW;YAE5C,OAAOA;QACT;QAEA,MAAMlD,YAAW0B,IAAI,EAAEyB,SAAS;YAC9B,MAAM3B,MAAML,KAAKiC,KAAK,CAAC9B,YAAYC,UAAU,GAAGD,YAAYE,GAAG;YAC/DhB,yBAAAA,MAAQ,cAAc;gBAAEkB;gBAAMD,WAAWD;YAAI;YAE7C,KAAK,MAAMwB,OAAOtB,KAAM;gBACtB,kCAAkC;gBAClC,MAAM2B,gBAAgBhE,aAAaI,GAAG,CAACuD,QAAQ,CAAC;gBAEhD,IAAIG,WAAW;oBACb,kCAAkC;oBAClC,MAAMG,UAA4B;wBAAE,GAAGD,aAAa;oBAAC;oBAErD,4BAA4B;oBAC5BC,QAAQC,KAAK,GAAG/B;oBAEhB,IAAI2B,UAAUnC,MAAM,KAAKpB,WAAW;wBAClC0D,QAAQL,OAAO,GAAGzB,MAAM2B,UAAUnC,MAAM,GAAG,KAAK,wBAAwB;;oBAC1E;oBAEA3B,aAAaQ,GAAG,CAACmD,KAAKM;gBACxB,OAAO;oBACL,8FAA8F;oBAC9FjE,aAAaQ,GAAG,CAACmD,KAAK;wBAAE,GAAGK,aAAa;wBAAEJ,SAASzB;oBAAI;gBACzD;YACF;QACF;IACF;AACF","ignoreList":[0]} |
@@ -19,8 +19,8 @@ import { CachedRouteKind } from '../../response-cache/types'; | ||
| if (!memoryCache) { | ||
| memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) { | ||
| var _JSON_stringify; | ||
| memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }, cacheKey) { | ||
| let valueSize; | ||
| if (!value) { | ||
| return 25; | ||
| valueSize = 25; | ||
| } else if (value.kind === CachedRouteKind.REDIRECT) { | ||
| return JSON.stringify(value.props).length; | ||
| valueSize = JSON.stringify(value.props).length; | ||
| } else if (value.kind === CachedRouteKind.IMAGE) { | ||
@@ -33,12 +33,14 @@ throw Object.defineProperty(new Error('invariant image should not be incremental-cache'), "__NEXT_ERROR_CODE", { | ||
| } else if (value.kind === CachedRouteKind.FETCH) { | ||
| return JSON.stringify(value.data || '').length; | ||
| valueSize = JSON.stringify(value.data || '').length; | ||
| } else if (value.kind === CachedRouteKind.APP_ROUTE) { | ||
| return value.body.length; | ||
| } | ||
| // rough estimate of size of cache value | ||
| if (value.kind === CachedRouteKind.APP_PAGE) { | ||
| valueSize = value.body.length; | ||
| } else if (value.kind === CachedRouteKind.APP_PAGE) { | ||
| var _value_postponed; | ||
| return Math.max(1, value.html.length + getBufferSize(value.rscData) + (((_value_postponed = value.postponed) == null ? void 0 : _value_postponed.length) || 0) + getSegmentDataSize(value.segmentData)); | ||
| // rough estimate of size of cache value | ||
| valueSize = Math.max(1, value.html.length + getBufferSize(value.rscData) + (((_value_postponed = value.postponed) == null ? void 0 : _value_postponed.length) || 0) + getSegmentDataSize(value.segmentData)); | ||
| } else { | ||
| var _JSON_stringify; | ||
| valueSize = value.html.length + (((_JSON_stringify = JSON.stringify(value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0); | ||
| } | ||
| return value.html.length + (((_JSON_stringify = JSON.stringify(value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0); | ||
| return cacheKey.length + valueSize; | ||
| }); | ||
@@ -45,0 +47,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/incremental-cache/memory-cache.external.ts"],"sourcesContent":["import type { CacheHandlerValue } from '.'\nimport { CachedRouteKind } from '../../response-cache/types'\nimport { LRUCache } from '../lru-cache'\n\nlet memoryCache: LRUCache<CacheHandlerValue> | undefined\n\nfunction getBufferSize(buffer: Buffer | undefined) {\n return buffer?.length || 0\n}\n\nfunction getSegmentDataSize(segmentData: Map<string, Buffer> | undefined) {\n if (!segmentData) {\n return 0\n }\n\n let size = 0\n\n for (const [segmentPath, buffer] of segmentData) {\n size += segmentPath.length + getBufferSize(buffer)\n }\n\n return size\n}\n\nexport function getMemoryCache(maxMemoryCacheSize: number) {\n if (!memoryCache) {\n memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) {\n if (!value) {\n return 25\n } else if (value.kind === CachedRouteKind.REDIRECT) {\n return JSON.stringify(value.props).length\n } else if (value.kind === CachedRouteKind.IMAGE) {\n throw new Error('invariant image should not be incremental-cache')\n } else if (value.kind === CachedRouteKind.FETCH) {\n return JSON.stringify(value.data || '').length\n } else if (value.kind === CachedRouteKind.APP_ROUTE) {\n return value.body.length\n }\n // rough estimate of size of cache value\n if (value.kind === CachedRouteKind.APP_PAGE) {\n return Math.max(\n 1,\n value.html.length +\n getBufferSize(value.rscData) +\n (value.postponed?.length || 0) +\n getSegmentDataSize(value.segmentData)\n )\n }\n\n return value.html.length + (JSON.stringify(value.pageData)?.length || 0)\n })\n }\n\n return memoryCache\n}\n"],"names":["CachedRouteKind","LRUCache","memoryCache","getBufferSize","buffer","length","getSegmentDataSize","segmentData","size","segmentPath","getMemoryCache","maxMemoryCacheSize","value","JSON","kind","REDIRECT","stringify","props","IMAGE","Error","FETCH","data","APP_ROUTE","body","APP_PAGE","Math","max","html","rscData","postponed","pageData"],"mappings":"AACA,SAASA,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,QAAQ,QAAQ,eAAc;AAEvC,IAAIC;AAEJ,SAASC,cAAcC,MAA0B;IAC/C,OAAOA,CAAAA,0BAAAA,OAAQC,MAAM,KAAI;AAC3B;AAEA,SAASC,mBAAmBC,WAA4C;IACtE,IAAI,CAACA,aAAa;QAChB,OAAO;IACT;IAEA,IAAIC,OAAO;IAEX,KAAK,MAAM,CAACC,aAAaL,OAAO,IAAIG,YAAa;QAC/CC,QAAQC,YAAYJ,MAAM,GAAGF,cAAcC;IAC7C;IAEA,OAAOI;AACT;AAEA,OAAO,SAASE,eAAeC,kBAA0B;IACvD,IAAI,CAACT,aAAa;QAChBA,cAAc,IAAID,SAASU,oBAAoB,SAASN,OAAO,EAAEO,KAAK,EAAE;gBAuB1CC;YAtB5B,IAAI,CAACD,OAAO;gBACV,OAAO;YACT,OAAO,IAAIA,MAAME,IAAI,KAAKd,gBAAgBe,QAAQ,EAAE;gBAClD,OAAOF,KAAKG,SAAS,CAACJ,MAAMK,KAAK,EAAEZ,MAAM;YAC3C,OAAO,IAAIO,MAAME,IAAI,KAAKd,gBAAgBkB,KAAK,EAAE;gBAC/C,MAAM,qBAA4D,CAA5D,IAAIC,MAAM,oDAAV,qBAAA;2BAAA;gCAAA;kCAAA;gBAA2D;YACnE,OAAO,IAAIP,MAAME,IAAI,KAAKd,gBAAgBoB,KAAK,EAAE;gBAC/C,OAAOP,KAAKG,SAAS,CAACJ,MAAMS,IAAI,IAAI,IAAIhB,MAAM;YAChD,OAAO,IAAIO,MAAME,IAAI,KAAKd,gBAAgBsB,SAAS,EAAE;gBACnD,OAAOV,MAAMW,IAAI,CAAClB,MAAM;YAC1B;YACA,wCAAwC;YACxC,IAAIO,MAAME,IAAI,KAAKd,gBAAgBwB,QAAQ,EAAE;oBAKtCZ;gBAJL,OAAOa,KAAKC,GAAG,CACb,GACAd,MAAMe,IAAI,CAACtB,MAAM,GACfF,cAAcS,MAAMgB,OAAO,IAC1BhB,CAAAA,EAAAA,mBAAAA,MAAMiB,SAAS,qBAAfjB,iBAAiBP,MAAM,KAAI,CAAA,IAC5BC,mBAAmBM,MAAML,WAAW;YAE1C;YAEA,OAAOK,MAAMe,IAAI,CAACtB,MAAM,GAAIQ,CAAAA,EAAAA,kBAAAA,KAAKG,SAAS,CAACJ,MAAMkB,QAAQ,sBAA7BjB,gBAAgCR,MAAM,KAAI,CAAA;QACxE;IACF;IAEA,OAAOH;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/incremental-cache/memory-cache.external.ts"],"sourcesContent":["import type { CacheHandlerValue } from '.'\nimport { CachedRouteKind } from '../../response-cache/types'\nimport { LRUCache } from '../lru-cache'\n\nlet memoryCache: LRUCache<CacheHandlerValue> | undefined\n\nfunction getBufferSize(buffer: Buffer | undefined) {\n return buffer?.length || 0\n}\n\nfunction getSegmentDataSize(segmentData: Map<string, Buffer> | undefined) {\n if (!segmentData) {\n return 0\n }\n\n let size = 0\n\n for (const [segmentPath, buffer] of segmentData) {\n size += segmentPath.length + getBufferSize(buffer)\n }\n\n return size\n}\n\nexport function getMemoryCache(maxMemoryCacheSize: number) {\n if (!memoryCache) {\n memoryCache = new LRUCache(maxMemoryCacheSize, function length(\n { value },\n cacheKey\n ) {\n let valueSize: number\n\n if (!value) {\n valueSize = 25\n } else if (value.kind === CachedRouteKind.REDIRECT) {\n valueSize = JSON.stringify(value.props).length\n } else if (value.kind === CachedRouteKind.IMAGE) {\n throw new Error('invariant image should not be incremental-cache')\n } else if (value.kind === CachedRouteKind.FETCH) {\n valueSize = JSON.stringify(value.data || '').length\n } else if (value.kind === CachedRouteKind.APP_ROUTE) {\n valueSize = value.body.length\n } else if (value.kind === CachedRouteKind.APP_PAGE) {\n // rough estimate of size of cache value\n valueSize = Math.max(\n 1,\n value.html.length +\n getBufferSize(value.rscData) +\n (value.postponed?.length || 0) +\n getSegmentDataSize(value.segmentData)\n )\n } else {\n valueSize =\n value.html.length + (JSON.stringify(value.pageData)?.length || 0)\n }\n\n return cacheKey.length + valueSize\n })\n }\n\n return memoryCache\n}\n"],"names":["CachedRouteKind","LRUCache","memoryCache","getBufferSize","buffer","length","getSegmentDataSize","segmentData","size","segmentPath","getMemoryCache","maxMemoryCacheSize","value","cacheKey","valueSize","kind","REDIRECT","JSON","stringify","props","IMAGE","Error","FETCH","data","APP_ROUTE","body","APP_PAGE","Math","max","html","rscData","postponed","pageData"],"mappings":"AACA,SAASA,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,QAAQ,QAAQ,eAAc;AAEvC,IAAIC;AAEJ,SAASC,cAAcC,MAA0B;IAC/C,OAAOA,CAAAA,0BAAAA,OAAQC,MAAM,KAAI;AAC3B;AAEA,SAASC,mBAAmBC,WAA4C;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CAACxB,MAAM,GAAIY,CAAAA,EAAAA,kBAAAA,KAAKC,SAAS,CAACN,MAAMoB,QAAQ,sBAA7Bf,gBAAgCZ,MAAM,KAAI,CAAA;YACnE;YAEA,OAAOQ,SAASR,MAAM,GAAGS;QAC3B;IACF;IAEA,OAAOZ;AACT","ignoreList":[0]} |
@@ -99,3 +99,3 @@ /** | ||
| */ set(key, value) { | ||
| const size = (this.calculateSize == null ? void 0 : this.calculateSize.call(this, value)) ?? 1; | ||
| const size = (this.calculateSize == null ? void 0 : this.calculateSize.call(this, value, key)) ?? 1; | ||
| if (size <= 0) { | ||
@@ -102,0 +102,0 @@ throw Object.defineProperty(new Error(`LRUCache: calculateSize returned ${size}, but size must be > 0. ` + `Items with size 0 would never be evicted, causing unbounded cache growth.`), "__NEXT_ERROR_CODE", { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/lru-cache.ts"],"sourcesContent":["/**\n * Node in the doubly-linked list used for LRU tracking.\n * Each node represents a cache entry with bidirectional pointers.\n */\nclass LRUNode<T> {\n public readonly key: string\n public data: T\n public size: number\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n\n constructor(key: string, data: T, size: number) {\n this.key = key\n this.data = data\n this.size = size\n }\n}\n\n/**\n * Sentinel node used for head/tail boundaries.\n * These nodes don't contain actual cache data but simplify list operations.\n */\nclass SentinelNode<T> {\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n}\n\n/**\n * LRU (Least Recently Used) Cache implementation using a doubly-linked list\n * and hash map for O(1) operations.\n *\n * Algorithm:\n * - Uses a doubly-linked list to maintain access order (most recent at head)\n * - Hash map provides O(1) key-to-node lookup\n * - Sentinel head/tail nodes simplify edge case handling\n * - Size-based eviction supports custom size calculation functions\n *\n * Data Structure Layout:\n * HEAD <-> [most recent] <-> ... <-> [least recent] <-> TAIL\n *\n * Operations:\n * - get(): Move accessed node to head (mark as most recent)\n * - set(): Add new node at head, evict from tail if over capacity\n * - Eviction: Remove least recent node (tail.prev) when size exceeds limit\n */\nexport class LRUCache<T> {\n private readonly cache: Map<string, LRUNode<T>> = new Map()\n private readonly head: SentinelNode<T>\n private readonly tail: SentinelNode<T>\n private totalSize: number = 0\n private readonly maxSize: number\n private readonly calculateSize: ((value: T) => number) | undefined\n private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n constructor(\n maxSize: number,\n calculateSize?: (value: T) => number,\n onEvict?: (key: string, value: T) => void\n ) {\n this.maxSize = maxSize\n this.calculateSize = calculateSize\n this.onEvict = onEvict\n\n // Create sentinel nodes to simplify doubly-linked list operations\n // HEAD <-> TAIL (empty list)\n this.head = new SentinelNode<T>()\n this.tail = new SentinelNode<T>()\n this.head.next = this.tail\n this.tail.prev = this.head\n }\n\n /**\n * Adds a node immediately after the head (marks as most recently used).\n * Used when inserting new items or when an item is accessed.\n * PRECONDITION: node must be disconnected (prev/next should be null)\n */\n private addToHead(node: LRUNode<T>): void {\n node.prev = this.head\n node.next = this.head.next\n // head.next is always non-null (points to tail or another node)\n this.head.next!.prev = node\n this.head.next = node\n }\n\n /**\n * Removes a node from its current position in the doubly-linked list.\n * Updates the prev/next pointers of adjacent nodes to maintain list integrity.\n * PRECONDITION: node must be connected (prev/next are non-null)\n */\n private removeNode(node: LRUNode<T>): void {\n // Connected nodes always have non-null prev/next\n node.prev!.next = node.next\n node.next!.prev = node.prev\n }\n\n /**\n * Moves an existing node to the head position (marks as most recently used).\n * This is the core LRU operation - accessed items become most recent.\n */\n private moveToHead(node: LRUNode<T>): void {\n this.removeNode(node)\n this.addToHead(node)\n }\n\n /**\n * Removes and returns the least recently used node (the one before tail).\n * This is called during eviction when the cache exceeds capacity.\n * PRECONDITION: cache is not empty (ensured by caller)\n */\n private removeTail(): LRUNode<T> {\n const lastNode = this.tail.prev as LRUNode<T>\n // tail.prev is always non-null and always LRUNode when cache is not empty\n this.removeNode(lastNode)\n return lastNode\n }\n\n /**\n * Sets a key-value pair in the cache.\n * If the key exists, updates the value and moves to head.\n * If new, adds at head and evicts from tail if necessary.\n *\n * Time Complexity:\n * - O(1) for uniform item sizes\n * - O(k) where k is the number of items evicted (can be O(N) for variable sizes)\n */\n public set(key: string, value: T): boolean {\n const size = this.calculateSize?.(value) ?? 1\n if (size <= 0) {\n throw new Error(\n `LRUCache: calculateSize returned ${size}, but size must be > 0. ` +\n `Items with size 0 would never be evicted, causing unbounded cache growth.`\n )\n }\n if (size > this.maxSize) {\n console.warn('Single item size exceeds maxSize')\n return false\n }\n\n const existing = this.cache.get(key)\n if (existing) {\n // Update existing node: adjust size and move to head (most recent)\n existing.data = value\n this.totalSize = this.totalSize - existing.size + size\n existing.size = size\n this.moveToHead(existing)\n } else {\n // Add new node at head (most recent position)\n const newNode = new LRUNode(key, value, size)\n this.cache.set(key, newNode)\n this.addToHead(newNode)\n this.totalSize += size\n }\n\n // Evict least recently used items until under capacity\n while (this.totalSize > this.maxSize && this.cache.size > 0) {\n const tail = this.removeTail()\n this.cache.delete(tail.key)\n this.totalSize -= tail.size\n this.onEvict?.(tail.key, tail.data)\n }\n\n return true\n }\n\n /**\n * Checks if a key exists in the cache.\n * This is a pure query operation - does NOT update LRU order.\n *\n * Time Complexity: O(1)\n */\n public has(key: string): boolean {\n return this.cache.has(key)\n }\n\n /**\n * Retrieves a value by key and marks it as most recently used.\n * Moving to head maintains the LRU property for future evictions.\n *\n * Time Complexity: O(1)\n */\n public get(key: string): T | undefined {\n const node = this.cache.get(key)\n if (!node) return undefined\n\n // Mark as most recently used by moving to head\n this.moveToHead(node)\n\n return node.data\n }\n\n /**\n * Returns an iterator over the cache entries. The order is outputted in the\n * order of most recently used to least recently used.\n */\n public *[Symbol.iterator](): IterableIterator<[string, T]> {\n let current = this.head.next\n while (current && current !== this.tail) {\n // Between head and tail, current is always LRUNode\n const node = current as LRUNode<T>\n yield [node.key, node.data]\n current = current.next\n }\n }\n\n /**\n * Removes a specific key from the cache.\n * Updates both the hash map and doubly-linked list.\n *\n * Note: This is an explicit removal and does NOT trigger the `onEvict`\n * callback. Use this for intentional deletions where eviction tracking\n * is not needed.\n *\n * Time Complexity: O(1)\n */\n public remove(key: string): void {\n const node = this.cache.get(key)\n if (!node) return\n\n this.removeNode(node)\n this.cache.delete(key)\n this.totalSize -= node.size\n }\n\n /**\n * Returns the number of items in the cache.\n */\n public get size(): number {\n return this.cache.size\n }\n\n /**\n * Returns the current total size of all cached items.\n * This uses the custom size calculation if provided.\n */\n public get currentSize(): number {\n return this.totalSize\n }\n}\n"],"names":["LRUNode","constructor","key","data","size","prev","next","SentinelNode","LRUCache","maxSize","calculateSize","onEvict","cache","Map","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","set","value","Error","console","warn","existing","get","newNode","delete","has","undefined","Symbol","iterator","current","remove","currentSize"],"mappings":"AAAA;;;CAGC,GACD,MAAMA;IAOJC,YAAYC,GAAW,EAAEC,IAAO,EAAEC,IAAY,CAAE;aAHzCC,OAA4C;aAC5CC,OAA4C;QAGjD,IAAI,CAACJ,GAAG,GAAGA;QACX,IAAI,CAACC,IAAI,GAAGA;QACZ,IAAI,CAACC,IAAI,GAAGA;IACd;AACF;AAEA;;;CAGC,GACD,MAAMG;;aACGF,OAA4C;aAC5CC,OAA4C;;AACrD;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAME;IASXP,YACEQ,OAAe,EACfC,aAAoC,EACpCC,OAAyC,CACzC;aAZeC,QAAiC,IAAIC;aAG9CC,YAAoB;QAU1B,IAAI,CAACL,OAAO,GAAGA;QACf,IAAI,CAACC,aAAa,GAAGA;QACrB,IAAI,CAACC,OAAO,GAAGA;QAEf,kEAAkE;QAClE,6BAA6B;QAC7B,IAAI,CAACI,IAAI,GAAG,IAAIR;QAChB,IAAI,CAACS,IAAI,GAAG,IAAIT;QAChB,IAAI,CAACQ,IAAI,CAACT,IAAI,GAAG,IAAI,CAACU,IAAI;QAC1B,IAA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IC,UAAU,IAAI,CAACrB,IAAI,CAACT,IAAI;QAC5B,MAAO8B,WAAWA,YAAY,IAAI,CAACpB,IAAI,CAAE;YACvC,mDAAmD;YACnD,MAAME,OAAOkB;YACb,MAAM;gBAAClB,KAAKhB,GAAG;gBAAEgB,KAAKf,IAAI;aAAC;YAC3BiC,UAAUA,QAAQ9B,IAAI;QACxB;IACF;IAEA;;;;;;;;;GASC,GACD,AAAO+B,OAAOnC,GAAW,EAAQ;QAC/B,MAAMgB,OAAO,IAAI,CAACN,KAAK,CAACiB,GAAG,CAAC3B;QAC5B,IAAI,CAACgB,MAAM;QAEX,IAAI,CAACC,UAAU,CAACD;QAChB,IAAI,CAACN,KAAK,CAACmB,MAAM,CAAC7B;QAClB,IAAI,CAACY,SAAS,IAAII,KAAKd,IAAI;IAC7B;IAEA;;GAEC,GACD,IAAWA,OAAe;QACxB,OAAO,IAAI,CAACQ,KAAK,CAACR,IAAI;IACxB;IAEA;;;GAGC,GACD,IAAWkC,cAAsB;QAC/B,OAAO,IAAI,CAACxB,SAAS;IACvB;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/lru-cache.ts"],"sourcesContent":["/**\n * Node in the doubly-linked list used for LRU tracking.\n * Each node represents a cache entry with bidirectional pointers.\n */\nclass LRUNode<T> {\n public readonly key: string\n public data: T\n public size: number\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n\n constructor(key: string, data: T, size: number) {\n this.key = key\n this.data = data\n this.size = size\n }\n}\n\n/**\n * Sentinel node used for head/tail boundaries.\n * These nodes don't contain actual cache data but simplify list operations.\n */\nclass SentinelNode<T> {\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n}\n\n/**\n * LRU (Least Recently Used) Cache implementation using a doubly-linked list\n * and hash map for O(1) operations.\n *\n * Algorithm:\n * - Uses a doubly-linked list to maintain access order (most recent at head)\n * - Hash map provides O(1) key-to-node lookup\n * - Sentinel head/tail nodes simplify edge case handling\n * - Size-based eviction supports custom size calculation functions\n *\n * Data Structure Layout:\n * HEAD <-> [most recent] <-> ... <-> [least recent] <-> TAIL\n *\n * Operations:\n * - get(): Move accessed node to head (mark as most recent)\n * - set(): Add new node at head, evict from tail if over capacity\n * - Eviction: Remove least recent node (tail.prev) when size exceeds limit\n */\nexport class LRUCache<T> {\n private readonly cache: Map<string, LRUNode<T>> = new Map()\n private readonly head: SentinelNode<T>\n private readonly tail: SentinelNode<T>\n private totalSize: number = 0\n private readonly maxSize: number\n private readonly calculateSize:\n | ((value: T, key: string) => number)\n | undefined\n private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n constructor(\n maxSize: number,\n calculateSize?: (value: T, key: string) => number,\n onEvict?: (key: string, value: T) => void\n ) {\n this.maxSize = maxSize\n this.calculateSize = calculateSize\n this.onEvict = onEvict\n\n // Create sentinel nodes to simplify doubly-linked list operations\n // HEAD <-> TAIL (empty list)\n this.head = new SentinelNode<T>()\n this.tail = new SentinelNode<T>()\n this.head.next = this.tail\n this.tail.prev = this.head\n }\n\n /**\n * Adds a node immediately after the head (marks as most recently used).\n * Used when inserting new items or when an item is accessed.\n * PRECONDITION: node must be disconnected (prev/next should be null)\n */\n private addToHead(node: LRUNode<T>): void {\n node.prev = this.head\n node.next = this.head.next\n // head.next is always non-null (points to tail or another node)\n this.head.next!.prev = node\n this.head.next = node\n }\n\n /**\n * Removes a node from its current position in the doubly-linked list.\n * Updates the prev/next pointers of adjacent nodes to maintain list integrity.\n * PRECONDITION: node must be connected (prev/next are non-null)\n */\n private removeNode(node: LRUNode<T>): void {\n // Connected nodes always have non-null prev/next\n node.prev!.next = node.next\n node.next!.prev = node.prev\n }\n\n /**\n * Moves an existing node to the head position (marks as most recently used).\n * This is the core LRU operation - accessed items become most recent.\n */\n private moveToHead(node: LRUNode<T>): void {\n this.removeNode(node)\n this.addToHead(node)\n }\n\n /**\n * Removes and returns the least recently used node (the one before tail).\n * This is called during eviction when the cache exceeds capacity.\n * PRECONDITION: cache is not empty (ensured by caller)\n */\n private removeTail(): LRUNode<T> {\n const lastNode = this.tail.prev as LRUNode<T>\n // tail.prev is always non-null and always LRUNode when cache is not empty\n this.removeNode(lastNode)\n return lastNode\n }\n\n /**\n * Sets a key-value pair in the cache.\n * If the key exists, updates the value and moves to head.\n * If new, adds at head and evicts from tail if necessary.\n *\n * Time Complexity:\n * - O(1) for uniform item sizes\n * - O(k) where k is the number of items evicted (can be O(N) for variable sizes)\n */\n public set(key: string, value: T): boolean {\n const size = this.calculateSize?.(value, key) ?? 1\n if (size <= 0) {\n throw new Error(\n `LRUCache: calculateSize returned ${size}, but size must be > 0. ` +\n `Items with size 0 would never be evicted, causing unbounded cache growth.`\n )\n }\n if (size > this.maxSize) {\n console.warn('Single item size exceeds maxSize')\n return false\n }\n\n const existing = this.cache.get(key)\n if (existing) {\n // Update existing node: adjust size and move to head (most recent)\n existing.data = value\n this.totalSize = this.totalSize - existing.size + size\n existing.size = size\n this.moveToHead(existing)\n } else {\n // Add new node at head (most recent position)\n const newNode = new LRUNode(key, value, size)\n this.cache.set(key, newNode)\n this.addToHead(newNode)\n this.totalSize += size\n }\n\n // Evict least recently used items until under capacity\n while (this.totalSize > this.maxSize && this.cache.size > 0) {\n const tail = this.removeTail()\n this.cache.delete(tail.key)\n this.totalSize -= tail.size\n this.onEvict?.(tail.key, tail.data)\n }\n\n return true\n }\n\n /**\n * Checks if a key exists in the cache.\n * This is a pure query operation - does NOT update LRU order.\n *\n * Time Complexity: O(1)\n */\n public has(key: string): boolean {\n return this.cache.has(key)\n }\n\n /**\n * Retrieves a value by key and marks it as most recently used.\n * Moving to head maintains the LRU property for future evictions.\n *\n * Time Complexity: O(1)\n */\n public get(key: string): T | undefined {\n const node = this.cache.get(key)\n if (!node) return undefined\n\n // Mark as most recently used by moving to head\n this.moveToHead(node)\n\n return node.data\n }\n\n /**\n * Returns an iterator over the cache entries. The order is outputted in the\n * order of most recently used to least recently used.\n */\n public *[Symbol.iterator](): IterableIterator<[string, T]> {\n let current = this.head.next\n while (current && current !== this.tail) {\n // Between head and tail, current is always LRUNode\n const node = current as LRUNode<T>\n yield [node.key, node.data]\n current = current.next\n }\n }\n\n /**\n * Removes a specific key from the cache.\n * Updates both the hash map and doubly-linked list.\n *\n * Note: This is an explicit removal and does NOT trigger the `onEvict`\n * callback. Use this for intentional deletions where eviction tracking\n * is not needed.\n *\n * Time Complexity: O(1)\n */\n public remove(key: string): void {\n const node = this.cache.get(key)\n if (!node) return\n\n this.removeNode(node)\n this.cache.delete(key)\n this.totalSize -= node.size\n }\n\n /**\n * Returns the number of items in the cache.\n */\n public get size(): number {\n return this.cache.size\n }\n\n /**\n * Returns the current total size of all cached items.\n * This uses the custom size calculation if provided.\n */\n public get currentSize(): number {\n return this.totalSize\n }\n}\n"],"names":["LRUNode","constructor","key","data","size","prev","next","SentinelNode","LRUCache","maxSize","calculateSize","onEvict","cache","Map","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","set","value","Error","console","warn","existing","get","newNode","delete","has","undefined","Symbol","iterator","current","remove","currentSize"],"mappings":"AAAA;;;CAGC,GACD,MAAMA;IAOJC,YAAYC,GAAW,EAAEC,IAAO,EAAEC,IAAY,CAAE;aAHzCC,OAA4C;aAC5CC,OAA4C;QAGjD,IAAI,CAACJ,GAAG,GAAGA;QACX,IAAI,CAACC,IAAI,GAAGA;QACZ,IAAI,CAACC,IAAI,GAAGA;IACd;AACF;AAEA;;;CAGC,GACD,MAAMG;;aACGF,OAA4C;aAC5CC,OAA4C;;AACrD;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAME;IAWXP,YACEQ,OAAe,EACfC,aAAiD,EACjDC,OAAyC,CACzC;aAdeC,QAAiC,IAAIC;aAG9CC,YAAoB;QAY1B,IAAI,CAACL,OAAO,GAAGA;QACf,IAAI,CAACC,aAAa,GAAGA;QACrB,IAAI,CAACC,OAAO,GAAGA;QAEf,k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AAI,CAACgB,MAAM,OAAOe;QAElB,+CAA+C;QAC/C,IAAI,CAACb,UAAU,CAACF;QAEhB,OAAOA,KAAKf,IAAI;IAClB;IAEA;;;GAGC,GACD,CAAQ,CAAC+B,OAAOC,QAAQ,CAAC,GAAkC;QACzD,IAAIC,UAAU,IAAI,CAACrB,IAAI,CAACT,IAAI;QAC5B,MAAO8B,WAAWA,YAAY,IAAI,CAACpB,IAAI,CAAE;YACvC,mDAAmD;YACnD,MAAME,OAAOkB;YACb,MAAM;gBAAClB,KAAKhB,GAAG;gBAAEgB,KAAKf,IAAI;aAAC;YAC3BiC,UAAUA,QAAQ9B,IAAI;QACxB;IACF;IAEA;;;;;;;;;GASC,GACD,AAAO+B,OAAOnC,GAAW,EAAQ;QAC/B,MAAMgB,OAAO,IAAI,CAACN,KAAK,CAACiB,GAAG,CAAC3B;QAC5B,IAAI,CAACgB,MAAM;QAEX,IAAI,CAACC,UAAU,CAACD;QAChB,IAAI,CAACN,KAAK,CAACmB,MAAM,CAAC7B;QAClB,IAAI,CAACY,SAAS,IAAII,KAAKd,IAAI;IAC7B;IAEA;;GAEC,GACD,IAAWA,OAAe;QACxB,OAAO,IAAI,CAACQ,KAAK,CAACR,IAAI;IACxB;IAEA;;;GAGC,GACD,IAAWkC,cAAsB;QAC/B,OAAO,IAAI,CAACxB,SAAS;IACvB;AACF","ignoreList":[0]} |
| import { AppRenderSpan, NextNodeServerSpan } from './trace/constants'; | ||
| import { isRequestInsightsEnabled, recordRequestInsightFetch } from './trace/request-insights'; | ||
| import { getRequestInsightsIdentity } from './trace/request-insights-identity'; | ||
| import { getTracer, SpanKind } from './trace/tracer'; | ||
| import { CACHE_ONE_YEAR_SECONDS, INFINITE_CACHE, NEXT_CACHE_TAG_MAX_ITEMS, NEXT_CACHE_TAG_MAX_LENGTH } from '../../lib/constants'; | ||
| import { markCurrentScopeAsDynamic } from '../app-render/dynamic-rendering'; | ||
| import { makeHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { makeDynamicHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { createDedupeFetch } from './dedupe-fetch'; | ||
@@ -89,17 +90,22 @@ import { getCacheSignal } from '../app-render/work-unit-async-storage.external'; | ||
| }); | ||
| if (isRequestInsightsEnabled() && workStore.requestId) { | ||
| recordRequestInsightFetch({ | ||
| requestId: workStore.requestId, | ||
| htmlRequestId: workStore.htmlRequestId, | ||
| route: workStore.route | ||
| }, { | ||
| url: metric.url, | ||
| method: metric.method, | ||
| statusCode: metric.status, | ||
| startTime: metric.start, | ||
| durationMs: metric.end - metric.start, | ||
| cacheStatus: metric.cacheStatus, | ||
| cacheReason: metric.cacheReason, | ||
| index: metric.idx | ||
| }); | ||
| if (isRequestInsightsEnabled()) { | ||
| const requestInsightsIdentity = getRequestInsightsIdentity(); | ||
| const requestInsightsRequestId = (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId) ?? workStore.requestId; | ||
| if (requestInsightsRequestId) { | ||
| recordRequestInsightFetch({ | ||
| requestId: requestInsightsRequestId, | ||
| kind: requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.kind, | ||
| htmlRequestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId) ?? workStore.htmlRequestId, | ||
| route: workStore.route | ||
| }, { | ||
| url: metric.url, | ||
| method: metric.method, | ||
| statusCode: metric.status, | ||
| startTime: metric.start, | ||
| durationMs: metric.end - metric.start, | ||
| cacheStatus: metric.cacheStatus, | ||
| cacheReason: metric.cacheReason, | ||
| index: metric.idx | ||
| }); | ||
| } | ||
| } | ||
@@ -419,3 +425,3 @@ if (!workStore.shouldTrackFetchMetrics) { | ||
| } | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'validation-client': | ||
@@ -534,3 +540,3 @@ break; | ||
| } | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'request': | ||
@@ -828,3 +834,3 @@ if (process.env.NODE_ENV === 'development' && workUnitStore.stagedRendering) { | ||
| } | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'request': | ||
@@ -863,3 +869,3 @@ if (process.env.NODE_ENV === 'development' && workUnitStore.stagedRendering) { | ||
| case 'validation-client': | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'request': | ||
@@ -866,0 +872,0 @@ if (process.env.NODE_ENV === 'development' && workUnitStore.stagedRendering) { |
@@ -52,9 +52,28 @@ import path from 'path'; | ||
| }; | ||
| // Measured retained cost of a cache entry beyond its strings (LRUNode, | ||
| // Map slot, string header): ~120 bytes. Counting it keeps the entry count | ||
| // bounded even when keys are short, so the budget approximates retained | ||
| // bytes. | ||
| const FS_LRU_ENTRY_OVERHEAD = 128; | ||
| const FS_LRU_MAX_SIZE = 8 * 1024 * 1024; | ||
| // The pathname passed to getItem is usually a V8 slice of the full request | ||
| // URL, and a sliced string retains its parent — including the query string — | ||
| // for as long as the cache holds the key. Store a flat copy instead. | ||
| // The JSON round-trip returns an equal string for every input (unlike a | ||
| // Buffer round-trip, which replaces lone surrogates), so distinct keys can | ||
| // never collide on the stored copy. | ||
| function flatKeyCopy(key) { | ||
| return JSON.parse(JSON.stringify(key)); | ||
| } | ||
| // Cached result for paths that resolve to nothing. Not null, so that a | ||
| // cached miss can't be conflated with an uncached key (undefined). | ||
| const notFound = Symbol('not-found'); | ||
| export async function setupFsCheck(opts) { | ||
| const getItemsLru = !opts.dev ? new LRUCache(1024 * 1024, function length(value) { | ||
| if (!value) { | ||
| // Null entries (negative cache) still need a non-zero size for LRU eviction | ||
| return 1; | ||
| const getItemsLru = !opts.dev ? new LRUCache(FS_LRU_MAX_SIZE, function length(value, key) { | ||
| const size = FS_LRU_ENTRY_OVERHEAD + key.length; | ||
| if (value === notFound) { | ||
| // Negative cache entries only retain their key. | ||
| return size; | ||
| } | ||
| return (value.fsPath || '').length + value.itemPath.length + value.type.length; | ||
| return size + (value.fsPath || '').length + value.itemPath.length + value.type.length; | ||
| }) : undefined; | ||
@@ -283,4 +302,4 @@ // routes that have _next/data endpoints (SSG/SSP) | ||
| const lruResult = getItemsLru == null ? void 0 : getItemsLru.get(itemKey); | ||
| if (lruResult) { | ||
| return lruResult; | ||
| if (lruResult !== undefined) { | ||
| return lruResult === notFound ? null : lruResult; | ||
| } | ||
@@ -506,9 +525,11 @@ const { basePath } = opts.config; | ||
| itemsRoot, | ||
| itemPath: curItemPath | ||
| // itemPath is usually a slice of the request URL too; keep a | ||
| // flat copy so the cached value doesn't retain the full URL. | ||
| itemPath: flatKeyCopy(curItemPath) | ||
| }; | ||
| getItemsLru == null ? void 0 : getItemsLru.set(itemKey, itemResult); | ||
| getItemsLru == null ? void 0 : getItemsLru.set(flatKeyCopy(itemKey), itemResult); | ||
| return itemResult; | ||
| } | ||
| } | ||
| getItemsLru == null ? void 0 : getItemsLru.set(itemKey, null); | ||
| getItemsLru == null ? void 0 : getItemsLru.set(flatKeyCopy(itemKey), notFound); | ||
| return null; | ||
@@ -515,0 +536,0 @@ }, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/router-utils/filesystem.ts"],"sourcesContent":["import type {\n FunctionsConfigManifest,\n ManifestRoute,\n PrerenderManifest,\n RoutesManifest,\n} from '../../../build'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'\nimport type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport type { __ApiPreviewProps } from '../../api-utils'\n\nimport path from 'path'\nimport fs from 'fs/promises'\nimport * as Log from '../../../build/output/log'\nimport setupDebug from 'next/dist/compiled/debug'\nimport { LRUCache } from '../lru-cache'\nimport loadCustomRoutes, { type Rewrite } from '../../../lib/load-custom-routes'\nimport { modifyRouteRegex } from '../../../lib/redirect-status'\nimport { FileType, fileExists } from '../../../lib/file-exists'\nimport { recursiveReadDir } from '../../../lib/recursive-readdir'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\nimport { getPathMatch } from '../../../shared/lib/router/utils/path-match'\nimport {\n getNamedRouteRegex,\n getRouteRegex,\n} from '../../../shared/lib/router/utils/route-regex'\nimport { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'\nimport { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'\nimport { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'\nimport { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'\nimport { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport {\n APP_PATH_ROUTES_MANIFEST,\n BUILD_ID_FILE,\n FUNCTIONS_CONFIG_MANIFEST,\n MIDDLEWARE_MANIFEST,\n PAGES_MANIFEST,\n PRERENDER_MANIFEST,\n ROUTES_MANIFEST,\n} from '../../../shared/lib/constants'\nimport { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'\nimport { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { encodeURIPath } from '../../../shared/lib/encode-uri-path'\nimport { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'\n\nexport type FsOutput = {\n type:\n | 'appFile'\n | 'pageFile'\n | 'nextImage'\n | 'publicFolder'\n | 'nextStaticFolder'\n | 'legacyStaticFolder'\n | 'devVirtualFsItem'\n\n itemPath: string\n fsPath?: string\n itemsRoot?: string\n locale?: string\n}\n\nconst debug = setupDebug('next:router-server:filesystem')\n\nexport type FilesystemDynamicRoute = ManifestRoute & {\n /**\n * The path matcher that can be used to match paths against this route.\n */\n match: PatchMatcher\n}\n\nexport const buildCustomRoute = <T>(\n type: 'redirect' | 'header' | 'rewrite' | 'before_files_rewrite',\n item: T & { source: string },\n basePath?: string,\n caseSensitive?: boolean\n): T & { match: PatchMatcher; check?: boolean; regex: string } => {\n const restrictedRedirectPaths = ['/_next'].map((p) =>\n basePath ? `${basePath}${p}` : p\n )\n let builtRegex = ''\n const match = getPathMatch(item.source, {\n strict: true,\n removeUnnamedParams: true,\n regexModifier: (regex: string) => {\n if (!(item as any).internal) {\n regex = modifyRouteRegex(\n regex,\n type === 'redirect' ? restrictedRedirectPaths : undefined\n )\n }\n builtRegex = regex\n return builtRegex\n },\n sensitive: caseSensitive,\n })\n\n return {\n ...item,\n regex: builtRegex,\n ...(type === 'rewrite' ? { check: true } : {}),\n match,\n }\n}\n\nexport async function setupFsCheck(opts: {\n dir: string\n dev: boolean\n minimalMode?: boolean\n config: NextConfigRuntime\n}) {\n const getItemsLru = !opts.dev\n ? new LRUCache<FsOutput | null>(1024 * 1024, function length(value) {\n if (!value) {\n // Null entries (negative cache) still need a non-zero size for LRU eviction\n return 1\n }\n return (\n (value.fsPath || '').length +\n value.itemPath.length +\n value.type.length\n )\n })\n : undefined\n\n // routes that have _next/data endpoints (SSG/SSP)\n const nextDataRoutes = new Set<string>()\n const publicFolderItems = new Set<string>()\n const nextStaticFolderItems = new Set<string>()\n const legacyStaticFolderItems = new Set<string>()\n\n const appFiles = new Set<string>()\n const pageFiles = new Set<string>()\n // Map normalized path to the file path. This is essential\n // for parallel and group routes as their original path\n // cannot be restored from the request path.\n // Example:\n // [normalized-path] -> [file-path]\n // /icon-<hash>.png -> .../app/@parallel/icon.png\n // /icon-<hash>.png -> .../app/(group)/icon.png\n // /icon.png -> .../app/icon.png\n const staticMetadataFiles = new Map<string, string>()\n let dynamicRoutes: FilesystemDynamicRoute[] = []\n\n let middlewareMatcher:\n | ReturnType<typeof getMiddlewareRouteMatcher>\n | undefined = () => false\n\n const distDir = path.join(opts.dir, opts.config.distDir)\n const publicFolderPath = path.join(opts.dir, 'public')\n const nextStaticFolderPath = path.join(distDir, 'static')\n const legacyStaticFolderPath = path.join(opts.dir, 'static')\n let customRoutes: UnwrapPromise<ReturnType<typeof loadCustomRoutes>> = {\n redirects: [],\n rewrites: {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n onMatchHeaders: [],\n headers: [],\n }\n let buildId = 'development'\n let previewProps: __ApiPreviewProps\n\n if (!opts.dev) {\n const buildIdPath = path.join(opts.dir, opts.config.distDir, BUILD_ID_FILE)\n try {\n buildId = await fs.readFile(buildIdPath, 'utf8')\n } catch (err: any) {\n if (err.code !== 'ENOENT') throw err\n throw new Error(\n `Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n )\n }\n\n try {\n for (const file of await recursiveReadDir(publicFolderPath)) {\n // Ensure filename is encoded and normalized.\n publicFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(legacyStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n legacyStaticFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n Log.warn(\n `The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`\n )\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(nextStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n nextStaticFolderItems.add(\n path.posix.join(\n '/_next/static',\n encodeURIPath(normalizePathSep(file))\n )\n )\n }\n } catch (err) {\n if (opts.config.output !== 'standalone') throw err\n }\n\n const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)\n const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST)\n const middlewareManifestPath = path.join(\n distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n const functionsConfigManifestPath = path.join(\n distDir,\n 'server',\n FUNCTIONS_CONFIG_MANIFEST\n )\n const pagesManifestPath = path.join(distDir, 'server', PAGES_MANIFEST)\n const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)\n\n const routesManifest = JSON.parse(\n await fs.readFile(routesManifestPath, 'utf8')\n ) as RoutesManifest\n\n previewProps = (\n JSON.parse(\n await fs.readFile(prerenderManifestPath, 'utf8')\n ) as PrerenderManifest\n ).preview\n\n const middlewareManifest = JSON.parse(\n await fs.readFile(middlewareManifestPath, 'utf8').catch(() => '{}')\n ) as MiddlewareManifest\n\n const functionsConfigManifest = JSON.parse(\n await fs.readFile(functionsConfigManifestPath, 'utf8').catch(() => '{}')\n ) as FunctionsConfigManifest\n\n const pagesManifest = JSON.parse(\n await fs.readFile(pagesManifestPath, 'utf8')\n )\n const appRoutesManifest = JSON.parse(\n await fs.readFile(appRoutesManifestPath, 'utf8').catch(() => '{}')\n )\n\n for (const key of Object.keys(pagesManifest)) {\n // ensure the non-locale version is in the set\n if (opts.config.i18n) {\n pageFiles.add(\n normalizeLocalePath(key, opts.config.i18n.locales).pathname\n )\n } else {\n pageFiles.add(key)\n }\n }\n for (const key of Object.keys(appRoutesManifest)) {\n appFiles.add(appRoutesManifest[key])\n }\n\n const escapedBuildId = escapeStringRegexp(buildId)\n\n for (const route of routesManifest.dataRoutes) {\n if (isDynamicRoute(route.page)) {\n const routeRegex = getNamedRouteRegex(route.page, {\n prefixRouteKeys: true,\n })\n dynamicRoutes.push({\n ...route,\n regex: routeRegex.re.toString(),\n namedRegex: routeRegex.namedRegex,\n routeKeys: routeRegex.routeKeys,\n match: getRouteMatcher({\n // TODO: fix this in the manifest itself, must also be fixed in\n // upstream builder that relies on this\n re: opts.config.i18n\n ? new RegExp(\n route.dataRouteRegex.replace(\n `/${escapedBuildId}/`,\n `/${escapedBuildId}/(?<nextLocale>[^/]+?)/`\n )\n )\n : new RegExp(route.dataRouteRegex),\n groups: routeRegex.groups,\n }),\n })\n }\n nextDataRoutes.add(route.page)\n }\n\n for (const route of routesManifest.dynamicRoutes) {\n // If a route is marked as skipInternalRouting, it's not for the internal\n // router, and instead has been added to support external routers.\n if (route.skipInternalRouting) {\n continue\n }\n\n dynamicRoutes.push({\n ...route,\n match: getRouteMatcher(getRouteRegex(route.page)),\n })\n }\n\n if (middlewareManifest.middleware?.['/']?.matchers) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n middlewareManifest.middleware?.['/']?.matchers\n )\n } else if (functionsConfigManifest?.functions['/_middleware']) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n functionsConfigManifest.functions['/_middleware'].matchers ?? [\n { regexp: '.*', originalSource: '/:path*' },\n ]\n )\n }\n\n customRoutes = {\n redirects: routesManifest.redirects,\n rewrites: routesManifest.rewrites\n ? Array.isArray(routesManifest.rewrites)\n ? {\n beforeFiles: [],\n afterFiles: routesManifest.rewrites,\n fallback: [],\n }\n : routesManifest.rewrites\n : {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n headers: routesManifest.headers,\n onMatchHeaders: routesManifest.onMatchHeaders,\n }\n } else {\n // dev handling\n customRoutes = await loadCustomRoutes(opts.config)\n\n previewProps = {\n previewModeId: (require('crypto') as typeof import('crypto'))\n .randomBytes(16)\n .toString('hex'),\n previewModeSigningKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n previewModeEncryptionKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n }\n }\n\n const headers = customRoutes.headers.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const onMatchHeaders = customRoutes.onMatchHeaders.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const redirects = customRoutes.redirects.map((item) =>\n buildCustomRoute(\n 'redirect',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const rewrites = {\n beforeFiles: customRoutes.rewrites.beforeFiles.map((item) =>\n buildCustomRoute('before_files_rewrite', item)\n ),\n afterFiles: customRoutes.rewrites.afterFiles.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n fallback: customRoutes.rewrites.fallback.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n }\n\n const { i18n } = opts.config\n\n const handleLocale = (pathname: string, locales?: string[]) => {\n let locale: string | undefined\n\n if (i18n) {\n const i18nResult = normalizeLocalePath(pathname, locales || i18n.locales)\n\n pathname = i18nResult.pathname\n locale = i18nResult.detectedLocale\n }\n return { locale, pathname }\n }\n\n debug('nextDataRoutes', nextDataRoutes)\n debug('dynamicRoutes', dynamicRoutes)\n debug('customRoutes', customRoutes)\n debug('publicFolderItems', publicFolderItems)\n debug('nextStaticFolderItems', nextStaticFolderItems)\n debug('pageFiles', pageFiles)\n debug('appFiles', appFiles)\n\n let ensureFn: (item: FsOutput) => Promise<void> | undefined\n\n const normalizers = {\n // Because we can't know if the app directory is enabled or not at this\n // stage, we assume that it is.\n rsc: new RSCPathnameNormalizer(),\n }\n\n return {\n headers,\n onMatchHeaders,\n rewrites,\n redirects,\n\n buildId,\n handleLocale,\n\n appFiles,\n pageFiles,\n staticMetadataFiles,\n dynamicRoutes,\n nextDataRoutes,\n\n exportPathMapRoutes: undefined as\n | undefined\n | ReturnType<typeof buildCustomRoute<Rewrite>>[],\n\n devVirtualFsItems: new Set<string>(),\n\n previewProps,\n middlewareMatcher: middlewareMatcher as MiddlewareRouteMatch | undefined,\n\n ensureCallback(fn: typeof ensureFn) {\n ensureFn = fn\n },\n\n async getItem(itemPath: string): Promise<FsOutput | null> {\n const originalItemPath = itemPath\n const itemKey = originalItemPath\n const lruResult = getItemsLru?.get(itemKey)\n\n if (lruResult) {\n return lruResult\n }\n\n const { basePath } = opts.config\n\n const hasBasePath = pathHasPrefix(itemPath, basePath)\n\n // Return null if path doesn't start with basePath\n if (basePath && !hasBasePath) {\n return null\n }\n\n // Remove basePath if it exists.\n if (basePath && hasBasePath) {\n itemPath = removePathPrefix(itemPath, basePath) || '/'\n }\n\n // Simulate minimal mode requests by normalizing RSC and postponed\n // requests.\n if (opts.minimalMode) {\n if (normalizers.rsc.match(itemPath)) {\n itemPath = normalizers.rsc.normalize(itemPath, true)\n }\n }\n\n if (itemPath !== '/' && itemPath.endsWith('/')) {\n itemPath = itemPath.substring(0, itemPath.length - 1)\n }\n\n let decodedItemPath = itemPath\n\n try {\n decodedItemPath = decodeURIComponent(itemPath)\n } catch {}\n\n if (itemPath === '/_next/image') {\n return {\n itemPath,\n type: 'nextImage',\n }\n }\n\n if (opts.dev && isMetadataRouteFile(itemPath, [], false)) {\n const fsPath = staticMetadataFiles.get(itemPath)\n if (fsPath) {\n return {\n // \"nextStaticFolder\" sets Cache-Control \"no-store\" on dev.\n type: 'nextStaticFolder',\n fsPath,\n itemPath: fsPath,\n }\n }\n }\n\n const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [\n [this.devVirtualFsItems, 'devVirtualFsItem'],\n [nextStaticFolderItems, 'nextStaticFolder'],\n [legacyStaticFolderItems, 'legacyStaticFolder'],\n [publicFolderItems, 'publicFolder'],\n [appFiles, 'appFile'],\n [pageFiles, 'pageFile'],\n ]\n\n for (let [items, type] of itemsToCheck) {\n let locale: string | undefined\n let curItemPath = itemPath\n let curDecodedItemPath = decodedItemPath\n\n const isDynamicOutput = type === 'pageFile' || type === 'appFile'\n\n if (i18n) {\n const localeResult = handleLocale(\n itemPath,\n // legacy behavior allows visiting static assets under\n // default locale but no other locale\n isDynamicOutput\n ? undefined\n : [\n i18n?.defaultLocale,\n // default locales from domains need to be matched too\n ...(i18n.domains?.map((item) => item.defaultLocale) || []),\n ]\n )\n\n if (localeResult.pathname !== curItemPath) {\n curItemPath = localeResult.pathname\n locale = localeResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n }\n\n if (type === 'legacyStaticFolder') {\n if (!pathHasPrefix(curItemPath, '/static')) {\n continue\n }\n curItemPath = curItemPath.substring('/static'.length)\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n if (\n type === 'nextStaticFolder' &&\n !pathHasPrefix(curItemPath, '/_next/static')\n ) {\n continue\n }\n\n const nextDataPrefix = `/_next/data/${buildId}/`\n\n if (\n type === 'pageFile' &&\n curItemPath.startsWith(nextDataPrefix) &&\n curItemPath.endsWith('.json')\n ) {\n items = nextDataRoutes\n // remove _next/data/<build-id> prefix\n curItemPath = curItemPath.substring(nextDataPrefix.length - 1)\n\n // remove .json postfix\n curItemPath = curItemPath.substring(\n 0,\n curItemPath.length - '.json'.length\n )\n const curLocaleResult = handleLocale(curItemPath)\n curItemPath =\n curLocaleResult.pathname === '/index'\n ? '/'\n : curLocaleResult.pathname\n\n locale = curLocaleResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n let matchedItem = items.has(curItemPath)\n\n // check decoded variant as well\n if (!matchedItem && !opts.dev) {\n matchedItem = items.has(curDecodedItemPath)\n if (matchedItem) curItemPath = curDecodedItemPath\n else {\n // x-ref: https://github.com/vercel/next.js/issues/54008\n // There're cases that urls get decoded before requests, we should support both encoded and decoded ones.\n // e.g. nginx could decode the proxy urls, the below ones should be treated as the same:\n // decoded version: `/_next/static/chunks/pages/blog/[slug]-d4858831b91b69f6.js`\n // encoded version: `/_next/static/chunks/pages/blog/%5Bslug%5D-d4858831b91b69f6.js`\n try {\n // encode the special characters in the path and retrieve again to determine if path exists.\n const encodedCurItemPath = encodeURIPath(curItemPath)\n matchedItem = items.has(encodedCurItemPath)\n } catch {}\n }\n }\n\n if (matchedItem || opts.dev) {\n let fsPath: string | undefined\n let itemsRoot: string | undefined\n\n switch (type) {\n case 'nextStaticFolder': {\n itemsRoot = nextStaticFolderPath\n curItemPath = curItemPath.substring('/_next/static'.length)\n break\n }\n case 'legacyStaticFolder': {\n itemsRoot = legacyStaticFolderPath\n break\n }\n case 'publicFolder': {\n itemsRoot = publicFolderPath\n break\n }\n case 'appFile':\n case 'pageFile':\n case 'nextImage':\n case 'devVirtualFsItem': {\n break\n }\n default: {\n ;(type) satisfies never\n }\n }\n\n if (itemsRoot && curItemPath) {\n fsPath = path.posix.join(itemsRoot, curItemPath)\n }\n\n // dynamically check fs in development so we don't\n // have to wait on the watcher\n if (!matchedItem && opts.dev) {\n const isStaticAsset = (\n [\n 'nextStaticFolder',\n 'publicFolder',\n 'legacyStaticFolder',\n ] as (typeof type)[]\n ).includes(type)\n\n if (isStaticAsset && itemsRoot) {\n let found = fsPath && (await fileExists(fsPath, FileType.File))\n\n if (!found) {\n try {\n // In dev, we ensure encoded paths match\n // decoded paths on the filesystem so check\n // that variation as well\n const tempItemPath = decodeURIComponent(curItemPath)\n fsPath = path.posix.join(itemsRoot, tempItemPath)\n found = await fileExists(fsPath, FileType.File)\n } catch {}\n\n if (!found) {\n continue\n }\n }\n } else if (type === 'pageFile' || type === 'appFile') {\n const isAppFile = type === 'appFile'\n\n // Attempt to ensure the page/app file is compiled and ready\n if (ensureFn) {\n const ensureItemPath = isAppFile\n ? normalizeMetadataRoute(curItemPath)\n : curItemPath\n\n try {\n await ensureFn({ type, itemPath: ensureItemPath })\n } catch (error) {\n // If ensure failed, skip this item and continue to the next one\n continue\n }\n }\n } else {\n continue\n }\n }\n\n // i18n locales aren't matched for app dir\n if (type === 'appFile' && locale && locale !== i18n?.defaultLocale) {\n continue\n }\n\n const itemResult = {\n type,\n fsPath,\n locale,\n itemsRoot,\n itemPath: curItemPath,\n }\n\n getItemsLru?.set(itemKey, itemResult)\n return itemResult\n }\n }\n\n getItemsLru?.set(itemKey, null)\n return null\n },\n getDynamicRoutes() {\n // this should include data routes\n return this.dynamicRoutes\n },\n getMiddlewareMatchers() {\n return this.middlewareMatcher\n },\n }\n}\n"],"names":["path","fs","Log","setupDebug","LRUCache","loadCustomRoutes","modifyRouteRegex","FileType","fileExists","recursiveReadDir","isDynamicRoute","escapeStringRegexp","getPathMatch","getNamedRouteRegex","getRouteRegex","getRouteMatcher","pathHasPrefix","normalizeLocalePath","removePathPrefix","getMiddlewareRouteMatcher","APP_PATH_ROUTES_MANIFEST","BUILD_ID_FILE","FUNCTIONS_CONFIG_MANIFEST","MIDDLEWARE_MANIFEST","PAGES_MANIFEST","PRERENDER_MANIFEST","ROUTES_MANIFEST","normalizePathSep","normalizeMetadataRoute","RSCPathnameNormalizer","encodeURIPath","isMetadataRouteFile","debug","buildCustomRoute","type","item","basePath","caseSensitive","restrictedRedirectPaths","map","p","builtRegex","match","source","strict","removeUnnamedParams","regexModifier","regex","internal","undefined","sensitive","check","setupFsCheck","opts","getItemsLru","dev","length","value","fsPath","itemPath","nextDataRoutes","Set","publicFolderItems","nextStaticFolderItems","legacyStaticFolderItems","appFiles","pageFiles","staticMetadataFiles","Map","dynamicRoutes","middlewareMatcher","distDir","join","dir","config","publicFolderPath","nextStaticFolderPath","legacyStaticFolderPath","customRoutes","redirects","rewrites","beforeFiles","afterFiles","fallback","onMatchHeaders","headers","buildId","previewProps","middlewareManifest","buildIdPath","readFile","err","code","Error","file","add","warn","posix","output","routesManifestPath","prerenderManifestPath","middlewareManifestPath","functionsConfigManifestPath","pagesManifestPath","appRoutesManifestPath","routesManifest","JSON","parse","preview","catch","functionsConfigManifest","pagesManifest","appRoutesManifest","key","Object","keys","i18n","locales","pathname","escapedBuildId","route","dataRoutes","page","routeRegex","prefixRouteKeys","push","re","toString","namedRegex","routeKeys","RegExp","dataRouteRegex","replace","groups","skipInternalRouting","middleware","matchers","functions","regexp","originalSource","Array","isArray","previewModeId","require","randomBytes","previewModeSigningKey","previewModeEncryptionKey","experimental","caseSensitiveRoutes","handleLocale","locale","i18nResult","detectedLocale","ensureFn","normalizers","rsc","exportPathMapRoutes","devVirtualFsItems","ensureCallback","fn","getItem","originalItemPath","itemKey","lruResult","get","hasBasePath","minimalMode","normalize","endsWith","substring","decodedItemPath","decodeURIComponent","itemsToCheck","items","curItemPath","curDecodedItemPath","isDynamicOutput","localeResult","defaultLocale","domains","nextDataPrefix","startsWith","curLocaleResult","matchedItem","has","encodedCurItemPath","itemsRoot","isStaticAsset","includes","found","File","tempItemPath","isAppFile","ensureItemPath","error","itemResult","set","getDynamicRoutes","getMiddlewareMatchers"],"mappings":"AAaA,OAAOA,UAAU,OAAM;AACvB,OAAOC,QAAQ,cAAa;AAC5B,YAAYC,SAAS,4BAA2B;AAChD,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,QAAQ,QAAQ,eAAc;AACvC,OAAOC,sBAAwC,kCAAiC;AAChF,SAASC,gBAAgB,QAAQ,+BAA8B;AAC/D,SAASC,QAAQ,EAAEC,UAAU,QAAQ,2BAA0B;AAC/D,SAASC,gBAAgB,QAAQ,iCAAgC;AACjE,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,kBAAkB,QAAQ,oCAAmC;AACtE,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SACEC,kBAAkB,EAClBC,aAAa,QACR,+CAA8C;AACrD,SAASC,eAAe,QAAQ,iDAAgD;AAChF,SAASC,aAAa,QAAQ,mDAAkD;AAChF,SAASC,mBAAmB,QAAQ,iDAAgD;AACpF,SAASC,gBAAgB,QAAQ,sDAAqD;AACtF,SAASC,yBAAyB,QAAQ,4DAA2D;AACrG,SACEC,wBAAwB,EACxBC,aAAa,EACbC,yBAAyB,EACzBC,mBAAmB,EACnBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,QACV,gCAA+B;AACtC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,sBAAsB,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;oCACzB,MAAME,eAAepB,mBAAmBG;oCACxCpH,SAAS1D,KAAKiG,KAAK,CAACzB,IAAI,CAACkH,WAAWK;oCACpCF,QAAQ,MAAMrL,WAAWkD,QAAQnD,SAASuL,IAAI;gCAChD,EAAE,OAAM,CAAC;gCAET,IAAI,CAACD,OAAO;oCACV;gCACF;4BACF;wBACF,OAAO,IAAI3J,SAAS,cAAcA,SAAS,WAAW;4BACpD,MAAM8J,YAAY9J,SAAS;4BAE3B,4DAA4D;4BAC5D,IAAIuH,UAAU;gCACZ,MAAMwC,iBAAiBD,YACnBpK,uBAAuBkJ,eACvBA;gCAEJ,IAAI;oCACF,MAAMrB,SAAS;wCAAEvH;wCAAMyB,UAAUsI;oCAAe;gCAClD,EAAE,OAAOC,OAAO;oCAEd;gCACF;4BACF;wBACF,OAAO;4BACL;wBACF;oBACF;oBAEA,0CAA0C;oBAC1C,IAAIhK,SAAS,aAAaoH,UAAUA,YAAWlC,wBAAAA,KAAM8D,aAAa,GAAE;wBAClE;oBACF;oBAEA,MAAMiB,aAAa;wBACjBjK;wBACAwB;wBACA4F;wBACAoC;wBACA/H,UAAUmH;oBACZ;oBAEAxH,+BAAAA,YAAa8I,GAAG,CAAClC,SAASiC;oBAC1B,OAAOA;gBACT;YACF;YAEA7I,+BAAAA,YAAa8I,GAAG,CAAClC,SAAS;YAC1B,OAAO;QACT;QACAmC;YACE,kCAAkC;YAClC,OAAO,IAAI,CAAChI,aAAa;QAC3B;QACAiI;YACE,OAAO,IAAI,CAAChI,iBAAiB;QAC/B;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/router-utils/filesystem.ts"],"sourcesContent":["import type {\n FunctionsConfigManifest,\n ManifestRoute,\n PrerenderManifest,\n RoutesManifest,\n} from '../../../build'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'\nimport type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport type { __ApiPreviewProps } from '../../api-utils'\n\nimport path from 'path'\nimport fs from 'fs/promises'\nimport * as Log from '../../../build/output/log'\nimport setupDebug from 'next/dist/compiled/debug'\nimport { LRUCache } from '../lru-cache'\nimport loadCustomRoutes, { type Rewrite } from '../../../lib/load-custom-routes'\nimport { modifyRouteRegex } from '../../../lib/redirect-status'\nimport { FileType, fileExists } from '../../../lib/file-exists'\nimport { recursiveReadDir } from '../../../lib/recursive-readdir'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\nimport { getPathMatch } from '../../../shared/lib/router/utils/path-match'\nimport {\n getNamedRouteRegex,\n getRouteRegex,\n} from '../../../shared/lib/router/utils/route-regex'\nimport { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'\nimport { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'\nimport { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'\nimport { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'\nimport { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport {\n APP_PATH_ROUTES_MANIFEST,\n BUILD_ID_FILE,\n FUNCTIONS_CONFIG_MANIFEST,\n MIDDLEWARE_MANIFEST,\n PAGES_MANIFEST,\n PRERENDER_MANIFEST,\n ROUTES_MANIFEST,\n} from '../../../shared/lib/constants'\nimport { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'\nimport { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { encodeURIPath } from '../../../shared/lib/encode-uri-path'\nimport { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'\n\nexport type FsOutput = {\n type:\n | 'appFile'\n | 'pageFile'\n | 'nextImage'\n | 'publicFolder'\n | 'nextStaticFolder'\n | 'legacyStaticFolder'\n | 'devVirtualFsItem'\n\n itemPath: string\n fsPath?: string\n itemsRoot?: string\n locale?: string\n}\n\nconst debug = setupDebug('next:router-server:filesystem')\n\nexport type FilesystemDynamicRoute = ManifestRoute & {\n /**\n * The path matcher that can be used to match paths against this route.\n */\n match: PatchMatcher\n}\n\nexport const buildCustomRoute = <T>(\n type: 'redirect' | 'header' | 'rewrite' | 'before_files_rewrite',\n item: T & { source: string },\n basePath?: string,\n caseSensitive?: boolean\n): T & { match: PatchMatcher; check?: boolean; regex: string } => {\n const restrictedRedirectPaths = ['/_next'].map((p) =>\n basePath ? `${basePath}${p}` : p\n )\n let builtRegex = ''\n const match = getPathMatch(item.source, {\n strict: true,\n removeUnnamedParams: true,\n regexModifier: (regex: string) => {\n if (!(item as any).internal) {\n regex = modifyRouteRegex(\n regex,\n type === 'redirect' ? restrictedRedirectPaths : undefined\n )\n }\n builtRegex = regex\n return builtRegex\n },\n sensitive: caseSensitive,\n })\n\n return {\n ...item,\n regex: builtRegex,\n ...(type === 'rewrite' ? { check: true } : {}),\n match,\n }\n}\n\n// Measured retained cost of a cache entry beyond its strings (LRUNode,\n// Map slot, string header): ~120 bytes. Counting it keeps the entry count\n// bounded even when keys are short, so the budget approximates retained\n// bytes.\nconst FS_LRU_ENTRY_OVERHEAD = 128\nconst FS_LRU_MAX_SIZE = 8 * 1024 * 1024\n\n// The pathname passed to getItem is usually a V8 slice of the full request\n// URL, and a sliced string retains its parent — including the query string —\n// for as long as the cache holds the key. Store a flat copy instead.\n// The JSON round-trip returns an equal string for every input (unlike a\n// Buffer round-trip, which replaces lone surrogates), so distinct keys can\n// never collide on the stored copy.\nfunction flatKeyCopy(key: string): string {\n return JSON.parse(JSON.stringify(key))\n}\n\n// Cached result for paths that resolve to nothing. Not null, so that a\n// cached miss can't be conflated with an uncached key (undefined).\nconst notFound = Symbol('not-found')\n\nexport async function setupFsCheck(opts: {\n dir: string\n dev: boolean\n minimalMode?: boolean\n config: NextConfigRuntime\n}) {\n const getItemsLru = !opts.dev\n ? new LRUCache<FsOutput | typeof notFound>(FS_LRU_MAX_SIZE, function length(\n value,\n key\n ) {\n const size = FS_LRU_ENTRY_OVERHEAD + key.length\n if (value === notFound) {\n // Negative cache entries only retain their key.\n return size\n }\n return (\n size +\n (value.fsPath || '').length +\n value.itemPath.length +\n value.type.length\n )\n })\n : undefined\n\n // routes that have _next/data endpoints (SSG/SSP)\n const nextDataRoutes = new Set<string>()\n const publicFolderItems = new Set<string>()\n const nextStaticFolderItems = new Set<string>()\n const legacyStaticFolderItems = new Set<string>()\n\n const appFiles = new Set<string>()\n const pageFiles = new Set<string>()\n // Map normalized path to the file path. This is essential\n // for parallel and group routes as their original path\n // cannot be restored from the request path.\n // Example:\n // [normalized-path] -> [file-path]\n // /icon-<hash>.png -> .../app/@parallel/icon.png\n // /icon-<hash>.png -> .../app/(group)/icon.png\n // /icon.png -> .../app/icon.png\n const staticMetadataFiles = new Map<string, string>()\n let dynamicRoutes: FilesystemDynamicRoute[] = []\n\n let middlewareMatcher:\n | ReturnType<typeof getMiddlewareRouteMatcher>\n | undefined = () => false\n\n const distDir = path.join(opts.dir, opts.config.distDir)\n const publicFolderPath = path.join(opts.dir, 'public')\n const nextStaticFolderPath = path.join(distDir, 'static')\n const legacyStaticFolderPath = path.join(opts.dir, 'static')\n let customRoutes: UnwrapPromise<ReturnType<typeof loadCustomRoutes>> = {\n redirects: [],\n rewrites: {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n onMatchHeaders: [],\n headers: [],\n }\n let buildId = 'development'\n let previewProps: __ApiPreviewProps\n\n if (!opts.dev) {\n const buildIdPath = path.join(opts.dir, opts.config.distDir, BUILD_ID_FILE)\n try {\n buildId = await fs.readFile(buildIdPath, 'utf8')\n } catch (err: any) {\n if (err.code !== 'ENOENT') throw err\n throw new Error(\n `Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n )\n }\n\n try {\n for (const file of await recursiveReadDir(publicFolderPath)) {\n // Ensure filename is encoded and normalized.\n publicFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(legacyStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n legacyStaticFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n Log.warn(\n `The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`\n )\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(nextStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n nextStaticFolderItems.add(\n path.posix.join(\n '/_next/static',\n encodeURIPath(normalizePathSep(file))\n )\n )\n }\n } catch (err) {\n if (opts.config.output !== 'standalone') throw err\n }\n\n const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)\n const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST)\n const middlewareManifestPath = path.join(\n distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n const functionsConfigManifestPath = path.join(\n distDir,\n 'server',\n FUNCTIONS_CONFIG_MANIFEST\n )\n const pagesManifestPath = path.join(distDir, 'server', PAGES_MANIFEST)\n const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)\n\n const routesManifest = JSON.parse(\n await fs.readFile(routesManifestPath, 'utf8')\n ) as RoutesManifest\n\n previewProps = (\n JSON.parse(\n await fs.readFile(prerenderManifestPath, 'utf8')\n ) as PrerenderManifest\n ).preview\n\n const middlewareManifest = JSON.parse(\n await fs.readFile(middlewareManifestPath, 'utf8').catch(() => '{}')\n ) as MiddlewareManifest\n\n const functionsConfigManifest = JSON.parse(\n await fs.readFile(functionsConfigManifestPath, 'utf8').catch(() => '{}')\n ) as FunctionsConfigManifest\n\n const pagesManifest = JSON.parse(\n await fs.readFile(pagesManifestPath, 'utf8')\n )\n const appRoutesManifest = JSON.parse(\n await fs.readFile(appRoutesManifestPath, 'utf8').catch(() => '{}')\n )\n\n for (const key of Object.keys(pagesManifest)) {\n // ensure the non-locale version is in the set\n if (opts.config.i18n) {\n pageFiles.add(\n normalizeLocalePath(key, opts.config.i18n.locales).pathname\n )\n } else {\n pageFiles.add(key)\n }\n }\n for (const key of Object.keys(appRoutesManifest)) {\n appFiles.add(appRoutesManifest[key])\n }\n\n const escapedBuildId = escapeStringRegexp(buildId)\n\n for (const route of routesManifest.dataRoutes) {\n if (isDynamicRoute(route.page)) {\n const routeRegex = getNamedRouteRegex(route.page, {\n prefixRouteKeys: true,\n })\n dynamicRoutes.push({\n ...route,\n regex: routeRegex.re.toString(),\n namedRegex: routeRegex.namedRegex,\n routeKeys: routeRegex.routeKeys,\n match: getRouteMatcher({\n // TODO: fix this in the manifest itself, must also be fixed in\n // upstream builder that relies on this\n re: opts.config.i18n\n ? new RegExp(\n route.dataRouteRegex.replace(\n `/${escapedBuildId}/`,\n `/${escapedBuildId}/(?<nextLocale>[^/]+?)/`\n )\n )\n : new RegExp(route.dataRouteRegex),\n groups: routeRegex.groups,\n }),\n })\n }\n nextDataRoutes.add(route.page)\n }\n\n for (const route of routesManifest.dynamicRoutes) {\n // If a route is marked as skipInternalRouting, it's not for the internal\n // router, and instead has been added to support external routers.\n if (route.skipInternalRouting) {\n continue\n }\n\n dynamicRoutes.push({\n ...route,\n match: getRouteMatcher(getRouteRegex(route.page)),\n })\n }\n\n if (middlewareManifest.middleware?.['/']?.matchers) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n middlewareManifest.middleware?.['/']?.matchers\n )\n } else if (functionsConfigManifest?.functions['/_middleware']) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n functionsConfigManifest.functions['/_middleware'].matchers ?? [\n { regexp: '.*', originalSource: '/:path*' },\n ]\n )\n }\n\n customRoutes = {\n redirects: routesManifest.redirects,\n rewrites: routesManifest.rewrites\n ? Array.isArray(routesManifest.rewrites)\n ? {\n beforeFiles: [],\n afterFiles: routesManifest.rewrites,\n fallback: [],\n }\n : routesManifest.rewrites\n : {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n headers: routesManifest.headers,\n onMatchHeaders: routesManifest.onMatchHeaders,\n }\n } else {\n // dev handling\n customRoutes = await loadCustomRoutes(opts.config)\n\n previewProps = {\n previewModeId: (require('crypto') as typeof import('crypto'))\n .randomBytes(16)\n .toString('hex'),\n previewModeSigningKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n previewModeEncryptionKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n }\n }\n\n const headers = customRoutes.headers.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const onMatchHeaders = customRoutes.onMatchHeaders.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const redirects = customRoutes.redirects.map((item) =>\n buildCustomRoute(\n 'redirect',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const rewrites = {\n beforeFiles: customRoutes.rewrites.beforeFiles.map((item) =>\n buildCustomRoute('before_files_rewrite', item)\n ),\n afterFiles: customRoutes.rewrites.afterFiles.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n fallback: customRoutes.rewrites.fallback.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n }\n\n const { i18n } = opts.config\n\n const handleLocale = (pathname: string, locales?: string[]) => {\n let locale: string | undefined\n\n if (i18n) {\n const i18nResult = normalizeLocalePath(pathname, locales || i18n.locales)\n\n pathname = i18nResult.pathname\n locale = i18nResult.detectedLocale\n }\n return { locale, pathname }\n }\n\n debug('nextDataRoutes', nextDataRoutes)\n debug('dynamicRoutes', dynamicRoutes)\n debug('customRoutes', customRoutes)\n debug('publicFolderItems', publicFolderItems)\n debug('nextStaticFolderItems', nextStaticFolderItems)\n debug('pageFiles', pageFiles)\n debug('appFiles', appFiles)\n\n let ensureFn: (item: FsOutput) => Promise<void> | undefined\n\n const normalizers = {\n // Because we can't know if the app directory is enabled or not at this\n // stage, we assume that it is.\n rsc: new RSCPathnameNormalizer(),\n }\n\n return {\n headers,\n onMatchHeaders,\n rewrites,\n redirects,\n\n buildId,\n handleLocale,\n\n appFiles,\n pageFiles,\n staticMetadataFiles,\n dynamicRoutes,\n nextDataRoutes,\n\n exportPathMapRoutes: undefined as\n | undefined\n | ReturnType<typeof buildCustomRoute<Rewrite>>[],\n\n devVirtualFsItems: new Set<string>(),\n\n previewProps,\n middlewareMatcher: middlewareMatcher as MiddlewareRouteMatch | undefined,\n\n ensureCallback(fn: typeof ensureFn) {\n ensureFn = fn\n },\n\n async getItem(itemPath: string): Promise<FsOutput | null> {\n const originalItemPath = itemPath\n const itemKey = originalItemPath\n const lruResult = getItemsLru?.get(itemKey)\n\n if (lruResult !== undefined) {\n return lruResult === notFound ? null : lruResult\n }\n\n const { basePath } = opts.config\n\n const hasBasePath = pathHasPrefix(itemPath, basePath)\n\n // Return null if path doesn't start with basePath\n if (basePath && !hasBasePath) {\n return null\n }\n\n // Remove basePath if it exists.\n if (basePath && hasBasePath) {\n itemPath = removePathPrefix(itemPath, basePath) || '/'\n }\n\n // Simulate minimal mode requests by normalizing RSC and postponed\n // requests.\n if (opts.minimalMode) {\n if (normalizers.rsc.match(itemPath)) {\n itemPath = normalizers.rsc.normalize(itemPath, true)\n }\n }\n\n if (itemPath !== '/' && itemPath.endsWith('/')) {\n itemPath = itemPath.substring(0, itemPath.length - 1)\n }\n\n let decodedItemPath = itemPath\n\n try {\n decodedItemPath = decodeURIComponent(itemPath)\n } catch {}\n\n if (itemPath === '/_next/image') {\n return {\n itemPath,\n type: 'nextImage',\n }\n }\n\n if (opts.dev && isMetadataRouteFile(itemPath, [], false)) {\n const fsPath = staticMetadataFiles.get(itemPath)\n if (fsPath) {\n return {\n // \"nextStaticFolder\" sets Cache-Control \"no-store\" on dev.\n type: 'nextStaticFolder',\n fsPath,\n itemPath: fsPath,\n }\n }\n }\n\n const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [\n [this.devVirtualFsItems, 'devVirtualFsItem'],\n [nextStaticFolderItems, 'nextStaticFolder'],\n [legacyStaticFolderItems, 'legacyStaticFolder'],\n [publicFolderItems, 'publicFolder'],\n [appFiles, 'appFile'],\n [pageFiles, 'pageFile'],\n ]\n\n for (let [items, type] of itemsToCheck) {\n let locale: string | undefined\n let curItemPath = itemPath\n let curDecodedItemPath = decodedItemPath\n\n const isDynamicOutput = type === 'pageFile' || type === 'appFile'\n\n if (i18n) {\n const localeResult = handleLocale(\n itemPath,\n // legacy behavior allows visiting static assets under\n // default locale but no other locale\n isDynamicOutput\n ? undefined\n : [\n i18n?.defaultLocale,\n // default locales from domains need to be matched too\n ...(i18n.domains?.map((item) => item.defaultLocale) || []),\n ]\n )\n\n if (localeResult.pathname !== curItemPath) {\n curItemPath = localeResult.pathname\n locale = localeResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n }\n\n if (type === 'legacyStaticFolder') {\n if (!pathHasPrefix(curItemPath, '/static')) {\n continue\n }\n curItemPath = curItemPath.substring('/static'.length)\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n if (\n type === 'nextStaticFolder' &&\n !pathHasPrefix(curItemPath, '/_next/static')\n ) {\n continue\n }\n\n const nextDataPrefix = `/_next/data/${buildId}/`\n\n if (\n type === 'pageFile' &&\n curItemPath.startsWith(nextDataPrefix) &&\n curItemPath.endsWith('.json')\n ) {\n items = nextDataRoutes\n // remove _next/data/<build-id> prefix\n curItemPath = curItemPath.substring(nextDataPrefix.length - 1)\n\n // remove .json postfix\n curItemPath = curItemPath.substring(\n 0,\n curItemPath.length - '.json'.length\n )\n const curLocaleResult = handleLocale(curItemPath)\n curItemPath =\n curLocaleResult.pathname === '/index'\n ? '/'\n : curLocaleResult.pathname\n\n locale = curLocaleResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n let matchedItem = items.has(curItemPath)\n\n // check decoded variant as well\n if (!matchedItem && !opts.dev) {\n matchedItem = items.has(curDecodedItemPath)\n if (matchedItem) curItemPath = curDecodedItemPath\n else {\n // x-ref: https://github.com/vercel/next.js/issues/54008\n // There're cases that urls get decoded before requests, we should support both encoded and decoded ones.\n // e.g. nginx could decode the proxy urls, the below ones should be treated as the same:\n // decoded version: `/_next/static/chunks/pages/blog/[slug]-d4858831b91b69f6.js`\n // encoded version: `/_next/static/chunks/pages/blog/%5Bslug%5D-d4858831b91b69f6.js`\n try {\n // encode the special characters in the path and retrieve again to determine if path exists.\n const encodedCurItemPath = encodeURIPath(curItemPath)\n matchedItem = items.has(encodedCurItemPath)\n } catch {}\n }\n }\n\n if (matchedItem || opts.dev) {\n let fsPath: string | undefined\n let itemsRoot: string | undefined\n\n switch (type) {\n case 'nextStaticFolder': {\n itemsRoot = nextStaticFolderPath\n curItemPath = curItemPath.substring('/_next/static'.length)\n break\n }\n case 'legacyStaticFolder': {\n itemsRoot = legacyStaticFolderPath\n break\n }\n case 'publicFolder': {\n itemsRoot = publicFolderPath\n break\n }\n case 'appFile':\n case 'pageFile':\n case 'nextImage':\n case 'devVirtualFsItem': {\n break\n }\n default: {\n ;(type) satisfies never\n }\n }\n\n if (itemsRoot && curItemPath) {\n fsPath = path.posix.join(itemsRoot, curItemPath)\n }\n\n // dynamically check fs in development so we don't\n // have to wait on the watcher\n if (!matchedItem && opts.dev) {\n const isStaticAsset = (\n [\n 'nextStaticFolder',\n 'publicFolder',\n 'legacyStaticFolder',\n ] as (typeof type)[]\n ).includes(type)\n\n if (isStaticAsset && itemsRoot) {\n let found = fsPath && (await fileExists(fsPath, FileType.File))\n\n if (!found) {\n try {\n // In dev, we ensure encoded paths match\n // decoded paths on the filesystem so check\n // that variation as well\n const tempItemPath = decodeURIComponent(curItemPath)\n fsPath = path.posix.join(itemsRoot, tempItemPath)\n found = await fileExists(fsPath, FileType.File)\n } catch {}\n\n if (!found) {\n continue\n }\n }\n } else if (type === 'pageFile' || type === 'appFile') {\n const isAppFile = type === 'appFile'\n\n // Attempt to ensure the page/app file is compiled and ready\n if (ensureFn) {\n const ensureItemPath = isAppFile\n ? normalizeMetadataRoute(curItemPath)\n : curItemPath\n\n try {\n await ensureFn({ type, itemPath: ensureItemPath })\n } catch (error) {\n // If ensure failed, skip this item and continue to the next one\n continue\n }\n }\n } else {\n continue\n }\n }\n\n // i18n locales aren't matched for app dir\n if (type === 'appFile' && locale && locale !== i18n?.defaultLocale) {\n continue\n }\n\n const itemResult = {\n type,\n fsPath,\n locale,\n itemsRoot,\n // itemPath is usually a slice of the request URL too; keep a\n // flat copy so the cached value doesn't retain the full URL.\n itemPath: flatKeyCopy(curItemPath),\n }\n\n getItemsLru?.set(flatKeyCopy(itemKey), itemResult)\n return itemResult\n }\n }\n\n getItemsLru?.set(flatKeyCopy(itemKey), notFound)\n return null\n },\n getDynamicRoutes() {\n // this should include data routes\n return this.dynamicRoutes\n },\n getMiddlewareMatchers() {\n return this.middlewareMatcher\n },\n }\n}\n"],"names":["path","fs","Log","setupDebug","LRUCache","loadCustomRoutes","modifyRouteRegex","FileType","fileExists","recursiveReadDir","isDynamicRoute","escapeStringRegexp","getPathMatch","getNamedRouteRegex","getRouteRegex","getRouteMatcher","pathHasPrefix","normalizeLocalePath","removePathPrefix","getMiddlewareRouteMatcher","APP_PATH_ROUTES_MANIFEST","BUILD_ID_FILE","FUNCTIONS_CONFIG_MANIFEST","MIDDLEWARE_MANIFEST","PAGES_MANIFEST","PRERENDER_MANIFEST","ROUTES_MANIFEST","normalizePathSep","normalizeMetadataRoute","RSCPathnameNormalizer","encodeURIPath","isMetadataRouteFile","debug","buildCustomRoute","type","item","basePath","caseSensitive","restrictedRedirectPaths","map","p","builtRegex","match","source","strict","removeUnnamedParams","regexModifier","regex","internal","undefined","sensitive","check","FS_LRU_ENTRY_OVERHEAD","FS_LRU_MAX_SIZE","flatKeyCopy","key","JSON","parse","stringify","notFound","Symbol","setupFsCheck","opts","getItemsLru","dev","length","value","size","fsPath","itemPath","nextDataRoutes","Set","publicFolderItems","nextStaticFolderItems","legacyStaticFolderItems","appFiles","pageFiles","staticMetadataFiles","Map","dynamicRoutes","middlewareMatcher","distDir","join","dir","config","publicFolderPath","nextStaticFolderPath","legacyStaticFolderPath","customRoutes","redirects","rewrites","beforeFiles","afterFiles","fallback","onMatchHeaders","headers","buildId","previewProps","middlewareManifest","buildIdPath","readFile","err","code","Error","file","add","warn","posix","output","routesManifestPath","prerenderManifestPath","middlewareManifestPath","functionsConfigManifestPath","pagesManifestPath","appRoutesManifestPath","routesManifest","preview","catch","functionsConfigManifest","pagesManifest","appRoutesManifest","Object","keys","i18n","locales","pathname","escapedBuildId","route","dataRoutes","page","routeRegex","prefixRouteKeys","push","re","toString","namedRegex","routeKeys","RegExp","dataRouteRegex","replace","groups","skipInternalRouting","middleware","matchers","functions","regexp","originalSource","Array","isArray","previewModeId","require","randomBytes","previewModeSigningKey","previewModeEncryptionKey","experimental","caseSensitiveRoutes","handleLocale","locale","i18nResult","detectedLocale","ensureFn","normalizers","rsc","exportPathMapRoutes","devVirtualFsItems","ensureCallback","fn","getItem","originalItemPath","itemKey","lruResult","get","hasBasePath","minimalMode","normalize","endsWith","substring","decodedItemPath","decodeURIComponent","itemsToCheck","items","curItemPath","curDecodedItemPath","isDynamicOutput","localeResult","defaultLocale","domains","nextDataPrefix","startsWith","curLocaleResult","matchedItem","has","encodedCurItemPath","itemsRoot","isStaticAsset","includes","found","File","tempItemPath","isAppFile","ensureItemPath","error","itemResult","set","getDynamicRoutes","getMiddlewareMatchers"],"mappings":"A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3C,yBAAyB;oCACzB,MAAME,eAAepB,mBAAmBG;oCACxCjH,SAASpE,KAAK2G,KAAK,CAACzB,IAAI,CAAC+G,WAAWK;oCACpCF,QAAQ,MAAM5L,WAAW4D,QAAQ7D,SAAS8L,IAAI;gCAChD,EAAE,OAAM,CAAC;gCAET,IAAI,CAACD,OAAO;oCACV;gCACF;4BACF;wBACF,OAAO,IAAIlK,SAAS,cAAcA,SAAS,WAAW;4BACpD,MAAMqK,YAAYrK,SAAS;4BAE3B,4DAA4D;4BAC5D,IAAI8H,UAAU;gCACZ,MAAMwC,iBAAiBD,YACnB3K,uBAAuByJ,eACvBA;gCAEJ,IAAI;oCACF,MAAMrB,SAAS;wCAAE9H;wCAAMmC,UAAUmI;oCAAe;gCAClD,EAAE,OAAOC,OAAO;oCAEd;gCACF;4BACF;wBACF,OAAO;4BACL;wBACF;oBACF;oBAEA,0CAA0C;oBAC1C,IAAIvK,SAAS,aAAa2H,UAAUA,YAAWlC,wBAAAA,KAAM8D,aAAa,GAAE;wBAClE;oBACF;oBAEA,MAAMiB,aAAa;wBACjBxK;wBACAkC;wBACAyF;wBACAoC;wBACA,6DAA6D;wBAC7D,6DAA6D;wBAC7D5H,UAAUf,YAAY+H;oBACxB;oBAEAtH,+BAAAA,YAAa4I,GAAG,CAACrJ,YAAYmH,UAAUiC;oBACvC,OAAOA;gBACT;YACF;YAEA3I,+BAAAA,YAAa4I,GAAG,CAACrJ,YAAYmH,UAAU9G;YACvC,OAAO;QACT;QACAiJ;YACE,kCAAkC;YAClC,OAAO,IAAI,CAAC7H,aAAa;QAC3B;QACA8H;YACE,OAAO,IAAI,CAAC7H,iBAAiB;QAC/B;IACF;AACF","ignoreList":[0]} |
@@ -9,9 +9,9 @@ import url from 'url'; | ||
| parsedUrl.search = stringifyQuery(req, query); | ||
| const target = url.format(parsedUrl); | ||
| // Keep in mind that a WHATWG URL's hostname and the parsedUrl's hostname | ||
| // are not strictly equal due to lowercasing, IDN translation, IPv4 and IPv6 normalization, etc. | ||
| // We just make sure this is a valid URL since http-proxy doesn't validate. | ||
| new URL(target); | ||
| const HttpProxy = require('next/dist/compiled/http-proxy'); | ||
| const proxy = new HttpProxy({ | ||
| // We just make sure this is a valid URL since httpxy would only parse it | ||
| // lazily on the `web()`/`ws()` call. | ||
| const target = new URL(url.format(parsedUrl)); | ||
| const { ProxyServer } = require('next/dist/compiled/httpxy'); | ||
| const proxy = new ProxyServer({ | ||
| target, | ||
@@ -29,3 +29,3 @@ changeOrigin: true, | ||
| let finished = false; | ||
| // http-proxy does not properly detect a client disconnect in newer | ||
| // httpxy does not properly detect a client disconnect in newer | ||
| // versions of Node.js. This is caused because it only listens for the | ||
@@ -64,6 +64,6 @@ // `aborted` event on the our request object, but it also fully reads | ||
| const detached = new DetachedPromise(); | ||
| proxy.on('error', (err)=>{ | ||
| console.error(`Failed to proxy ${target}`, err); | ||
| const onProxyError = (err)=>{ | ||
| if (!finished) { | ||
| finished = true; | ||
| console.error(`Failed to proxy ${target}`, err); | ||
| detached.reject(err); | ||
@@ -77,3 +77,4 @@ if (!res.destroyed) { | ||
| } | ||
| }); | ||
| }; | ||
| proxy.on('error', onProxyError); | ||
| // If upgrade head is present or the response is a Duplex stream, treat as | ||
@@ -90,3 +91,5 @@ // WebSocket request. | ||
| }); | ||
| proxy.ws(req, res, upgradeHead); | ||
| // The returned promise rejects on errors of the client socket (e.g. an | ||
| // abrupt client disconnect) even when an `error` listener is registered. | ||
| proxy.ws(req, res, {}, upgradeHead).catch(onProxyError); | ||
| detached.resolve(true); | ||
@@ -102,5 +105,8 @@ } else { | ||
| }); | ||
| // The returned promise rejects on errors of the client response stream | ||
| // (e.g. an abrupt client disconnect) even when an `error` listener is | ||
| // registered. | ||
| proxy.web(req, res, { | ||
| buffer: reqBody | ||
| }); | ||
| }).catch(onProxyError); | ||
| } | ||
@@ -107,0 +113,0 @@ // When the proxy finishes proxying the request, shut down the proxy. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/router-utils/proxy-request.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextUrlWithParsedQuery } from '../../request-meta'\n\nimport url from 'url'\nimport { stringifyQuery } from '../../server-route-utils'\nimport { Duplex } from 'stream'\nimport { DetachedPromise } from '../../../lib/detached-promise'\n\nexport async function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse | Duplex,\n parsedUrl: NextUrlWithParsedQuery,\n upgradeHead?: Buffer,\n reqBody?: any,\n proxyTimeout?: number | null\n) {\n const { query } = parsedUrl\n delete (parsedUrl as any).query\n parsedUrl.search = stringifyQuery(req as any, query)\n\n const target = url.format(parsedUrl)\n // Keep in mind that a WHATWG URL's hostname and the parsedUrl's hostname\n // are not strictly equal due to lowercasing, IDN translation, IPv4 and IPv6 normalization, etc.\n // We just make sure this is a valid URL since http-proxy doesn't validate.\n new URL(target)\n const HttpProxy =\n require('next/dist/compiled/http-proxy') as typeof import('next/dist/compiled/http-proxy')\n\n const proxy = new HttpProxy({\n target,\n changeOrigin: true,\n ignorePath: true,\n ws: true,\n // we limit proxy requests to 30s by default, in development\n // we don't time out WebSocket requests to allow proxying\n proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000,\n headers: {\n 'x-forwarded-host': req.headers.host || '',\n },\n })\n\n let finished = false\n\n // http-proxy does not properly detect a client disconnect in newer\n // versions of Node.js. This is caused because it only listens for the\n // `aborted` event on the our request object, but it also fully reads\n // and closes the request object. Node **will not** fire `aborted` when\n // the request is already closed. Listening for `close` on our response\n // object will detect the disconnect, and we can abort the proxy's\n // connection.\n proxy.on('proxyReq', (proxyReq) => {\n res.on('close', () => proxyReq.destroy())\n })\n\n proxy.on('proxyRes', (proxyRes) => {\n if (res.destroyed) {\n proxyRes.destroy()\n } else {\n res.on('close', () => proxyRes.destroy())\n }\n })\n\n proxy.on('proxyRes', (proxyRes, innerReq, innerRes) => {\n const cleanup = (err: any) => {\n // cleanup event listeners to allow clean garbage collection\n proxyRes.removeListener('error', cleanup)\n proxyRes.removeListener('close', cleanup)\n innerRes.removeListener('error', cleanup)\n innerRes.removeListener('close', cleanup)\n\n // destroy all source streams to propagate the caught event backward\n innerReq.destroy(err)\n proxyRes.destroy(err)\n }\n\n proxyRes.once('error', cleanup)\n proxyRes.once('close', cleanup)\n innerRes.once('error', cleanup)\n innerRes.once('close', cleanup)\n })\n\n const detached = new DetachedPromise<boolean>()\n\n proxy.on('error', (err) => {\n console.error(`Failed to proxy ${target}`, err)\n if (!finished) {\n finished = true\n detached.reject(err)\n\n if (!res.destroyed) {\n if (!(res instanceof Duplex)) {\n res.statusCode = 500\n }\n\n res.end('Internal Server Error')\n }\n }\n })\n\n // If upgrade head is present or the response is a Duplex stream, treat as\n // WebSocket request.\n if (upgradeHead || res instanceof Duplex) {\n proxy.on('proxyReqWs', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n proxy.ws(req, res, upgradeHead)\n detached.resolve(true)\n } else {\n proxy.on('proxyReq', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n proxy.web(req, res, {\n buffer: reqBody,\n })\n }\n\n // When the proxy finishes proxying the request, shut down the proxy.\n return detached.promise.finally(() => {\n proxy.close()\n })\n}\n"],"names":["url","stringifyQuery","Duplex","DetachedPromise","proxyRequest","req","res","parsedUrl","upgradeHead","reqBody","proxyTimeout","query","search","target","format","URL","HttpProxy","require","proxy","changeOrigin","ignorePath","ws","undefined","headers","host","finished","on","proxyReq","destroy","proxyRes","destroyed","innerReq","innerRes","cleanup","err","removeListener","once","detached","console","error","reject","statusCode","end","resolve","web","buffer","promise","finally","close"],"mappings":"AAGA,OAAOA,SAAS,MAAK;AACrB,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SAASC,MAAM,QAAQ,SAAQ;AAC/B,SAASC,eAAe,QAAQ,gCAA+B;AAE/D,OAAO,eAAeC,aACpBC,GAAoB,EAC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SAASO,IAAI,CAAC,SAASH;QACvBJ,SAASO,IAAI,CAAC,SAASH;QACvBD,SAASI,IAAI,CAAC,SAASH;QACvBD,SAASI,IAAI,CAAC,SAASH;IACzB;IAEA,MAAMI,WAAW,IAAIlC;IAErBe,MAAMQ,EAAE,CAAC,SAAS,CAACQ;QACjBI,QAAQC,KAAK,CAAC,CAAC,gBAAgB,EAAE1B,QAAQ,EAAEqB;QAC3C,IAAI,CAACT,UAAU;YACbA,WAAW;YACXY,SAASG,MAAM,CAACN;YAEhB,IAAI,CAAC5B,IAAIwB,SAAS,EAAE;gBAClB,IAAI,CAAExB,CAAAA,eAAeJ,MAAK,GAAI;oBAC5BI,IAAImC,UAAU,GAAG;gBACnB;gBAEAnC,IAAIoC,GAAG,CAAC;YACV;QACF;IACF;IAEA,0EAA0E;IAC1E,qBAAqB;IACrB,IAAIlC,eAAeF,eAAeJ,QAAQ;QACxCgB,MAAMQ,EAAE,CAAC,cAAc,CAACC;YACtBA,SAASD,EAAE,CAAC,SAAS;gBACnB,IAAI,CAACD,UAAU;oBACbA,WAAW;oBACXY,SAASM,OAAO,CAAC;gBACnB;YACF;QACF;QACAzB,MAAMG,EAAE,CAAChB,KAAKC,KAAKE;QACnB6B,SAASM,OAAO,CAAC;IACnB,OAAO;QACLzB,MAAMQ,EAAE,CAAC,YAAY,CAACC;YACpBA,SAASD,EAAE,CAAC,SAAS;gBACnB,IAAI,CAACD,UAAU;oBACbA,WAAW;oBACXY,SAASM,OAAO,CAAC;gBACnB;YACF;QACF;QACAzB,MAAM0B,GAAG,CAACvC,KAAKC,KAAK;YAClBuC,QAAQpC;QACV;IACF;IAEA,qEAAqE;IACrE,OAAO4B,SAASS,OAAO,CAACC,OAAO,CAAC;QAC9B7B,MAAM8B,KAAK;IACb;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/router-utils/proxy-request.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type { Socket } from 'net'\nimport type { NextUrlWithParsedQuery } from '../../request-meta'\n\nimport url from 'url'\nimport { stringifyQuery } from '../../server-route-utils'\nimport { Duplex } from 'stream'\nimport { DetachedPromise } from '../../../lib/detached-promise'\n\nexport async function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse | Duplex,\n parsedUrl: NextUrlWithParsedQuery,\n upgradeHead?: Buffer,\n reqBody?: any,\n proxyTimeout?: number | null\n) {\n const { query } = parsedUrl\n delete (parsedUrl as any).query\n parsedUrl.search = stringifyQuery(req as any, query)\n\n // Keep in mind that a WHATWG URL's hostname and the parsedUrl's hostname\n // are not strictly equal due to lowercasing, IDN translation, IPv4 and IPv6 normalization, etc.\n // We just make sure this is a valid URL since httpxy would only parse it\n // lazily on the `web()`/`ws()` call.\n const target = new URL(url.format(parsedUrl))\n const { ProxyServer } =\n require('next/dist/compiled/httpxy') as typeof import('next/dist/compiled/httpxy')\n\n const proxy = new ProxyServer({\n target,\n changeOrigin: true,\n ignorePath: true,\n ws: true,\n // we limit proxy requests to 30s by default, in development\n // we don't time out WebSocket requests to allow proxying\n proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000,\n headers: {\n 'x-forwarded-host': req.headers.host || '',\n },\n })\n\n let finished = false\n\n // httpxy does not properly detect a client disconnect in newer\n // versions of Node.js. This is caused because it only listens for the\n // `aborted` event on the our request object, but it also fully reads\n // and closes the request object. Node **will not** fire `aborted` when\n // the request is already closed. Listening for `close` on our response\n // object will detect the disconnect, and we can abort the proxy's\n // connection.\n proxy.on('proxyReq', (proxyReq) => {\n res.on('close', () => proxyReq.destroy())\n })\n\n proxy.on('proxyRes', (proxyRes) => {\n if (res.destroyed) {\n proxyRes.destroy()\n } else {\n res.on('close', () => proxyRes.destroy())\n }\n })\n\n proxy.on('proxyRes', (proxyRes, innerReq, innerRes) => {\n const cleanup = (err: any) => {\n // cleanup event listeners to allow clean garbage collection\n proxyRes.removeListener('error', cleanup)\n proxyRes.removeListener('close', cleanup)\n innerRes.removeListener('error', cleanup)\n innerRes.removeListener('close', cleanup)\n\n // destroy all source streams to propagate the caught event backward\n innerReq.destroy(err)\n proxyRes.destroy(err)\n }\n\n proxyRes.once('error', cleanup)\n proxyRes.once('close', cleanup)\n innerRes.once('error', cleanup)\n innerRes.once('close', cleanup)\n })\n\n const detached = new DetachedPromise<boolean>()\n\n const onProxyError = (err: Error) => {\n if (!finished) {\n finished = true\n console.error(`Failed to proxy ${target}`, err)\n detached.reject(err)\n\n if (!res.destroyed) {\n if (!(res instanceof Duplex)) {\n res.statusCode = 500\n }\n\n res.end('Internal Server Error')\n }\n }\n }\n\n proxy.on('error', onProxyError)\n\n // If upgrade head is present or the response is a Duplex stream, treat as\n // WebSocket request.\n if (upgradeHead || res instanceof Duplex) {\n proxy.on('proxyReqWs', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n // The returned promise rejects on errors of the client socket (e.g. an\n // abrupt client disconnect) even when an `error` listener is registered.\n proxy.ws(req, res as Socket, {}, upgradeHead).catch(onProxyError)\n detached.resolve(true)\n } else {\n proxy.on('proxyReq', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n // The returned promise rejects on errors of the client response stream\n // (e.g. an abrupt client disconnect) even when an `error` listener is\n // registered.\n proxy\n .web(req, res, {\n buffer: reqBody,\n })\n .catch(onProxyError)\n }\n\n // When the proxy finishes proxying the request, shut down the proxy.\n return detached.promise.finally(() => {\n proxy.close()\n })\n}\n"],"names":["url","stringifyQuery","Duplex","DetachedPromise","proxyRequest","req","res","parsedUrl","upgradeHead","reqBody","proxyTimeout","query","search","target","URL","format","ProxyServer","require","proxy","changeOrigin","ignorePath","ws","undefined","headers","host","finished","on","proxyReq","destroy","proxyRes","destroyed","innerReq","innerRes","cleanup","err","removeListener","once","detached","onProxyError","console","error","reject","statusCode","end","resolve","catch","web","buffer","promise","finally","close"],"mappings":"AAIA,OAAOA,SAAS,MAAK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1B,MACG4B,GAAG,CAACzC,KAAKC,KAAK;YACbyC,QAAQtC;QACV,GACCoC,KAAK,CAACP;IACX;IAEA,qEAAqE;IACrE,OAAOD,SAASW,OAAO,CAACC,OAAO,CAAC;QAC9B/B,MAAMgC,KAAK;IACb;AACF","ignoreList":[0]} |
@@ -119,4 +119,3 @@ import { LRUCache } from './lru-cache'; | ||
| const invalidSourceMap = Symbol('invalid-source-map'); | ||
| const sourceMapURLs = new LRUCache(512 * 1024 * 1024, (url)=>url === invalidSourceMap ? // so that we don't create a huge cache with empty source maps. | ||
| 8 * 1024 : url.length); | ||
| const sourceMapURLs = new LRUCache(512 * 1024 * 1024, (url, sourceURL)=>sourceURL.length + (url === invalidSourceMap ? 8 * 1024 : url.length)); | ||
| export function findSourceMapURLDEV(scriptNameOrSourceURL) { | ||
@@ -123,0 +122,0 @@ try { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n return undefined\n }\n let payload = sourceMapPayloads.get(sourceMap)\n if (payload === undefined) {\n payload = sourceMap.payload as ModernSourceMapPayload\n sourceMapPayloads.set(sourceMap, payload)\n }\n return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const payload = findSourceMapPayload(sourceURL)\n if (payload === undefined) {\n // No source map associated.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["LRUCache","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","findSourceMapPayload","sourceURL","sourceMap","payload","get","set","sourceMapIgnoreListsEverything","ignoreList","sources","length","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","filterStackFrameDEV","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","setBundlerFindSourceMapURLImplementation","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","url","findSourceMapURLDEV","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","devirtualizeReactServerURL","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","ignoreListAnonymousStackFramesIfSandwiched","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":"AACA,SAASA,QAAQ,QAAQ,cAAa;AAEtC,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;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AII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n return undefined\n }\n let payload = sourceMapPayloads.get(sourceMap)\n if (payload === undefined) {\n payload = sourceMap.payload as ModernSourceMapPayload\n sourceMapPayloads.set(sourceMap, payload)\n }\n return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const payload = findSourceMapPayload(sourceURL)\n if (payload === undefined) {\n // No source map associated.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url, sourceURL) =>\n sourceURL.length +\n (url === invalidSourceMap\n ? // Guestimate a small source map so invalid entries don't fill the cache.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length)\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["LRUCache","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","findSourceMapPayload","sourceURL","sourceMap","payload","get","set","sourceMapIgnoreListsEverything","ignoreList","sources","length","findApplicableSourceMapPayload","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","filterStackFrameDEV","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","setBundlerFindSourceMapURLImplementation","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","url","findSourceMapURLDEV","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","devirtualizeReactServerURL","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","ignoreListAnonymousStackFramesIfSandwiched","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":"AACA,SAASA,QAAQ,QAAQ,cAAa;AAEtC,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,0EAA0E;AAC1E,0EAA0E;AAC1E,qCAAqC;AACrC,MAAMK,oBAAoB,IAAIC;AAE9B;;;;CAIC,GACD,OAAO,SAASC,qBACdC,SAAiB;IAEjB,MAAMC,YAAYT,cAAcQ;IAChC,IAAIC,cAAcV,WAAW;QAC3B,OAAOA;IACT;IACA,IAAIW,UAAUL,kBAAkBM,GAAG,CAACF;IACpC,IAAIC,YAAYX,WAAW;QACzBW,UAAUD,UAAUC,OAAO;QAC3BL,kBAAkBO,GAAG,CAACH,WAAWC;IACnC;IACA,OAAOA;AACT;AAEA,OAAO,SAASG,+BACdJ,SAAgC;IAEhC,OACEA,UAAUK,UAAU,KAAKf,aACzBU,UAAUM,OAAO,CAACC,MAAM,KAAKP,UA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E1B;AAEA,OAAO,SAASwC,2CACdC,MAAe,EACfC,gBAA2C,EAC3CC,cAAyC,EACzCC,aAAuC,EACvC,2HAA2H,GAC3HC,WAAmC;IAEnC,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAO7D,MAAM,EAAEkE,IAAK;QACtC,MAAMC,eAAeN,MAAM,CAACK,EAAE;QAC9B,IACE,CACEJ,CAAAA,iBAAiBK,iBACjBT,+BAA+BM,cAAcG,cAAa,GAE5D;YACA;QACF;QAEA,MAAMC,yBAAyBL,eAAeF,MAAM,CAACK,IAAI,EAAE;QAC3D,IAAIE,0BAA0BF,IAAIL,OAAO7D,MAAM,GAAG,GAAG;YACnD,IAAIqE,iBAAiB;YACrB,IAAIC,IAAIJ,IAAI;YACZ,IAAKI,GAAGA,IAAIT,OAAO7D,MAAM,EAAEsE,IAAK;gBAC9B,MAAMC,YAAYV,MAAM,CAACS,EAAE;gBAC3B,MAAME,uBACJV,iBAAiBS,cACjBb,+BAA+BM,cAAcO;gBAC/C,IAAIC,sBAAsB;oBACxB;gBACF;gBAEA,MAAMC,qBAAqBV,eAAeQ;gBAC1C,IAAIE,oBAAoB;oBACtBJ,iBAAiB;oBACjB;gBACF;YACF;YAEA,IAAIA,gBAAgB;gBAClB,IAAKH,GAAGA,IAAII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} |
@@ -112,3 +112,3 @@ // Start CPU profile if it wasn't already started. | ||
| let { port } = serverOptions; | ||
| process.title = `next-server (v${"16.3.0-canary.97"})`; | ||
| process.title = `next-server (v${"16.3.0-canary.99"})`; | ||
| let handlersReady = ()=>{}; | ||
@@ -115,0 +115,0 @@ let handlersError = ()=>{}; |
@@ -88,2 +88,3 @@ /** | ||
| AppRenderSpan["renderToNodeFizzStream"] = "AppRender.renderToNodeFizzStream"; | ||
| AppRenderSpan["instantInsights"] = "AppRender.instantInsights"; | ||
| return AppRenderSpan; | ||
@@ -90,0 +91,0 @@ }(AppRenderSpan || {}); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["BaseServerSpan","LoadComponentsSpan","NextServerSpan","NextNodeServerSpan","StartServerSpan","RenderSpan","AppRenderSpan","RouterSpan","NodeSpan","AppRouteRouteHandlersSpan","ResolveMetadataSpan","MiddlewareSpan","NextVanillaSpanAllowlist","Set","LogSpanAllowList"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;AAE5C,IAAA,AAAKA,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKC,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,uCAAAA;;;;;;;WAAAA;EAAAA;AASL,IAAA,AAAKC,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;WAAAA;EAAAA;AAkBL,0EAA0E;AAC1E,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;;;;;;;;;;;;;;;;;CAiB/C,EAAC;AAEF,8CAA8C;AAC9C,sCAAsC;AACtC,OAAO,MAAMC,mBAAmB,IAAID,IAAI;;;;CAIvC,EAAC;AAEF,SACEb,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,UAAU,EACVE,UAAU,EACVD,aAAa,EACbE,QAAQ,EACRC,yBAAyB,EACzBC,mBAAmB,EACnBC,cAAc,KACf","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["BaseServerSpan","LoadComponentsSpan","NextServerSpan","NextNodeServerSpan","StartServerSpan","RenderSpan","AppRenderSpan","RouterSpan","NodeSpan","AppRouteRouteHandlersSpan","ResolveMetadataSpan","MiddlewareSpan","NextVanillaSpanAllowlist","Set","LogSpanAllowList"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;AAE5C,IAAA,AAAKA,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKC,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKC,uCAAAA;;;;;;;;WAAAA;EAAAA;AAUL,IAAA,AAAKC,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKC,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKC,wCAAAA;;WAAAA;EAAAA;AAkBL,0EAA0E;AAC1E,OAAO,MAAMC,2BAA2B,IAAIC,IAAI;;;;;;;;;;;;;;;;;CAiB/C,EAAC;AAEF,8CAA8C;AAC9C,sCAAsC;AACtC,OAAO,MAAMC,mBAAmB,IAAID,IAAI;;;;CAIvC,EAAC;AAEF,SACEb,cAAc,EACdC,kBAAkB,EAClBC,cAAc,EACdC,kBAAkB,EAClBC,eAAe,EACfC,UAAU,EACVE,UAAU,EACVD,aAAa,EACbE,QAAQ,EACRC,yBAAyB,EACzBC,mBAAmB,EACnBC,cAAc,KACf","ignoreList":[0]} |
@@ -104,5 +104,6 @@ import { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'; | ||
| } | ||
| const eventTime = startTime === undefined && isTimestampInput(attributesOrStartTime) ? attributesOrStartTime : startTime; | ||
| this.events.push({ | ||
| name, | ||
| timestamp: Date.now(), | ||
| timestamp: getTimestamp(eventTime), | ||
| attributes: isSpanStoreAttributes(attributesOrStartTime) ? cleanSpanStoreAttributes(attributesOrStartTime) : undefined | ||
@@ -159,3 +160,3 @@ }); | ||
| name: 'exception', | ||
| timestamp: Date.now(), | ||
| timestamp: getTimestamp(time), | ||
| attributes: getSpanStoreExceptionAttributes(this.exception) | ||
@@ -176,2 +177,3 @@ }); | ||
| requestId: this.requestIdentity.requestId, | ||
| requestInsightKind: this.requestIdentity.requestInsightKind, | ||
| htmlRequestId: this.requestIdentity.htmlRequestId, | ||
@@ -239,11 +241,6 @@ route: getStringAttribute(recordAttributes, 'next.route') ?? getStringAttribute(recordAttributes, 'http.route') ?? this.requestIdentity.route, | ||
| if (typeof time === 'number') { | ||
| const timeOrigin = getPerformanceTimeOrigin(); | ||
| return timeOrigin !== undefined && time < timeOrigin ? timeOrigin + time : time; | ||
| return time < performance.timeOrigin / 2 ? performance.timeOrigin + time : time; | ||
| } | ||
| const timeOrigin = getPerformanceTimeOrigin(); | ||
| return timeOrigin === undefined ? Date.now() : timeOrigin + performance.now(); | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
| function getPerformanceTimeOrigin() { | ||
| return typeof performance !== 'undefined' && typeof performance.timeOrigin === 'number' ? performance.timeOrigin : undefined; | ||
| } | ||
| function getStringAttribute(attributes, key) { | ||
@@ -256,2 +253,5 @@ const value = attributes == null ? void 0 : attributes[key]; | ||
| } | ||
| function isTimestampInput(value) { | ||
| return typeof value === 'number' || Array.isArray(value) || value instanceof Date; | ||
| } | ||
| function getSpanStoreException(exception) { | ||
@@ -301,4 +301,5 @@ if (exception instanceof Error) { | ||
| return { | ||
| requestId: (workStore == null ? void 0 : workStore.requestId) ?? (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId), | ||
| htmlRequestId: (workStore == null ? void 0 : workStore.htmlRequestId) ?? (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId), | ||
| requestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId) ?? (workStore == null ? void 0 : workStore.requestId), | ||
| requestInsightKind: requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.kind, | ||
| htmlRequestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId) ?? (workStore == null ? void 0 : workStore.htmlRequestId), | ||
| route: workStore == null ? void 0 : workStore.route, | ||
@@ -305,0 +306,0 @@ url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.url |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/local-span-recorder.ts"],"sourcesContent":["import type {\n AttributeValue,\n Span,\n SpanOptions,\n} from 'next/dist/compiled/@opentelemetry/api'\nimport type { AsyncLocalStorage } from 'async_hooks'\nimport { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'\nimport {\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n recordSpan,\n type SpanStoreAttributes,\n type SpanStoreEvent,\n type SpanStoreLink,\n} from './span-store'\n\nexport { isLocalSpanRecordingEnabled } from './span-store'\n\nconst TRACE_ID_HEX_LENGTH = 32\nconst SPAN_ID_HEX_LENGTH = 16\n\ntype LocalSpanAttributes = Partial<Record<string, AttributeValue | undefined>>\n\nlet lastLocalTraceId = 0\nlet lastLocalSpanId = 0\nlet localSpanAsyncStorage: AsyncLocalStorage<Span> | undefined\n\nconst getLocalTraceId = () =>\n (++lastLocalTraceId).toString(16).padStart(TRACE_ID_HEX_LENGTH, '0')\n\nconst getLocalSpanId = () =>\n (++lastLocalSpanId).toString(16).padStart(SPAN_ID_HEX_LENGTH, '0')\n\nexport function createLocalSpan({\n name,\n attributes,\n links,\n startTime,\n traceId,\n spanId,\n parentSpanId,\n delegateSpan,\n}: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n traceId?: string\n spanId?: string\n parentSpanId?: string\n delegateSpan?: Span\n}): Span {\n return new LocalRecordingSpan({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId: traceId ?? getLocalTraceId(),\n spanId: spanId ?? getLocalSpanId(),\n parentSpanId,\n requestIdentity: getCurrentRequestIdentity(),\n })\n}\n\nexport function getActiveLocalSpan(): Span | undefined {\n return localSpanAsyncStorage?.getStore()\n}\n\nexport function isLocalRecordingSpan(span: Span): boolean {\n return span instanceof LocalRecordingSpan\n}\n\nexport function withLocalSpan<T>(span: Span, fn: () => T): T {\n return getLocalSpanAsyncStorage().run(span, fn)\n}\n\nexport type LocalSpanRecorder = {\n createLocalSpan: typeof createLocalSpan\n getActiveLocalSpan: typeof getActiveLocalSpan\n isLocalRecordingSpan: typeof isLocalRecordingSpan\n isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled\n isRequestInsightsEnabled: typeof isRequestInsightsEnabled\n withLocalSpan: typeof withLocalSpan\n}\n\nexport function registerLocalSpanRecorder(): void {\n const key = Symbol.for('@next/local-span-recorder')\n ;(\n globalThis as typeof globalThis & {\n [key]?: LocalSpanRecorder\n }\n )[key] = {\n createLocalSpan,\n getActiveLocalSpan,\n isLocalRecordingSpan,\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n withLocalSpan,\n }\n}\n\nfunction getLocalSpanAsyncStorage(): AsyncLocalStorage<Span> {\n if (!localSpanAsyncStorage) {\n const { createAsyncLocalStorage } =\n require('../../app-render/async-local-storage') as typeof import('../../app-render/async-local-storage')\n localSpanAsyncStorage = createAsyncLocalStorage()\n }\n\n return localSpanAsyncStorage\n}\n\ntype RequestIdentity = {\n requestId?: string\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nclass LocalRecordingSpan implements Span {\n public name: string\n\n private attributes: SpanStoreAttributes\n private events: SpanStoreEvent[]\n private readonly spanContextValue: ReturnType<Span['spanContext']>\n private delegateSpan?: Span\n private links?: SpanStoreLink[]\n private readonly parentSpanId?: string\n private requestIdentity: RequestIdentity\n private readonly startTime: number\n private statusCode: number | undefined\n private statusMessage: string | undefined\n private exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n private ended: boolean\n\n constructor({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId,\n spanId,\n parentSpanId,\n requestIdentity,\n }: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n delegateSpan?: Span\n traceId: string\n spanId: string\n parentSpanId?: string\n requestIdentity: RequestIdentity\n }) {\n this.name = name\n this.attributes = cleanSpanStoreAttributes(attributes)\n this.events = []\n this.delegateSpan = delegateSpan\n this.spanContextValue = delegateSpan?.spanContext() ?? {\n traceId,\n spanId,\n traceFlags: 0,\n }\n this.links = getSpanStoreLinks(links)\n this.parentSpanId = parentSpanId\n this.requestIdentity = requestIdentity\n this.startTime = getTimestamp(startTime)\n this.statusCode = undefined\n this.statusMessage = undefined\n this.exception = undefined\n this.ended = false\n }\n\n spanContext(): ReturnType<Span['spanContext']> {\n return this.spanContextValue\n }\n\n setAttribute(key: string, value: AttributeValue): this {\n if (this.ended) {\n return this\n }\n\n this.attributes[key] = value\n this.delegateSpan?.setAttribute(key, value)\n return this\n }\n\n setAttributes(attributes: Parameters<Span['setAttributes']>[0]): this {\n if (this.ended) {\n return this\n }\n\n // OpenTelemetry attributes may be undefined. Ignore them instead of\n // overwriting an existing value as Object.assign would.\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n this.attributes[key] = value\n }\n }\n this.delegateSpan?.setAttributes(attributes)\n return this\n }\n\n addEvent(\n name: string,\n attributesOrStartTime?: Parameters<Span['addEvent']>[1],\n startTime?: Parameters<Span['addEvent']>[2]\n ): this {\n if (this.ended) {\n return this\n }\n\n this.events.push({\n name,\n timestamp: Date.now(),\n attributes: isSpanStoreAttributes(attributesOrStartTime)\n ? cleanSpanStoreAttributes(attributesOrStartTime)\n : undefined,\n })\n this.delegateSpan?.addEvent(name, attributesOrStartTime, startTime)\n return this\n }\n\n setStatus(status: Parameters<Span['setStatus']>[0]): this {\n if (this.ended) {\n return this\n }\n\n this.statusCode = status.code\n this.statusMessage = status.message\n this.delegateSpan?.setStatus(status)\n return this\n }\n\n updateName(name: string): this {\n if (this.ended) {\n return this\n }\n\n this.name = name\n this.delegateSpan?.updateName(name)\n return this\n }\n\n end(endTime?: Parameters<Span['end']>[0]): void {\n if (this.ended) {\n return\n }\n\n this.ended = true\n try {\n this.delegateSpan?.end(endTime)\n } finally {\n try {\n this.record(endTime)\n } finally {\n this.releaseReferences()\n }\n }\n }\n\n isRecording(): boolean {\n return !this.ended\n }\n\n recordException(\n exception: Parameters<Span['recordException']>[0],\n time?: Parameters<Span['recordException']>[1]\n ): void {\n if (this.ended) {\n return\n }\n\n this.exception = getSpanStoreException(exception)\n this.events.push({\n name: 'exception',\n timestamp: Date.now(),\n attributes: getSpanStoreExceptionAttributes(this.exception),\n })\n this.delegateSpan?.recordException(exception, time)\n }\n\n private record(endTime: Parameters<Span['end']>[0]): void {\n const recordAttributes =\n Object.keys(this.attributes).length > 0 ? this.attributes : undefined\n\n recordSpan({\n name: this.name,\n startTime: this.startTime,\n durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),\n status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',\n traceId: this.spanContextValue.traceId,\n spanId: this.spanContextValue.spanId,\n parentSpanId: this.parentSpanId,\n requestId: this.requestIdentity.requestId,\n htmlRequestId: this.requestIdentity.htmlRequestId,\n route:\n getStringAttribute(recordAttributes, 'next.route') ??\n getStringAttribute(recordAttributes, 'http.route') ??\n this.requestIdentity.route,\n url:\n getStringAttribute(recordAttributes, 'http.url') ??\n this.requestIdentity.url,\n attributes: recordAttributes,\n links: this.links,\n events: this.events.length > 0 ? this.events : undefined,\n error: this.getRecordError(),\n })\n }\n\n private releaseReferences(): void {\n // AsyncLocalStorage can keep an ended span reachable when work spawned\n // inside the span outlives it. Keep only the immutable span context and\n // primitive timing/identity fields needed by the Span API after end.\n this.name = ''\n this.attributes = {}\n this.events = []\n this.delegateSpan = undefined\n this.links = undefined\n this.requestIdentity = {}\n this.statusMessage = undefined\n this.exception = undefined\n }\n\n private getRecordError():\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (this.exception) {\n return this.exception\n }\n\n if (this.statusCode === SpanStatusCode.ERROR && this.statusMessage) {\n return {\n message: this.statusMessage,\n }\n }\n\n return undefined\n }\n}\n\nfunction getSpanStoreLinks(\n links: SpanOptions['links'] | undefined\n): SpanStoreLink[] | undefined {\n const spanStoreLinks = links?.map((link) => ({\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n attributes: cleanSpanStoreAttributes(link.attributes),\n }))\n\n return spanStoreLinks?.length ? spanStoreLinks : undefined\n}\n\nfunction cleanSpanStoreAttributes(\n attributes:\n | Record<string, AttributeValue | undefined>\n | SpanStoreAttributes\n | undefined\n): SpanStoreAttributes {\n const cleanedAttributes: SpanStoreAttributes = {}\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n cleanedAttributes[key] = value\n }\n }\n }\n return cleanedAttributes\n}\n\nfunction getTimestamp(time?: SpanOptions['startTime']): number {\n if (time instanceof Date) {\n return time.getTime()\n }\n\n if (Array.isArray(time)) {\n return time[0] * 1000 + time[1] / 1_000_000\n }\n\n if (typeof time === 'number') {\n const timeOrigin = getPerformanceTimeOrigin()\n return timeOrigin !== undefined && time < timeOrigin\n ? timeOrigin + time\n : time\n }\n\n const timeOrigin = getPerformanceTimeOrigin()\n return timeOrigin === undefined ? Date.now() : timeOrigin + performance.now()\n}\n\nfunction getPerformanceTimeOrigin(): number | undefined {\n return typeof performance !== 'undefined' &&\n typeof performance.timeOrigin === 'number'\n ? performance.timeOrigin\n : undefined\n}\n\nfunction getStringAttribute(\n attributes: SpanStoreAttributes | undefined,\n key: string\n): string | undefined {\n const value = attributes?.[key]\n return typeof value === 'string' ? value : undefined\n}\n\nfunction isSpanStoreAttributes(\n value: Parameters<Span['addEvent']>[1]\n): value is SpanStoreAttributes {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n )\n}\n\nfunction getSpanStoreException(\n exception: Parameters<Span['recordException']>[0]\n):\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (exception instanceof Error) {\n return {\n type: exception.name,\n message: exception.message,\n }\n }\n\n if (typeof exception === 'string') {\n return {\n message: exception,\n }\n }\n\n if (exception && typeof exception === 'object') {\n return {\n type: exception.constructor?.name,\n message: 'message' in exception ? String(exception.message) : undefined,\n }\n }\n\n return undefined\n}\n\nfunction getSpanStoreExceptionAttributes(\n exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n): SpanStoreAttributes | undefined {\n if (!exception) {\n return undefined\n }\n\n const attributes: SpanStoreAttributes = {}\n if (exception.type !== undefined) {\n attributes['exception.type'] = exception.type\n }\n if (exception.message !== undefined) {\n attributes['exception.message'] = exception.message\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined\n}\n\nfunction getCurrentRequestIdentity(): RequestIdentity {\n try {\n const { getRequestInsightsIdentity } =\n require('./request-insights-identity') as typeof import('./request-insights-identity')\n const { workAsyncStorage } =\n require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external')\n const { workUnitAsyncStorage } =\n require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external')\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n const requestInsightsIdentity = getRequestInsightsIdentity()\n const url =\n workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined\n\n return {\n requestId: workStore?.requestId ?? requestInsightsIdentity?.requestId,\n htmlRequestId:\n workStore?.htmlRequestId ?? requestInsightsIdentity?.htmlRequestId,\n route: workStore?.route,\n url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,\n }\n } catch {\n return {}\n }\n}\n"],"names":["SpanStatusCode","isLocalSpanRecordingEnabled","isRequestInsightsEnabled","recordSpan","TRACE_ID_HEX_LENGTH","SPAN_ID_HEX_LENGTH","lastLocalTraceId","lastLocalSpanId","localSpanAsyncStorage","getLocalTraceId","toString","padStart","getLocalSpanId","createLocalSpan","name","attributes","links","startTime","traceId","spanId","parentSpanId","delegateSpan","LocalRecordingSpan","requestIdentity","getCurrentRequestIdentity","getActiveLocalSpan","getStore","isLocalRecordingSpan","span","withLocalSpan","fn","getLocalSpanAsyncStorage","run","registerLocalSpanRecorder","key","Symbol","for","globalThis","createAsyncLocalStorage","require","constructor","cleanSpanStoreAttributes","events","spanContextValue","spanContext","traceFlags","getSpanStoreLinks","getTimestamp","statusCode","undefined","statusMessage","exception","ended","setAttribute","value","setAttributes","Object","keys","addEvent","attributesOrStartTime","push","timestamp","Date","now","isSpanStoreAttributes","setStatus","status","code","message","updateName","end","endTime","record","releaseReferences","isRecording","recordException","time","getSpanStoreException","getSpanStoreExceptionAttributes","recordAttributes","length","durationMs","Math","max","ERROR","requestId","htmlRequestId","route","getStringAttribute","url","error","getRecordError","spanStoreLinks","map","link","context","cleanedAttributes","getTime","Array","isArray","timeOrigin","getPerformanceTimeOrigin","performance","Error","type","String","getRequestInsightsIdentity","workAsyncStorage","workUnitAsyncStorage","workStore","workUnitStore","requestInsightsIdentity","pathname","search"],"mappings":"AAMA,SAASA,cAAc,QAAQ,wCAAuC;AACtE,SACEC,2BAA2B,EAC3BC,wBAAwB,EACxBC,UAAU,QAIL,eAAc;AAErB,SAASF,2BAA2B,QAAQ,eAAc;AAE1D,MAAMG,sBAAsB;AAC5B,MAAMC,qBAAqB;AAI3B,IAAIC,mBAAmB;AACvB,IAAIC,kBAAkB;AACtB,IAAIC;AAEJ,MAAMC,kBAAkB,IACtB,AAAC,CAAA,EAAEH,gBAAe,EAAGI,QAAQ,CAAC,IAAIC,QAAQ,CAACP,qBAAqB;AAElE,MAAMQ,iBAAiB,IACrB,AAAC,CAAA,EAAEL,eAAc,EAAGG,QAAQ,CAAC,IAAIC,QAAQ,CAACN,oBAAoB;AAEhE,OAAO,SAASQ,gBAAgB,EAC9BC,IAAI,EACJC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,YAAY,EACZC,YAAY,EAUb;IACC,OAAO,IAAIC,mBAAmB;QAC5BR;QACAC;QACAC;QACAC;QACAI;QACAH,SAASA,WAAWT;QACpBU,QAAQA,UAAUP;QAClBQ;QACAG,iBAAiBC;IACnB;AACF;AAEA,OAAO,SAASC;IACd,OAAOjB,yCAAAA,sBAAuBkB,QAAQ;AACxC;AAEA,OAAO,SAASC,qBAAqBC,IAAU;IAC7C,OAAOA,gBAAgBN;AACzB;AAEA,OAAO,SAASO,cAAiBD,IAAU,EAAEE,EAAW;IACtD,OAAOC,2BAA2BC,GAAG,CAACJ,MAAME;A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,UAAWxB,SAAS,MAAI0B,2CAAAA,wBAAyB1B,SAAS;YACrEC,eACEuB,CAAAA,6BAAAA,UAAWvB,aAAa,MAAIyB,2CAAAA,wBAAyBzB,aAAa;YACpEC,KAAK,EAAEsB,6BAAAA,UAAWtB,KAAK;YACvBE,KAAKA,MAAM,GAAGA,IAAIuB,QAAQ,GAAGvB,IAAIwB,MAAM,EAAE,GAAGF,2CAAAA,wBAAyBtB,GAAG;QAC1E;IACF,EAAE,OAAM;QACN,OAAO,CAAC;IACV;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/local-span-recorder.ts"],"sourcesContent":["import type {\n AttributeValue,\n Span,\n SpanOptions,\n} from 'next/dist/compiled/@opentelemetry/api'\nimport type { AsyncLocalStorage } from 'async_hooks'\nimport { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'\nimport {\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n recordSpan,\n type SpanStoreAttributes,\n type SpanStoreEvent,\n type SpanStoreLink,\n} from './span-store'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport { isLocalSpanRecordingEnabled } from './span-store'\n\nconst TRACE_ID_HEX_LENGTH = 32\nconst SPAN_ID_HEX_LENGTH = 16\n\ntype LocalSpanAttributes = Partial<Record<string, AttributeValue | undefined>>\n\nlet lastLocalTraceId = 0\nlet lastLocalSpanId = 0\nlet localSpanAsyncStorage: AsyncLocalStorage<Span> | undefined\n\nconst getLocalTraceId = () =>\n (++lastLocalTraceId).toString(16).padStart(TRACE_ID_HEX_LENGTH, '0')\n\nconst getLocalSpanId = () =>\n (++lastLocalSpanId).toString(16).padStart(SPAN_ID_HEX_LENGTH, '0')\n\nexport function createLocalSpan({\n name,\n attributes,\n links,\n startTime,\n traceId,\n spanId,\n parentSpanId,\n delegateSpan,\n}: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n traceId?: string\n spanId?: string\n parentSpanId?: string\n delegateSpan?: Span\n}): Span {\n return new LocalRecordingSpan({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId: traceId ?? getLocalTraceId(),\n spanId: spanId ?? getLocalSpanId(),\n parentSpanId,\n requestIdentity: getCurrentRequestIdentity(),\n })\n}\n\nexport function getActiveLocalSpan(): Span | undefined {\n return localSpanAsyncStorage?.getStore()\n}\n\nexport function isLocalRecordingSpan(span: Span): boolean {\n return span instanceof LocalRecordingSpan\n}\n\nexport function withLocalSpan<T>(span: Span, fn: () => T): T {\n return getLocalSpanAsyncStorage().run(span, fn)\n}\n\nexport type LocalSpanRecorder = {\n createLocalSpan: typeof createLocalSpan\n getActiveLocalSpan: typeof getActiveLocalSpan\n isLocalRecordingSpan: typeof isLocalRecordingSpan\n isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled\n isRequestInsightsEnabled: typeof isRequestInsightsEnabled\n withLocalSpan: typeof withLocalSpan\n}\n\nexport function registerLocalSpanRecorder(): void {\n const key = Symbol.for('@next/local-span-recorder')\n ;(\n globalThis as typeof globalThis & {\n [key]?: LocalSpanRecorder\n }\n )[key] = {\n createLocalSpan,\n getActiveLocalSpan,\n isLocalRecordingSpan,\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n withLocalSpan,\n }\n}\n\nfunction getLocalSpanAsyncStorage(): AsyncLocalStorage<Span> {\n if (!localSpanAsyncStorage) {\n const { createAsyncLocalStorage } =\n require('../../app-render/async-local-storage') as typeof import('../../app-render/async-local-storage')\n localSpanAsyncStorage = createAsyncLocalStorage()\n }\n\n return localSpanAsyncStorage\n}\n\ntype RequestIdentity = {\n requestId?: string\n requestInsightKind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nclass LocalRecordingSpan implements Span {\n public name: string\n\n private attributes: SpanStoreAttributes\n private events: SpanStoreEvent[]\n private readonly spanContextValue: ReturnType<Span['spanContext']>\n private delegateSpan?: Span\n private links?: SpanStoreLink[]\n private readonly parentSpanId?: string\n private requestIdentity: RequestIdentity\n private readonly startTime: number\n private statusCode: number | undefined\n private statusMessage: string | undefined\n private exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n private ended: boolean\n\n constructor({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId,\n spanId,\n parentSpanId,\n requestIdentity,\n }: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n delegateSpan?: Span\n traceId: string\n spanId: string\n parentSpanId?: string\n requestIdentity: RequestIdentity\n }) {\n this.name = name\n this.attributes = cleanSpanStoreAttributes(attributes)\n this.events = []\n this.delegateSpan = delegateSpan\n this.spanContextValue = delegateSpan?.spanContext() ?? {\n traceId,\n spanId,\n traceFlags: 0,\n }\n this.links = getSpanStoreLinks(links)\n this.parentSpanId = parentSpanId\n this.requestIdentity = requestIdentity\n this.startTime = getTimestamp(startTime)\n this.statusCode = undefined\n this.statusMessage = undefined\n this.exception = undefined\n this.ended = false\n }\n\n spanContext(): ReturnType<Span['spanContext']> {\n return this.spanContextValue\n }\n\n setAttribute(key: string, value: AttributeValue): this {\n if (this.ended) {\n return this\n }\n\n this.attributes[key] = value\n this.delegateSpan?.setAttribute(key, value)\n return this\n }\n\n setAttributes(attributes: Parameters<Span['setAttributes']>[0]): this {\n if (this.ended) {\n return this\n }\n\n // OpenTelemetry attributes may be undefined. Ignore them instead of\n // overwriting an existing value as Object.assign would.\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n this.attributes[key] = value\n }\n }\n this.delegateSpan?.setAttributes(attributes)\n return this\n }\n\n addEvent(\n name: string,\n attributesOrStartTime?: Parameters<Span['addEvent']>[1],\n startTime?: Parameters<Span['addEvent']>[2]\n ): this {\n if (this.ended) {\n return this\n }\n\n const eventTime =\n startTime === undefined && isTimestampInput(attributesOrStartTime)\n ? attributesOrStartTime\n : startTime\n this.events.push({\n name,\n timestamp: getTimestamp(eventTime),\n attributes: isSpanStoreAttributes(attributesOrStartTime)\n ? cleanSpanStoreAttributes(attributesOrStartTime)\n : undefined,\n })\n this.delegateSpan?.addEvent(name, attributesOrStartTime, startTime)\n return this\n }\n\n setStatus(status: Parameters<Span['setStatus']>[0]): this {\n if (this.ended) {\n return this\n }\n\n this.statusCode = status.code\n this.statusMessage = status.message\n this.delegateSpan?.setStatus(status)\n return this\n }\n\n updateName(name: string): this {\n if (this.ended) {\n return this\n }\n\n this.name = name\n this.delegateSpan?.updateName(name)\n return this\n }\n\n end(endTime?: Parameters<Span['end']>[0]): void {\n if (this.ended) {\n return\n }\n\n this.ended = true\n try {\n this.delegateSpan?.end(endTime)\n } finally {\n try {\n this.record(endTime)\n } finally {\n this.releaseReferences()\n }\n }\n }\n\n isRecording(): boolean {\n return !this.ended\n }\n\n recordException(\n exception: Parameters<Span['recordException']>[0],\n time?: Parameters<Span['recordException']>[1]\n ): void {\n if (this.ended) {\n return\n }\n\n this.exception = getSpanStoreException(exception)\n this.events.push({\n name: 'exception',\n timestamp: getTimestamp(time),\n attributes: getSpanStoreExceptionAttributes(this.exception),\n })\n this.delegateSpan?.recordException(exception, time)\n }\n\n private record(endTime: Parameters<Span['end']>[0]): void {\n const recordAttributes =\n Object.keys(this.attributes).length > 0 ? this.attributes : undefined\n\n recordSpan({\n name: this.name,\n startTime: this.startTime,\n durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),\n status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',\n traceId: this.spanContextValue.traceId,\n spanId: this.spanContextValue.spanId,\n parentSpanId: this.parentSpanId,\n requestId: this.requestIdentity.requestId,\n requestInsightKind: this.requestIdentity.requestInsightKind,\n htmlRequestId: this.requestIdentity.htmlRequestId,\n route:\n getStringAttribute(recordAttributes, 'next.route') ??\n getStringAttribute(recordAttributes, 'http.route') ??\n this.requestIdentity.route,\n url:\n getStringAttribute(recordAttributes, 'http.url') ??\n this.requestIdentity.url,\n attributes: recordAttributes,\n links: this.links,\n events: this.events.length > 0 ? this.events : undefined,\n error: this.getRecordError(),\n })\n }\n\n private releaseReferences(): void {\n // AsyncLocalStorage can keep an ended span reachable when work spawned\n // inside the span outlives it. Keep only the immutable span context and\n // primitive timing/identity fields needed by the Span API after end.\n this.name = ''\n this.attributes = {}\n this.events = []\n this.delegateSpan = undefined\n this.links = undefined\n this.requestIdentity = {}\n this.statusMessage = undefined\n this.exception = undefined\n }\n\n private getRecordError():\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (this.exception) {\n return this.exception\n }\n\n if (this.statusCode === SpanStatusCode.ERROR && this.statusMessage) {\n return {\n message: this.statusMessage,\n }\n }\n\n return undefined\n }\n}\n\nfunction getSpanStoreLinks(\n links: SpanOptions['links'] | undefined\n): SpanStoreLink[] | undefined {\n const spanStoreLinks = links?.map((link) => ({\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n attributes: cleanSpanStoreAttributes(link.attributes),\n }))\n\n return spanStoreLinks?.length ? spanStoreLinks : undefined\n}\n\nfunction cleanSpanStoreAttributes(\n attributes:\n | Record<string, AttributeValue | undefined>\n | SpanStoreAttributes\n | undefined\n): SpanStoreAttributes {\n const cleanedAttributes: SpanStoreAttributes = {}\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n cleanedAttributes[key] = value\n }\n }\n }\n return cleanedAttributes\n}\n\nfunction getTimestamp(time?: SpanOptions['startTime']): number {\n if (time instanceof Date) {\n return time.getTime()\n }\n\n if (Array.isArray(time)) {\n return time[0] * 1000 + time[1] / 1_000_000\n }\n\n if (typeof time === 'number') {\n return time < performance.timeOrigin / 2\n ? performance.timeOrigin + time\n : time\n }\n\n return performance.timeOrigin + performance.now()\n}\n\nfunction getStringAttribute(\n attributes: SpanStoreAttributes | undefined,\n key: string\n): string | undefined {\n const value = attributes?.[key]\n return typeof value === 'string' ? value : undefined\n}\n\nfunction isSpanStoreAttributes(\n value: Parameters<Span['addEvent']>[1]\n): value is SpanStoreAttributes {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n )\n}\n\nfunction isTimestampInput(\n value: Parameters<Span['addEvent']>[1]\n): value is SpanOptions['startTime'] {\n return (\n typeof value === 'number' || Array.isArray(value) || value instanceof Date\n )\n}\n\nfunction getSpanStoreException(\n exception: Parameters<Span['recordException']>[0]\n):\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (exception instanceof Error) {\n return {\n type: exception.name,\n message: exception.message,\n }\n }\n\n if (typeof exception === 'string') {\n return {\n message: exception,\n }\n }\n\n if (exception && typeof exception === 'object') {\n return {\n type: exception.constructor?.name,\n message: 'message' in exception ? String(exception.message) : undefined,\n }\n }\n\n return undefined\n}\n\nfunction getSpanStoreExceptionAttributes(\n exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n): SpanStoreAttributes | undefined {\n if (!exception) {\n return undefined\n }\n\n const attributes: SpanStoreAttributes = {}\n if (exception.type !== undefined) {\n attributes['exception.type'] = exception.type\n }\n if (exception.message !== undefined) {\n attributes['exception.message'] = exception.message\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined\n}\n\nfunction getCurrentRequestIdentity(): RequestIdentity {\n try {\n const { getRequestInsightsIdentity } =\n require('./request-insights-identity') as typeof import('./request-insights-identity')\n const { workAsyncStorage } =\n require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external')\n const { workUnitAsyncStorage } =\n require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external')\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n const requestInsightsIdentity = getRequestInsightsIdentity()\n const url =\n workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined\n\n return {\n requestId: requestInsightsIdentity?.requestId ?? workStore?.requestId,\n requestInsightKind: requestInsightsIdentity?.kind,\n htmlRequestId:\n requestInsightsIdentity?.htmlRequestId ?? workStore?.htmlRequestId,\n route: workStore?.route,\n url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,\n }\n } catch {\n return {}\n }\n}\n"],"names":["SpanStatusCode","isLocalSpanRecordingEnabled","isRequestInsightsEnabled","recordSpan","TRACE_ID_HEX_LENGTH","SPAN_ID_HEX_LENGTH","lastLocalTraceId","lastLocalSpanId","localSpanAsyncStorage","getLocalTraceId","toString","padStart","getLocalSpanId","createLocalSpan","name","attributes","links","startTime","traceId","spanId","parentSpanId","delegateSpan","LocalRecordingSpan","requestIdentity","getCurrentRequestIdentity","getActiveLocalSpan","getStore","isLocalRecordingSpan","span","withLocalSpan","fn","getLocalSpanAsyncStorage","run","registerLocalSpanRecorder","key","Symbol","for","globalThis","createAsyncLocalStorage","require","constructor","cleanSpanStoreAttributes","events","spanContextValue","spanContext","traceFlags","getSpanStoreLinks","getTimestamp","statusCode","undefined","statusMessage","exception","ended","setAttribute","value","setAttributes","Object","keys","addEvent","attributesOrStartTime","eventTime","isTimestampInput","push","timestamp","isSpanStoreAttributes","setStatus","status","code","message","updateName","end","endTime","record","releaseReferences","isRecording","recordException","time","getSpanStoreException","getSpanStoreExceptionAttributes","recordAttributes","length","durationMs","Math","max","ERROR","requestId","requestInsightKind","htmlRequestId","route","getStringAttribute","url","error","getRecordError","spanStoreLinks","map","link","context","cleanedAttributes","Date","getTime","Array","isArray","performance","timeOrigin","now","Error","type","String","getRequestInsightsIdentity","workAsyncStorage","workUnitAsyncStorage","workStore","workUnitStore","requestInsightsIdentity","kind","pathname","search"],"mappings":"AAMA,SAASA,cAAc,QAAQ,wCAAuC;AACtE,SACEC,2BAA2B,EAC3BC,wBAAwB,EACxBC,UAAU,QAIL,eAAc;AAGrB,SAASF,2BAA2B,QAAQ,eAAc;AAE1D,MAAMG,sBAAsB;AAC5B,MAAMC,qBAAqB;AAI3B,IAAIC,mBAAmB;AACvB,IAAIC,kBAAkB;AACtB,IAAIC;AAEJ,MAAMC,kBAAkB,IACtB,AAAC,CAAA,EAAEH,gBAAe,EAAGI,QAAQ,CAAC,IAAIC,QA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AC;IACzC,IAAIoC,UAAUuD,IAAI,KAAKzD,WAAW;QAChClC,UAAU,CAAC,iBAAiB,GAAGoC,UAAUuD,IAAI;IAC/C;IACA,IAAIvD,UAAUiB,OAAO,KAAKnB,WAAW;QACnClC,UAAU,CAAC,oBAAoB,GAAGoC,UAAUiB,OAAO;IACrD;IACA,OAAOZ,OAAOC,IAAI,CAAC1C,YAAYiE,MAAM,GAAG,IAAIjE,aAAakC;AAC3D;AAEA,SAASzB;IACP,IAAI;QACF,MAAM,EAAEoF,0BAA0B,EAAE,GAClCrE,QAAQ;QACV,MAAM,EAAEsE,gBAAgB,EAAE,GACxBtE,QAAQ;QACV,MAAM,EAAEuE,oBAAoB,EAAE,GAC5BvE,QAAQ;QACV,MAAMwE,YAAYF,iBAAiBnF,QAAQ;QAC3C,MAAMsF,gBAAgBF,qBAAqBpF,QAAQ;QACnD,MAAMuF,0BAA0BL;QAChC,MAAMlB,MACJsB,iBAAiB,SAASA,gBAAgBA,cAActB,GAAG,GAAGzC;QAEhE,OAAO;YACLoC,WAAW4B,CAAAA,2CAAAA,wBAAyB5B,SAAS,MAAI0B,6BAAAA,UAAW1B,SAAS;YACrEC,kBAAkB,EAAE2B,2CAAAA,wBAAyBC,IAAI;YACjD3B,eACE0B,CAAAA,2CAAAA,wBAAyB1B,aAAa,MAAIwB,6BAAAA,UAAWxB,aAAa;YACpEC,KAAK,EAAEuB,6BAAAA,UAAWvB,KAAK;YACvBE,KAAKA,MAAM,GAAGA,IAAIyB,QAAQ,GAAGzB,IAAI0B,MAAM,EAAE,GAAGH,2CAAAA,wBAAyBvB,GAAG;QAC1E;IACF,EAAE,OAAM;QACN,OAAO,CAAC;IACV;AACF","ignoreList":[0]} |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/request-insights-identity.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport { createAsyncLocalStorage } from '../../app-render/async-local-storage'\n\nexport type RequestInsightsIdentity = {\n requestId: string\n htmlRequestId: string\n url: string | undefined\n}\n\n// This storage covers the part of BaseServer request handling that runs before\n// App Render creates workAsyncStorage. Once available, workStore remains the\n// primary identity source for locally recorded spans.\nconst REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY = Symbol.for(\n '@next/request-insights-identity-storage'\n)\n\nfunction getRequestInsightsIdentityStorage(): AsyncLocalStorage<RequestInsightsIdentity> {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY]?: AsyncLocalStorage<RequestInsightsIdentity>\n }\n\n return (globalStore[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY] ??=\n createAsyncLocalStorage())\n}\n\nexport function runWithRequestInsightsIdentity<T>(\n identity: RequestInsightsIdentity,\n fn: () => T\n): T {\n return getRequestInsightsIdentityStorage().run(identity, fn)\n}\n\nexport function getRequestInsightsIdentity():\n | RequestInsightsIdentity\n | undefined {\n return getRequestInsightsIdentityStorage().getStore()\n}\n"],"names":["createAsyncLocalStorage","REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY","Symbol","for","getRequestInsightsIdentityStorage","globalStore","globalThis","runWithRequestInsightsIdentity","identity","fn","run","getRequestInsightsIdentity","getStore"],"mappings":"AACA,SAASA,uBAAuB,QAAQ,uCAAsC;AAQ9E,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,MAAMC,wCAAwCC,OAAOC,GAAG,CACtD;AAGF,SAASC;IACP,MAAMC,cAAcC;IAIpB,OAAQD,WAAW,CAACJ,sCAAsC,KACxDD;AACJ;AAEA,OAAO,SAASO,+BACdC,QAAiC,EACjCC,EAAW;IAEX,OAAOL,oCAAoCM,GAAG,CAACF,UAAUC;AAC3D;AAEA,OAAO,SAASE;IAGd,OAAOP,oCAAoCQ,QAAQ;AACrD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/request-insights-identity.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\nimport { createAsyncLocalStorage } from '../../app-render/async-local-storage'\n\nexport type RequestInsightsIdentity = {\n requestId: string\n kind?: RequestInsightKind\n htmlRequestId: string\n url: string | undefined\n}\n\n// This storage covers the part of BaseServer request handling that runs before\n// App Render creates workAsyncStorage. Once available, workStore remains the\n// primary identity source for locally recorded spans.\nconst REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY = Symbol.for(\n '@next/request-insights-identity-storage'\n)\n\nfunction getRequestInsightsIdentityStorage(): AsyncLocalStorage<RequestInsightsIdentity> {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY]?: AsyncLocalStorage<RequestInsightsIdentity>\n }\n\n return (globalStore[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY] ??=\n createAsyncLocalStorage())\n}\n\nexport function runWithRequestInsightsIdentity<T>(\n identity: RequestInsightsIdentity,\n fn: () => T\n): T {\n return getRequestInsightsIdentityStorage().run(identity, fn)\n}\n\nexport function getRequestInsightsIdentity():\n | RequestInsightsIdentity\n | undefined {\n return getRequestInsightsIdentityStorage().getStore()\n}\n"],"names":["createAsyncLocalStorage","REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY","Symbol","for","getRequestInsightsIdentityStorage","globalStore","globalThis","runWithRequestInsightsIdentity","identity","fn","run","getRequestInsightsIdentity","getStore"],"mappings":"AAEA,SAASA,uBAAuB,QAAQ,uCAAsC;AAS9E,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,MAAMC,wCAAwCC,OAAOC,GAAG,CACtD;AAGF,SAASC;IACP,MAAMC,cAAcC;IAIpB,OAAQD,WAAW,CAACJ,sCAAsC,KACxDD;AACJ;AAEA,OAAO,SAASO,+BACdC,QAAiC,EACjCC,EAAW;IAEX,OAAOL,oCAAoCM,GAAG,CAACF,UAAUC;AAC3D;AAEA,OAAO,SAASE;IAGd,OAAOP,oCAAoCQ,QAAQ;AACrD","ignoreList":[0]} |
@@ -0,1 +1,2 @@ | ||
| import { getRequestInsightKey, getRequestInsightKind } from '../../../shared/lib/request-insights'; | ||
| export { isRequestInsightsEnabled } from './span-store'; | ||
@@ -30,3 +31,9 @@ const MAX_REQUEST_INSIGHTS = 100; | ||
| } | ||
| const insight = this.getOrCreateRequest(span, span.startTime ?? span.timestamp); | ||
| const insight = this.getOrCreateRequest({ | ||
| requestId: span.requestId, | ||
| kind: span.requestInsightKind, | ||
| htmlRequestId: span.htmlRequestId, | ||
| route: span.route, | ||
| url: span.url | ||
| }, span.startTime ?? span.timestamp); | ||
| const spanStartTime = span.startTime ?? span.timestamp; | ||
@@ -61,3 +68,3 @@ insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId; | ||
| } | ||
| const fetchStartTime = fetch.startTime ?? Date.now(); | ||
| const fetchStartTime = fetch.startTime ?? getCurrentTimestamp(); | ||
| const insight = this.getOrCreateRequest(identity, fetchStartTime); | ||
@@ -70,3 +77,3 @@ this.updateTiming(insight, fetchStartTime, fetch.durationMs, false); | ||
| return { | ||
| requests: this.requestOrder.map((requestId)=>this.requests.get(requestId)).filter((request)=>request !== undefined) | ||
| requests: this.requestOrder.map((insightKey)=>this.requests.get(insightKey)).filter((request)=>request !== undefined) | ||
| }; | ||
@@ -86,2 +93,3 @@ } | ||
| updateTiming(insight, startTime, durationMs, isRequestSpan) { | ||
| const insightKey = getRequestInsightKey(insight); | ||
| if (isRequestSpan && durationMs !== undefined) { | ||
@@ -92,3 +100,3 @@ const requestTiming = { | ||
| }; | ||
| this.requestTimings.set(insight.requestId, requestTiming); | ||
| this.requestTimings.set(insightKey, requestTiming); | ||
| insight.startTime = requestTiming.startTime; | ||
@@ -98,3 +106,3 @@ insight.durationMs = requestTiming.durationMs; | ||
| } | ||
| const requestTiming = this.requestTimings.get(insight.requestId); | ||
| const requestTiming = this.requestTimings.get(insightKey); | ||
| if (requestTiming) { | ||
@@ -117,6 +125,11 @@ insight.startTime = requestTiming.startTime; | ||
| const requestId = identity.requestId; | ||
| let insight = this.requests.get(requestId); | ||
| const insightKey = getRequestInsightKey({ | ||
| requestId, | ||
| kind: identity.kind | ||
| }); | ||
| let insight = this.requests.get(insightKey); | ||
| if (!insight) { | ||
| insight = { | ||
| requestId, | ||
| kind: getRequestInsightKind(identity), | ||
| htmlRequestId: identity.htmlRequestId ?? requestId, | ||
@@ -130,4 +143,4 @@ route: identity.route, | ||
| }; | ||
| this.requests.set(requestId, insight); | ||
| this.requestOrder.push(requestId); | ||
| this.requests.set(insightKey, insight); | ||
| this.requestOrder.push(insightKey); | ||
| this.trim(); | ||
@@ -149,6 +162,6 @@ } | ||
| while(this.requestOrder.length > MAX_REQUEST_INSIGHTS){ | ||
| const requestId = this.requestOrder.shift(); | ||
| if (requestId) { | ||
| this.requests.delete(requestId); | ||
| this.requestTimings.delete(requestId); | ||
| const insightKey = this.requestOrder.shift(); | ||
| if (insightKey) { | ||
| this.requests.delete(insightKey); | ||
| this.requestTimings.delete(insightKey); | ||
| } | ||
@@ -209,2 +222,5 @@ } | ||
| } | ||
| function getCurrentTimestamp() { | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
| function sanitizeSpanAttributes(attributes) { | ||
@@ -211,0 +227,0 @@ if (!attributes) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/request-insights.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type {\n RequestInsight,\n RequestInsightFetch,\n RequestInsightsSnapshot,\n} from '../../../next-devtools/shared/request-insights'\nimport type { SpanStoreRecord } from './span-store'\nexport { isRequestInsightsEnabled } from './span-store'\n\nconst MAX_REQUEST_INSIGHTS = 100\nconst REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')\nconst CLIENT_COMPONENT_LOADING_SPAN_TYPE =\n 'NextNodeServer.clientComponentLoading'\n\ntype RequestInsightsListener = (insight: RequestInsight) => void\ntype RequestInsightIdentity = {\n requestId?: string\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nconst REDACTED_VALUE = 'redacted'\nconst SAFE_SPAN_ATTRIBUTE_KEYS = new Set([\n 'http.method',\n 'http.route',\n 'http.status_code',\n 'http.url',\n 'net.peer.name',\n 'net.peer.port',\n 'next.fetch.cache_reason',\n 'next.fetch.cache_status',\n 'next.fetch.idx',\n 'next.route',\n 'next.rsc',\n 'next.segment',\n 'next.span_category',\n 'next.span_name',\n 'next.span_type',\n])\nconst SENSITIVE_PARAM_NAME_RE =\n /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i\n\nclass InMemoryRequestInsightsStore {\n private readonly requests = new Map<string, RequestInsight>()\n private readonly requestTimings = new Map<\n string,\n { startTime: number; durationMs: number }\n >()\n private readonly requestOrder: string[] = []\n private readonly listeners = new Set<RequestInsightsListener>()\n\n recordSpan(span: SpanStoreRecord): void {\n if (!span.requestId) {\n return\n }\n\n const insight = this.getOrCreateRequest(\n span,\n span.startTime ?? span.timestamp\n )\n\n const spanStartTime = span.startTime ?? span.timestamp\n insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? span.route\n insight.url = insight.url ?? sanitizeUrl(span.url)\n this.updateTiming(\n insight,\n spanStartTime,\n span.durationMs,\n span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'\n )\n insight.status =\n insight.status === 'error' || span.status === 'error'\n ? 'error'\n : span.status === 'ok'\n ? 'ok'\n : insight.status\n\n insight.spans.push({\n name: span.name,\n startTime: spanStartTime,\n durationMs: span.durationMs,\n status: span.status,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n attributes: sanitizeSpanAttributes(span.attributes),\n links: sanitizeSpanLinks(span.links),\n events: sanitizeSpanEvents(span.events),\n error: span.error,\n })\n\n const fetch = getFetchInsight(span)\n if (fetch) {\n this.recordFetchForInsight(insight, fetch)\n }\n\n this.notify(insight)\n }\n\n recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {\n if (!identity.requestId) {\n return\n }\n\n const fetchStartTime = fetch.startTime ?? Date.now()\n const insight = this.getOrCreateRequest(identity, fetchStartTime)\n this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)\n this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))\n this.notify(insight)\n }\n\n getSnapshot(): RequestInsightsSnapshot {\n return {\n requests: this.requestOrder\n .map((requestId) => this.requests.get(requestId))\n .filter((request): request is RequestInsight => request !== undefined),\n }\n }\n\n subscribe(listener: RequestInsightsListener): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n clear(): void {\n this.requests.clear()\n this.requestTimings.clear()\n this.requestOrder.length = 0\n }\n\n private updateTiming(\n insight: RequestInsight,\n startTime: number,\n durationMs: number | undefined,\n isRequestSpan: boolean\n ): void {\n if (isRequestSpan && durationMs !== undefined) {\n const requestTiming = { startTime, durationMs }\n this.requestTimings.set(insight.requestId, requestTiming)\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const requestTiming = this.requestTimings.get(insight.requestId)\n if (requestTiming) {\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const endTime = startTime + (durationMs ?? 0)\n const requestEndTime = insight.startTime + (insight.durationMs ?? 0)\n insight.startTime = Math.min(insight.startTime, startTime)\n insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime\n }\n\n private notify(insight: RequestInsight): void {\n for (const listener of this.listeners) {\n listener(insight)\n }\n }\n\n private getOrCreateRequest(\n identity: RequestInsightIdentity,\n startTime: number\n ): RequestInsight {\n const requestId = identity.requestId!\n let insight = this.requests.get(requestId)\n\n if (!insight) {\n insight = {\n requestId,\n htmlRequestId: identity.htmlRequestId ?? requestId,\n route: identity.route,\n url: sanitizeUrl(identity.url),\n startTime,\n status: 'pending',\n spans: [],\n fetches: [],\n }\n this.requests.set(requestId, insight)\n this.requestOrder.push(requestId)\n this.trim()\n }\n\n insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? identity.route\n insight.url = insight.url ?? sanitizeUrl(identity.url)\n insight.startTime = Math.min(insight.startTime, startTime)\n\n return insight\n }\n\n private recordFetchForInsight(\n insight: RequestInsight,\n fetch: RequestInsightFetch\n ): void {\n if (\n insight.fetches.some(\n (existingFetch) =>\n existingFetch.url === fetch.url &&\n (existingFetch.index !== undefined && fetch.index !== undefined\n ? existingFetch.index === fetch.index\n : existingFetch.startTime === fetch.startTime)\n )\n ) {\n return\n }\n\n insight.fetches.push(sanitizeFetchInsight(fetch))\n }\n\n private trim(): void {\n while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {\n const requestId = this.requestOrder.shift()\n if (requestId) {\n this.requests.delete(requestId)\n this.requestTimings.delete(requestId)\n }\n }\n }\n}\n\nexport function recordRequestInsightSpan(span: SpanStoreRecord): void {\n if (\n span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE\n ) {\n return\n }\n\n getRequestInsightsStore().recordSpan(span)\n}\n\nexport function recordRequestInsightFetch(\n identity: RequestInsightIdentity,\n fetch: RequestInsightFetch\n): void {\n getRequestInsightsStore().recordFetch(identity, fetch)\n}\n\nexport function getRequestInsightsSnapshot(): RequestInsightsSnapshot {\n return getRequestInsightsStore().getSnapshot()\n}\n\nexport function subscribeRequestInsights(\n listener: RequestInsightsListener\n): () => void {\n return getRequestInsightsStore().subscribe(listener)\n}\n\nexport function clearRequestInsightsForTest(): void {\n getRequestInsightsStore().clear()\n}\n\nfunction getRequestInsightsStore(): InMemoryRequestInsightsStore {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore\n }\n\n return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=\n new InMemoryRequestInsightsStore())\n}\n\nfunction getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {\n const attributes = span.attributes\n\n if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {\n return null\n }\n\n return {\n url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),\n method: getStringAttribute(attributes['http.method']),\n statusCode: getNumberAttribute(attributes['http.status_code']),\n startTime: span.startTime ?? span.timestamp,\n durationMs: span.durationMs,\n cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),\n cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),\n index: getNumberAttribute(attributes['next.fetch.idx']),\n }\n}\n\nfunction sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {\n return {\n ...fetch,\n url: sanitizeUrl(fetch.url),\n }\n}\n\nfunction sanitizeSpanAttributes(\n attributes: SpanStoreRecord['attributes']\n): SpanStoreRecord['attributes'] {\n if (!attributes) {\n return undefined\n }\n\n const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {\n continue\n }\n\n sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value\n }\n\n return Object.keys(sanitized).length > 0 ? sanitized : undefined\n}\n\nfunction sanitizeSpanEvents(\n events: SpanStoreRecord['events']\n): SpanStoreRecord['events'] {\n return events?.map((event) => ({\n ...event,\n attributes: sanitizeSpanAttributes(event.attributes),\n }))\n}\n\nfunction sanitizeSpanLinks(\n links: SpanStoreRecord['links']\n): SpanStoreRecord['links'] {\n return links?.map((link) => ({\n ...link,\n attributes: sanitizeSpanAttributes(link.attributes),\n }))\n}\n\nfunction sanitizeUrlAttribute(value: AttributeValue): AttributeValue {\n return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value\n}\n\nfunction sanitizeUrl(value: string | undefined): string | undefined {\n if (!value) {\n return value\n }\n\n const isRelativeUrl = value.startsWith('/')\n\n try {\n const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)\n\n url.username = ''\n url.password = ''\n\n for (const name of Array.from(url.searchParams.keys())) {\n if (SENSITIVE_PARAM_NAME_RE.test(name)) {\n url.searchParams.set(name, REDACTED_VALUE)\n }\n }\n\n return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href\n } catch {\n return value\n }\n}\n\nfunction getStringAttribute(value: AttributeValue | undefined) {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction getNumberAttribute(value: AttributeValue | undefined) {\n return typeof value === 'number' ? value : undefined\n}\n"],"names":["isRequestInsightsEnabled","MAX_REQUEST_INSIGHTS","REQUEST_INSIGHTS_STORE_KEY","Symbol","for","CLIENT_COMPONENT_LOADING_SPAN_TYPE","REDACTED_VALUE","SAFE_SPAN_ATTRIBUTE_KEYS","Set","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","requestId","insight","getOrCreateRequest","startTime","timestamp","spanStartTime","htmlRequestId","route","url","sanitizeUrl","updateTiming","durationMs","attributes","status","spans","push","name","traceId","spanId","parentSpanId","sanitizeSpanAttributes","links","sanitizeSpanLinks","events","sanitizeSpanEvents","error","fetch","getFetchInsight","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","Date","now","sanitizeFetchInsight","getSnapshot","requests","requestOrder","map","get","filter","request","undefined","subscribe","listener","listeners","add","delete","clear","requestTimings","length","isRequestSpan","requestTiming","set","endTime","requestEndTime","Math","min","max","fetches","trim","some","existingFetch","index","shift","Map","recordRequestInsightSpan","getRequestInsightsStore","recordRequestInsightFetch","getRequestInsightsSnapshot","subscribeRequestInsights","clearRequestInsightsForTest","globalStore","globalThis","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","sanitized","key","value","Object","entries","has","sanitizeUrlAttribute","keys","event","link","isRelativeUrl","startsWith","URL","username","password","Array","from","searchParams","test","pathname","search","hash","href"],"mappings":"AAOA,SAASA,wBAAwB,QAAQ,eAAc;AAEvD,MAAMC,uBAAuB;AAC7B,MAAM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AC7C;AAEA,SAASmC,mBAAmBK,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQxC;AAC7C","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/request-insights.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type {\n RequestInsight,\n RequestInsightFetch,\n RequestInsightsSnapshot,\n} from '../../../next-devtools/shared/request-insights'\nimport type { RequestInsightKind } from '../../../shared/lib/request-insights'\nimport {\n getRequestInsightKey,\n getRequestInsightKind,\n} from '../../../shared/lib/request-insights'\nimport type { SpanStoreRecord } from './span-store'\nexport { isRequestInsightsEnabled } from './span-store'\n\nconst MAX_REQUEST_INSIGHTS = 100\nconst REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')\nconst CLIENT_COMPONENT_LOADING_SPAN_TYPE =\n 'NextNodeServer.clientComponentLoading'\n\ntype RequestInsightsListener = (insight: RequestInsight) => void\ntype RequestInsightIdentity = {\n requestId?: string\n kind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nconst REDACTED_VALUE = 'redacted'\nconst SAFE_SPAN_ATTRIBUTE_KEYS = new Set([\n 'http.method',\n 'http.route',\n 'http.status_code',\n 'http.url',\n 'net.peer.name',\n 'net.peer.port',\n 'next.fetch.cache_reason',\n 'next.fetch.cache_status',\n 'next.fetch.idx',\n 'next.route',\n 'next.rsc',\n 'next.segment',\n 'next.span_category',\n 'next.span_name',\n 'next.span_type',\n])\nconst SENSITIVE_PARAM_NAME_RE =\n /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i\n\nclass InMemoryRequestInsightsStore {\n private readonly requests = new Map<string, RequestInsight>()\n private readonly requestTimings = new Map<\n string,\n { startTime: number; durationMs: number }\n >()\n private readonly requestOrder: string[] = []\n private readonly listeners = new Set<RequestInsightsListener>()\n\n recordSpan(span: SpanStoreRecord): void {\n if (!span.requestId) {\n return\n }\n\n const insight = this.getOrCreateRequest(\n {\n requestId: span.requestId,\n kind: span.requestInsightKind,\n htmlRequestId: span.htmlRequestId,\n route: span.route,\n url: span.url,\n },\n span.startTime ?? span.timestamp\n )\n\n const spanStartTime = span.startTime ?? span.timestamp\n insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? span.route\n insight.url = insight.url ?? sanitizeUrl(span.url)\n this.updateTiming(\n insight,\n spanStartTime,\n span.durationMs,\n span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'\n )\n insight.status =\n insight.status === 'error' || span.status === 'error'\n ? 'error'\n : span.status === 'ok'\n ? 'ok'\n : insight.status\n\n insight.spans.push({\n name: span.name,\n startTime: spanStartTime,\n durationMs: span.durationMs,\n status: span.status,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n attributes: sanitizeSpanAttributes(span.attributes),\n links: sanitizeSpanLinks(span.links),\n events: sanitizeSpanEvents(span.events),\n error: span.error,\n })\n\n const fetch = getFetchInsight(span)\n if (fetch) {\n this.recordFetchForInsight(insight, fetch)\n }\n\n this.notify(insight)\n }\n\n recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {\n if (!identity.requestId) {\n return\n }\n\n const fetchStartTime = fetch.startTime ?? getCurrentTimestamp()\n const insight = this.getOrCreateRequest(identity, fetchStartTime)\n this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)\n this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))\n this.notify(insight)\n }\n\n getSnapshot(): RequestInsightsSnapshot {\n return {\n requests: this.requestOrder\n .map((insightKey) => this.requests.get(insightKey))\n .filter((request): request is RequestInsight => request !== undefined),\n }\n }\n\n subscribe(listener: RequestInsightsListener): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n clear(): void {\n this.requests.clear()\n this.requestTimings.clear()\n this.requestOrder.length = 0\n }\n\n private updateTiming(\n insight: RequestInsight,\n startTime: number,\n durationMs: number | undefined,\n isRequestSpan: boolean\n ): void {\n const insightKey = getRequestInsightKey(insight)\n if (isRequestSpan && durationMs !== undefined) {\n const requestTiming = { startTime, durationMs }\n this.requestTimings.set(insightKey, requestTiming)\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const requestTiming = this.requestTimings.get(insightKey)\n if (requestTiming) {\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const endTime = startTime + (durationMs ?? 0)\n const requestEndTime = insight.startTime + (insight.durationMs ?? 0)\n insight.startTime = Math.min(insight.startTime, startTime)\n insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime\n }\n\n private notify(insight: RequestInsight): void {\n for (const listener of this.listeners) {\n listener(insight)\n }\n }\n\n private getOrCreateRequest(\n identity: RequestInsightIdentity,\n startTime: number\n ): RequestInsight {\n const requestId = identity.requestId!\n const insightKey = getRequestInsightKey({\n requestId,\n kind: identity.kind,\n })\n let insight = this.requests.get(insightKey)\n\n if (!insight) {\n insight = {\n requestId,\n kind: getRequestInsightKind(identity),\n htmlRequestId: identity.htmlRequestId ?? requestId,\n route: identity.route,\n url: sanitizeUrl(identity.url),\n startTime,\n status: 'pending',\n spans: [],\n fetches: [],\n }\n this.requests.set(insightKey, insight)\n this.requestOrder.push(insightKey)\n this.trim()\n }\n\n insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? identity.route\n insight.url = insight.url ?? sanitizeUrl(identity.url)\n insight.startTime = Math.min(insight.startTime, startTime)\n\n return insight\n }\n\n private recordFetchForInsight(\n insight: RequestInsight,\n fetch: RequestInsightFetch\n ): void {\n if (\n insight.fetches.some(\n (existingFetch) =>\n existingFetch.url === fetch.url &&\n (existingFetch.index !== undefined && fetch.index !== undefined\n ? existingFetch.index === fetch.index\n : existingFetch.startTime === fetch.startTime)\n )\n ) {\n return\n }\n\n insight.fetches.push(sanitizeFetchInsight(fetch))\n }\n\n private trim(): void {\n while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {\n const insightKey = this.requestOrder.shift()\n if (insightKey) {\n this.requests.delete(insightKey)\n this.requestTimings.delete(insightKey)\n }\n }\n }\n}\n\nexport function recordRequestInsightSpan(span: SpanStoreRecord): void {\n if (\n span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE\n ) {\n return\n }\n\n getRequestInsightsStore().recordSpan(span)\n}\n\nexport function recordRequestInsightFetch(\n identity: RequestInsightIdentity,\n fetch: RequestInsightFetch\n): void {\n getRequestInsightsStore().recordFetch(identity, fetch)\n}\n\nexport function getRequestInsightsSnapshot(): RequestInsightsSnapshot {\n return getRequestInsightsStore().getSnapshot()\n}\n\nexport function subscribeRequestInsights(\n listener: RequestInsightsListener\n): () => void {\n return getRequestInsightsStore().subscribe(listener)\n}\n\nexport function clearRequestInsightsForTest(): void {\n getRequestInsightsStore().clear()\n}\n\nfunction getRequestInsightsStore(): InMemoryRequestInsightsStore {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore\n }\n\n return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=\n new InMemoryRequestInsightsStore())\n}\n\nfunction getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {\n const attributes = span.attributes\n\n if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {\n return null\n }\n\n return {\n url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),\n method: getStringAttribute(attributes['http.method']),\n statusCode: getNumberAttribute(attributes['http.status_code']),\n startTime: span.startTime ?? span.timestamp,\n durationMs: span.durationMs,\n cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),\n cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),\n index: getNumberAttribute(attributes['next.fetch.idx']),\n }\n}\n\nfunction sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {\n return {\n ...fetch,\n url: sanitizeUrl(fetch.url),\n }\n}\n\nfunction getCurrentTimestamp(): number {\n return performance.timeOrigin + performance.now()\n}\n\nfunction sanitizeSpanAttributes(\n attributes: SpanStoreRecord['attributes']\n): SpanStoreRecord['attributes'] {\n if (!attributes) {\n return undefined\n }\n\n const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {\n continue\n }\n\n sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value\n }\n\n return Object.keys(sanitized).length > 0 ? sanitized : undefined\n}\n\nfunction sanitizeSpanEvents(\n events: SpanStoreRecord['events']\n): SpanStoreRecord['events'] {\n return events?.map((event) => ({\n ...event,\n attributes: sanitizeSpanAttributes(event.attributes),\n }))\n}\n\nfunction sanitizeSpanLinks(\n links: SpanStoreRecord['links']\n): SpanStoreRecord['links'] {\n return links?.map((link) => ({\n ...link,\n attributes: sanitizeSpanAttributes(link.attributes),\n }))\n}\n\nfunction sanitizeUrlAttribute(value: AttributeValue): AttributeValue {\n return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value\n}\n\nfunction sanitizeUrl(value: string | undefined): string | undefined {\n if (!value) {\n return value\n }\n\n const isRelativeUrl = value.startsWith('/')\n\n try {\n const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)\n\n url.username = ''\n url.password = ''\n\n for (const name of Array.from(url.searchParams.keys())) {\n if (SENSITIVE_PARAM_NAME_RE.test(name)) {\n url.searchParams.set(name, REDACTED_VALUE)\n }\n }\n\n return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href\n } catch {\n return value\n }\n}\n\nfunction getStringAttribute(value: AttributeValue | undefined) {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction getNumberAttribute(value: AttributeValue | undefined) {\n return typeof value === 'number' ? value : undefined\n}\n"],"names":["getRequestInsightKey","getRequestInsightKind","isRequestInsightsEnabled","MAX_REQUEST_INSIGHTS","REQUEST_INSIGHTS_STORE_KEY","Symbol","for","CLIENT_COMPONENT_LOADING_SPAN_TYPE","REDACTED_VALUE","SAFE_SPAN_ATTRIBUTE_KEYS","Set","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","requestId","insight","getOrCreateRequest","kind","requestInsightKind","htmlRequestId","route","url","startTime","timestamp","spanStartTime","sanitizeUrl","updateTiming","durationMs","attributes","status","spans","push","name","traceId","spanId","parentSpanId","sanitizeSpanAttributes","links","sanitizeSpanLinks","events","sanitizeSpanEvents","error","fetch","getFetchInsight","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","getCurrentTimestamp","sanitizeFetchInsight","getSnapshot","requests","requestOrder","map","insightKey","get","filter","request","undefined","subscribe","listener","listeners","add","delete","clear","requestTimings","length","isRequestSpan","requestTiming","set","endTime","requestEndTime","Math","min","max","fetches","trim","some","existingFetch","index","shift","Map","recordRequestInsightSpan","getRequestInsightsStore","recordRequestInsightFetch","getRequestInsightsSnapshot","subscribeRequestInsights","clearRequestInsightsForTest","globalStore","globalThis","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","performance","timeOrigin","now","sanitized","key","value","Object","entries","has","sanitizeUrlAttribute","keys","event","link","isRelativeUrl","startsWith","URL","username","password","Array","from","searchParams","test","pathname","search","hash","href"],"mappings":"AAOA,SACEA,oBAAoB,EACpBC,qBAAqB,QAChB,uCAAsC;AAE7C,SAASC,wBAAwB,QAAQ,eAAc;AAEvD,MAAMC,uBAAuB;AAC7B,MAAMC,6BAA6BC,OAAOC,GAAG,CAAC;AAC9C,MAAMC,qCACJ;AAWF,MAAMC,iBAAiB;AACvB,MAAMC,2BAA2B,IAAIC,IAAI;IACvC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMC,0BACJ;AAEF,MAAMC;IASJC,WAAWC,IAAqB,EAAQ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BW,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQ3C;AAC7C;AAEA,SAASmC,mBAAmBQ,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQ3C;AAC7C","ignoreList":[0]} |
@@ -7,3 +7,3 @@ let spanRecorderForTest; | ||
| const spanRecord = { | ||
| timestamp: Date.now(), | ||
| timestamp: getCurrentTimestamp(), | ||
| ...record | ||
@@ -36,3 +36,6 @@ }; | ||
| } | ||
| function getCurrentTimestamp() { | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
| //# sourceMappingURL=span-store.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/span-store.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\n\nexport type SpanStoreAttributes = Record<string, AttributeValue>\n\nexport type SpanStoreLink = {\n traceId: string\n spanId: string\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreEvent = {\n name: string\n timestamp: number\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreRecord = {\n name: string\n timestamp: number\n startTime?: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n requestId?: string\n htmlRequestId?: string\n route?: string\n url?: string\n attributes?: SpanStoreAttributes\n links?: SpanStoreLink[]\n events?: SpanStoreEvent[]\n error?: {\n type?: string\n message?: string\n }\n}\n\ntype SpanRecorderForTest = (span: SpanStoreRecord) => void\n\nlet spanRecorderForTest: SpanRecorderForTest | undefined\n\nexport function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {\n if (!isLocalSpanRecordingEnabled()) {\n return\n }\n\n const spanRecord: SpanStoreRecord = {\n timestamp: Date.now(),\n ...record,\n }\n\n spanRecorderForTest?.(spanRecord)\n\n if (isRequestInsightsEnabled() && spanRecord.requestId) {\n const { recordRequestInsightSpan } =\n require('./request-insights') as typeof import('./request-insights')\n recordRequestInsightSpan(spanRecord)\n }\n}\n\nexport function setSpanRecorderForTest(\n recorder: SpanRecorderForTest | undefined\n): void {\n spanRecorderForTest = recorder\n}\n\nexport function isLocalSpanRecordingEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n return spanRecorderForTest !== undefined || isRequestInsightsEnabled()\n}\n\nexport function isRequestInsightsEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n const value = process.env.__NEXT_REQUEST_INSIGHTS\n return isEnabledEnvValue(value)\n}\n\nfunction isEnabledEnvValue(value: string | undefined): boolean {\n return value === '1' || value === 'true' || (value as unknown) === true\n}\n"],"names":["spanRecorderForTest","recordSpan","record","isLocalSpanRecordingEnabled","spanRecord","timestamp","Date","now","isRequestInsightsEnabled","requestId","recordRequestInsightSpan","require","setSpanRecorderForTest","recorder","process","env","__NEXT_DEV_SERVER","undefined","value","__NEXT_REQUEST_INSIGHTS","isEnabledEnvValue"],"mappings":"AAwCA,IAAIA;AAEJ,OAAO,SAASC,WAAWC,MAA0C;IACnE,IAAI,CAACC,+BAA+B;QAClC;IACF;IAEA,MAAMC,aAA8B;QAClCC,WAAWC,KAAKC,GAAG;QACnB,GAAGL,MAAM;IACX;IAEAF,uCAAAA,oBAAsBI;IAEtB,IAAII,8BAA8BJ,WAAWK,SAAS,EAAE;QACtD,MAAM,EAAEC,wBAAwB,EAAE,GAChCC,QAAQ;QACVD,yBAAyBN;IAC3B;AACF;AAEA,OAAO,SAASQ,uBACdC,QAAyC;IAEzCb,sBAAsBa;AACxB;AAEA,OAAO,SAASV;IACd,IAAI,CAACW,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,OAAOhB,wBAAwBiB,aAAaT;AAC9C;AAEA,OAAO,SAASA;IACd,IAAI,CAACM,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,MAAME,QAAQJ,QAAQC,GAAG,CAACI,uBAAuB;IACjD,OAAOC,kBAAkBF;AAC3B;AAEA,SAASE,kBAAkBF,KAAyB;IAClD,OAAOA,UAAU,OAAOA,UAAU,UAAU,AAACA,UAAsB;AACrE","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../../src/server/lib/trace/span-store.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport type SpanStoreAttributes = Record<string, AttributeValue>\n\nexport type SpanStoreLink = {\n traceId: string\n spanId: string\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreEvent = {\n name: string\n timestamp: number\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreRecord = {\n name: string\n timestamp: number\n startTime?: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n requestId?: string\n requestInsightKind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n attributes?: SpanStoreAttributes\n links?: SpanStoreLink[]\n events?: SpanStoreEvent[]\n error?: {\n type?: string\n message?: string\n }\n}\n\ntype SpanRecorderForTest = (span: SpanStoreRecord) => void\n\nlet spanRecorderForTest: SpanRecorderForTest | undefined\n\nexport function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {\n if (!isLocalSpanRecordingEnabled()) {\n return\n }\n\n const spanRecord: SpanStoreRecord = {\n timestamp: getCurrentTimestamp(),\n ...record,\n }\n\n spanRecorderForTest?.(spanRecord)\n\n if (isRequestInsightsEnabled() && spanRecord.requestId) {\n const { recordRequestInsightSpan } =\n require('./request-insights') as typeof import('./request-insights')\n recordRequestInsightSpan(spanRecord)\n }\n}\n\nexport function setSpanRecorderForTest(\n recorder: SpanRecorderForTest | undefined\n): void {\n spanRecorderForTest = recorder\n}\n\nexport function isLocalSpanRecordingEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n return spanRecorderForTest !== undefined || isRequestInsightsEnabled()\n}\n\nexport function isRequestInsightsEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n const value = process.env.__NEXT_REQUEST_INSIGHTS\n return isEnabledEnvValue(value)\n}\n\nfunction isEnabledEnvValue(value: string | undefined): boolean {\n return value === '1' || value === 'true' || (value as unknown) === true\n}\n\nfunction getCurrentTimestamp(): number {\n return performance.timeOrigin + performance.now()\n}\n"],"names":["spanRecorderForTest","recordSpan","record","isLocalSpanRecordingEnabled","spanRecord","timestamp","getCurrentTimestamp","isRequestInsightsEnabled","requestId","recordRequestInsightSpan","require","setSpanRecorderForTest","recorder","process","env","__NEXT_DEV_SERVER","undefined","value","__NEXT_REQUEST_INSIGHTS","isEnabledEnvValue","performance","timeOrigin","now"],"mappings":"AA0CA,IAAIA;AAEJ,OAAO,SAASC,WAAWC,MAA0C;IACnE,IAAI,CAACC,+BAA+B;QAClC;IACF;IAEA,MAAMC,aAA8B;QAClCC,WAAWC;QACX,GAAGJ,MAAM;IACX;IAEAF,uCAAAA,oBAAsBI;IAEtB,IAAIG,8BAA8BH,WAAWI,SAAS,EAAE;QACtD,MAAM,EAAEC,wBAAwB,EAAE,GAChCC,QAAQ;QACVD,yBAAyBL;IAC3B;AACF;AAEA,OAAO,SAASO,uBACdC,QAAyC;IAEzCZ,sBAAsBY;AACxB;AAEA,OAAO,SAAST;IACd,IAAI,CAACU,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,OAAOf,wBAAwBgB,aAAaT;AAC9C;AAEA,OAAO,SAASA;IACd,IAAI,CAACM,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,MAAME,QAAQJ,QAAQC,GAAG,CAACI,uBAAuB;IACjD,OAAOC,kBAAkBF;AAC3B;AAEA,SAASE,kBAAkBF,KAAyB;IAClD,OAAOA,UAAU,OAAOA,UAAU,UAAU,AAACA,UAAsB;AACrE;AAEA,SAASX;IACP,OAAOc,YAAYC,UAAU,GAAGD,YAAYE,GAAG;AACjD","ignoreList":[0]} |
@@ -7,3 +7,3 @@ import { Readable } from 'node:stream'; | ||
| import { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'; | ||
| import { makeHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { makeDynamicHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { getClientReferenceManifest, getServerModuleMap } from '../app-render/manifests-singleton'; | ||
@@ -161,3 +161,8 @@ // eslint-disable-next-line import/no-extraneous-dependencies | ||
| // budget then classifies the route as dynamic. | ||
| return makeHangingPromise(renderSignal, workStore.route, 'dynamic `ImageResponse`'); | ||
| // Whatever dynamic input made the element partial already classified | ||
| // itself when it created its own hanging promise (cookies() creates a | ||
| // runtime hanging promise, an uncached fetch creates a dynamic one, | ||
| // ...), so this wrapper adds no new information and can use the | ||
| // non-recording dynamic variant. | ||
| return makeDynamicHangingPromise(renderSignal, workStore.route, 'dynamic `ImageResponse`'); | ||
| } | ||
@@ -164,0 +169,0 @@ // The serialization finished before any dynamic input was needed, so we |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n return makeHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["Readable","createHash","InvariantError","workAsyncStorage","workUnitAsyncStorage","createHangingInputAbortSignal","makeHangingPromise","getClientReferenceManifest","getServerModuleMap","prerenderToNodeStream","createFromNodeStream","importOgModule","getCachedImageResponseBody","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","element","options","hangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","prelude","signal","filterStackFrame","onError","error","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","from","moduleLoading","moduleMap","serverModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,UAAU,QAAmB,cAAa;AAEnD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SAASC,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SAASC,6BAA6B,QAAQ,kCAAiC;AAC/E,SAASC,kBAAkB,QAAQ,6BAA4B;AAC/D,SACEC,0BAA0B,EAC1BC,kBAAkB,QACb,oCAAmC;AAC1C,6DAA6D;AAC7D,SAASC,qBAAqB,QAAQ,kCAAiC;AACvE,6DAA6D;AAC7D,SAASC,oBAAoB,QAAQ,kCAAiC;AAMtE,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAEA;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,SAASC,2BACdC,IAAuB;IAEvB,OAAO,IAAIC,eAA2B;QACpC,MAAMC,OAAMC,UAAU;YACpB,MAAMC,cAAc,MAAMC,kCAAkCL;YAC5D,IAAII,Y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M,AAACqB,KAAiC,CAACqB,IAAI;IACrE;AACF;AAEA;;;;CAIC,GACD,SAASpB,oBAAoBtB,IAAU,EAAE2C,GAAW,EAAEC,KAAiB;IACrE5C,KAAKC,MAAM,CAAC,GAAG0C,MAAMC,MAAMpF,UAAU,CAAC,CAAC,CAAC;IACxCwC,KAAKC,MAAM,CAAC2C;AACd;AAEA,eAAe5E,+BACbd,IAAuB;IAEvB,MAAM2F,kBAAkB,AAAC,CAAA,MAAM7F,gBAAe,EAAG8F,aAAa;IAC9D,MAAMC,gBAAgB,IAAIF,mBAAmB3F;IAE7C,IAAI,CAAC6F,cAAcC,IAAI,EAAE;QACvB,OAAO,IAAIxB,YAAY;IACzB;IAEA,OAAOuB,cAAczF,WAAW;AAClC;AAEA,MAAM2F,kBAAkBC,OAAOC,GAAG,CAAC;AAEnC;;;;;;CAMC,GACD,SAASpC,oBAAoBqC,IAAa;IACxC,IAAIA,SAAS,QAAQ,OAAOA,SAAS,UAAU;QAC7C,OAAOA;IACT;IAEA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAM1C,UAAU+E;IAChB,IAAI/E,QAAQqF,KAAK,IAAI,cAAcrF,QAAQqF,KAAK,EAAE;QAChD,OAAO;YACL,GAAGrF,OAAO;YACVqF,OAAO;gBACL,GAAGrF,QAAQqF,KAAK;gBAChBC,UAAU5C,oBAAoB1C,QAAQqF,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["Readable","createHash","InvariantError","workAsyncStorage","workUnitAsyncStorage","createHangingInputAbortSignal","makeDynamicHangingPromise","getClientReferenceManifest","getServerModuleMap","prerenderToNodeStream","createFromNodeStream","importOgModule","getCachedImageResponseBody","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","element","options","hangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","prelude","signal","filterStackFrame","onError","error","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","from","moduleLoading","moduleMap","serverModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,cAAa;AACtC,SAASC,UAAU,QAAmB,cAAa;AAEnD,SAAS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ACxC,IAAIA,SAAS,QAAQ,OAAOA,SAAS,UAAU;QAC7C,OAAOA;IACT;IAEA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAM1C,UAAU+E;IAChB,IAAI/E,QAAQqF,KAAK,IAAI,cAAcrF,QAAQqF,KAAK,EAAE;QAChD,OAAO;YACL,GAAGrF,OAAO;YACVqF,OAAO;gBACL,GAAGrF,QAAQqF,KAAK;gBAChBC,UAAU5C,oBAAoB1C,QAAQqF,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]} |
@@ -5,3 +5,3 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'; | ||
| import { makeHangingPromise, makeDevtoolsIOAwarePromise } from '../dynamic-rendering-utils'; | ||
| import { makeDynamicHangingPromise, makeDevtoolsIOAwarePromise } from '../dynamic-rendering-utils'; | ||
| import { isRequestApiAllowedInCurrentPhase } from './utils'; | ||
@@ -85,3 +85,3 @@ import { applyOwnerStack } from '../dynamic-rendering-utils'; | ||
| // stall at this point. | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, '`connection()`'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, '`connection()`'); | ||
| case 'validation-client': | ||
@@ -88,0 +88,0 @@ { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-ppr':\n // We use React's postpone API to interrupt rendering here to create a\n // dynamic hole\n return postponeWithTracking(\n workStore.route,\n 'connection',\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeHangingPromise","makeDevtoolsIOAwarePromise","isRequestApiAllowedInCurrentPhase","applyOwnerStack","RenderStage","InvariantError","connection","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","renderSignal","exportName","dynamicTracking","process","env","NODE_ENV","asyncApiPromises","Dynamic"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SACEC,2BAA2B,EAC3BC,oBAAoB,QACf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,kBAAkB,EAClBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,cAAc,QAAQ,mCAAkC;AAEjE;;;;CAIC,GACD,OAAO,SAASC;IACd,MAAMC,oBA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E;IACzE,8GAA8G;IAC9G,sDAAsD;IACtDhB,4BAA4Ba;AAC9B","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-ppr':\n // We use React's postpone API to interrupt rendering here to create a\n // dynamic hole\n return postponeWithTracking(\n workStore.route,\n 'connection',\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDynamicHangingPromise","makeDevtoolsIOAwarePromise","isRequestApiAllowedInCurrentPhase","applyOwnerStack","RenderStage","InvariantError","connection","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","renderSignal","exportName","dynamicTracking","process","env","NODE_ENV","asyncApiPromises","Dynamic"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SACEC,2BAA2B,EAC3BC,oBAAoB,QACf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC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,OAAOlB,cAAckB,gBAAgB,CAACtB,UAAU;wBAClD;wBACA,OAAOL,2BACLe,WACAN,eACAN,YAAYyB,OAAO;oBAEvB,OAAO,IAAInB,cAAckB,gBAAgB,EAAE;wBACzC,OAAOlB,cAAckB,gBAAgB,CAACtB,UAAU;oBAClD,OAAO;wBACL,OAAOQ,QAAQC,OAAO,CAACC;oBACzB;gBACF;oBACEN;YACJ;QACF;IACF;IAEA,yEAAyE;IACzE,8GAA8G;IAC9G,sDAAsD;IACtDhB,4BAA4Ba;AAC9B","ignoreList":[0]} |
@@ -7,3 +7,3 @@ import { areCookiesMutableInCurrentPhase, RequestCookiesAdapter } from '../web/spec-extension/adapters/request-cookies'; | ||
| import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'; | ||
| import { makeDevtoolsIOAwarePromise, makeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeRuntimeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'; | ||
@@ -134,3 +134,3 @@ import { isRequestApiAllowedInCurrentPhase } from './utils'; | ||
| } | ||
| const promise = makeHangingPromise(prerenderStore.renderSignal, workStore.route, '`cookies()`'); | ||
| const promise = makeRuntimeHangingPromise(prerenderStore.renderSignal, workStore.route, '`cookies()`', prerenderStore); | ||
| CachedCookies.set(prerenderStore, promise); | ||
@@ -137,0 +137,0 @@ return promise; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // We need track dynamic access here eagerly to keep continuity with\n // how cookies has worked in PPR without cacheComponents.\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`'\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["areCookiesMutableInCurrentPhase","RequestCookiesAdapter","RequestCookies","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","cookies","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","makeHangingCookies","exportName","dynamicTracking","stagedRendering","delayUntilStage","sessionData","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","seal","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SAEEA,+BAA+B,EAC/BC,qBAAqB,QAChB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,gCAA+B;AAC9D,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,0BAA0B,EAC1BC,kBAAkB,EAClBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYhB,iBAAiBiB,QAAQ;IAC3C,MAAMC,gBAAgBhB,qBAAqBe,QAAQ;IAEnD,IAAID,WAAW;QACb,IAAIE,iBAAiB,CAACP,kCAAkCO,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,UAAUK,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBC;YAC1B,OAAOC,qBAAqBF;QAC9B;QAEA,IAAIN,UAAUS,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAInB,sBACR,CAAC,MAAM,EAAEU,UAAUI,KAAK,CAAC,mNAAmN,CAAC,GADzO,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIF,eAAe;YACjB,OAAQA,cAAcQ,IAAI;gBACxB,KA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C9D;IACA,OAAO8B;AACT;AAEA,SAASiB,6BACPM,MAAe,EACfC,IAAY,EACZtD,KAAyB;IAEzB,OAAO;QACLuD,YAAY;QACZ1B;YACEU,kBAAkBvC,OAAO,CAAC,YAAY,EAAEsD,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACAxB,KAAIyB,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASf,8CACPQ,MAAe,EACfrD,KAAyB;IAEzB,OAAO;QACLuD,YAAY;QACZ1B;YACEU,kBAAkBvC,OAAO;YACzB,OAAOwD;QACT;QACAxB,KAAIyB,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPxC,KAAyB,EACzB6D,UAAkB;IAElB,MAAMC,SAAS9D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG+D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // We need track dynamic access here eagerly to keep continuity with\n // how cookies has worked in PPR without cacheComponents.\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["areCookiesMutableInCurrentPhase","RequestCookiesAdapter","RequestCookies","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","cookies","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","type","error","captureStackTrace","invalidDynamicUsageError","makeHangingCookies","exportName","dynamicTracking","stagedRendering","delayUntilStage","sessionData","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","seal","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable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ASiB,6BACPM,MAAe,EACfC,IAAY,EACZtD,KAAyB;IAEzB,OAAO;QACLuD,YAAY;QACZ1B;YACEU,kBAAkBvC,OAAO,CAAC,YAAY,EAAEsD,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACAxB,KAAIyB,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASf,8CACPQ,MAAe,EACfrD,KAAyB;IAEzB,OAAO;QACLuD,YAAY;QACZ1B;YACEU,kBAAkBvC,OAAO;YACzB,OAAOwD;QACT;QACAxB,KAAIyB,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPxC,KAAyB,EACzB6D,UAAkB;IAElB,MAAMC,SAAS9D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG+D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
@@ -6,3 +6,3 @@ import { HeadersAdapter } from '../web/spec-extension/adapters/headers'; | ||
| import { StaticGenBailoutError } from '../../client/components/static-generation-bailout'; | ||
| import { makeDevtoolsIOAwarePromise, makeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeRuntimeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'; | ||
@@ -148,3 +148,3 @@ import { isRequestApiAllowedInCurrentPhase } from './utils'; | ||
| } | ||
| const promise = makeHangingPromise(prerenderStore.renderSignal, workStore.route, '`headers()`'); | ||
| const promise = makeRuntimeHangingPromise(prerenderStore.renderSignal, workStore.route, '`headers()`', prerenderStore); | ||
| CachedHeaders.set(prerenderStore, promise); | ||
@@ -151,0 +151,0 @@ return promise; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // PPR Prerender (no cacheComponents)\n // We are prerendering with PPR. We need track dynamic access here eagerly\n // to keep continuity with how headers has worked in PPR without cacheComponents.\n // TODO consider switching the semantic to throw on property access instead\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`'\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["HeadersAdapter","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","headers","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingHeaders","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","invalidDynamicUsageError","dynamicShouldError","makeHangingHeaders","exportName","dynamicTracking","stagedRendering","delayUntilStage","sessionData","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SACEA,cAAc,QAET,yCAAwC;AAC/C,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,0BAA0B,EAC1BC,kBAAkB,EAClBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,cAAc,QAAQ,mCAAkC;AAEjE;;;;;;;;CAQC,GACD,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYhB,iBAAiBiB,QAAQ;IAC3C,MAAMC,gBAAgBhB,qBAAqBe,QAAQ;IAEnD,IAAID,WAAW;QACb,IAAIE,iBAAiB,CAACP,kCAAkCO,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIC,MACR,C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OAAO3B;QAClD8C,cAAcH,6BAA6BhB,SAAS,gBAAgB3B;QACpE+C,SAASJ,6BAA6BhB,SAAS,WAAW3B;QAC1DgD,MAAML,6BAA6BhB,SAAS,QAAQ3B;QACpDiD,QAAQN,6BAA6BhB,SAAS,UAAU3B;QACxDkD,SAASP,6BAA6BhB,SAAS,WAAW3B;IAC5D;IACA,OAAO2B;AACT;AAEA,SAASgB,6BACPQ,MAAe,EACfC,IAAY,EACZpD,KAAyB;IAEzB,OAAO;QACLqD,YAAY;QACZ3B;YACES,kBAAkBnC,OAAO,CAAC,YAAY,EAAEoD,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACAzB,KAAI0B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASjB,8CACPU,MAAe,EACfnD,KAAyB;IAEzB,OAAO;QACLqD,YAAY;QACZ3B;YACES,kBAAkBnC,OAAO;YACzB,OAAOsD;QACT;QACAzB,KAAI0B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQZ,OAAOC,QAAQ,EAAE;gBAC7Ce;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAAStB,yBACPpC,KAAyB,EACzB2D,UAAkB;IAElB,MAAMC,SAAS5D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG6D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // PPR Prerender (no cacheComponents)\n // We are prerendering with PPR. We need track dynamic access here eagerly\n // to keep continuity with how headers has worked in PPR without cacheComponents.\n // TODO consider switching the semantic to throw on property access instead\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["HeadersAdapter","workAsyncStorage","throwForMissingRequestStore","workUnitAsyncStorage","postponeWithTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","StaticGenBailoutError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","isRequestApiAllowedInCurrentPhase","applyOwnerStack","InvariantError","headers","callingExpression","workStore","getStore","workUnitStore","Error","route","forceStatic","underlyingHeaders","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","invalidDynamicUsageError","dynamicShouldError","makeHangingHeaders","exportName","dynamicTracking","stagedRendering","delayUntilStage","sessionData","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","proxiedPromise","warnForSyncAccess","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":"AAAA,SACEA,cAAc,QAET,yCAAwC;AAC/C,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,2BAA2B,EAC3BC,oBAAoB,QAGf,iDAAgD;AACvD,SACEC,oBAAoB,EACpBC,gCAAgC,EAChCC,+BAA+B,QAC1B,kCAAiC;AACxC,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,iCAAiC,QAAQ,UAAS;AAC3D,SAASC,eAAe,QAAQ,6BAA4B;AAC5D,SAASC,cAAc,QAAQ,mCAAkC;AAEjE;;;;;;;;CAQC,GACD,OAAO,SAASC;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYhB,iBAAiBiB,QAAQ;IAC3C,MAAMC,gBAAgBhB,qBAAqBe,QAAQ;IAEnD,IAAID,WAAW;QACb,IAAIE,iBAAiB,CAACP,kCAAkCO,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,UAAUK,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBvB,eAAewB,IAAI,CAAC,IAAIC,QAAQ,CAAC;YAC3D,OAAOC,qBAAqBH;QAC9B;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcQ,IAAI;gBACxB,KAAK;oBAAS;wBACZ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ACZ3B;YACES,kBAAkBnC,OAAO,CAAC,YAAY,EAAEoD,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACAzB,KAAI0B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASjB,8CACPU,MAAe,EACfnD,KAAyB;IAEzB,OAAO;QACLqD,YAAY;QACZ3B;YACES,kBAAkBnC,OAAO;YACzB,OAAOsD;QACT;QACAzB,KAAI0B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQZ,OAAOC,QAAQ,EAAE;gBAC7Ce;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAAStB,yBACPpC,KAAyB,EACzB2D,UAAkB;IAElB,MAAMC,SAAS5D,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG6D,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
| import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'; | ||
| import { makeHangingPromise, makeDevtoolsIOAwarePromise } from '../dynamic-rendering-utils'; | ||
| import { makeDynamicHangingPromise, makeDevtoolsIOAwarePromise } from '../dynamic-rendering-utils'; | ||
| import { RenderStage } from '../app-render/staged-rendering'; | ||
@@ -56,3 +56,3 @@ import { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'; | ||
| // anything after it by making it return a hanging promise. | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, '`io()`'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, '`io()`'); | ||
| case 'prerender-ppr': | ||
@@ -59,0 +59,0 @@ // Dead code to be removed when we eliminate legacy ppr code |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'prerender-ppr':\n // Dead code to be removed when we eliminate legacy ppr code\n throwPrerenderPPRRemovedError()\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","makeHangingPromise","makeDevtoolsIOAwarePromise","RenderStage","throwPrerenderPPRRemovedError","isRequestApiAllowedInCurrentPhase","resolvedIOPromise","Promise","resolve","undefined","status","value","io","workStore","getStore","workUnitStore","Error","route","type","process","env","NODE_ENV","asyncApiPromises","Dynamic","renderSignal"],"mappings":"AAAA,SA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UAAUI,KAAK,EACf;YAEJ,KAAK;gBACH,4DAA4D;gBAC5Db;gBACA;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,kDAAkD;YAClD,iEAAiE;YACjE,8CAA8C;YAC9C,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,iEAAiE;YACjE,sCAAsC;YACtC,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,4DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOE;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'prerender-ppr':\n // Dead code to be removed when we eliminate legacy ppr code\n throwPrerenderPPRRemovedError()\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["workAsyncStorage","workUnitAsyncStorage","makeDynamicHangingPromise","makeDevtoolsIOAwarePromise","RenderStage","throwPrerenderPPRRemovedError","isRequestApiAllowedInCurrentPhase","resolvedIOPromise","Promise","resolve","undefined","status","value","io","workStore","getStore","workUnitStore","Error","route","type","process","env","NODE_ENV","asyncApiPromises","Dynamic","renderSignal"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,4CAA2C;AAC5E,SAASC,oBAAoB,QAAQ,iDAAgD;AACrF,SACEC,yBAAyB,EACzBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,WAAW,QAAQ,iCAAgC;AAC5D,SAASC,6BAA6B,QAAQ,qCAAoC;AAClF,SAASC,iCAAiC,QAAQ,UAAS;AAE3D,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAMC,oBAAmCC,QAAQC,OAAO,CAACC;AACvDH,kBAA0BI,MAAM,GAAG;AACnCJ,kBAA0BK,KAAK,GAAGF;AAEpC;;;;;;;;;;CAUC,GACD,OAAO,SAASG;IACd,MAAMC,YAAYd,iBAAiBe,QAAQ;IAC3C,MAAMC,gBAAgBf,qBAAqBc,QAAQ;IAEnD,IAAID,aAAaE,eAAe;QAC9B,IAAIA,iBAAiB,CAACV,kCAAkCU,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,oLAAoL,CAAC,GAD1M,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QACA,OAAQF,cAAcG,IAAI;YACxB,KAAK;gBACH,kEAAkE;gBAClE,mEAAmE;gBACnE,6DAA6D;gBAC7D,uEAAuE;gBACvE,oEAAoE;gBACpE,kBAAkB;gBAClB,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;oBAC1C,IAAIN,cAAcO,gBAAgB,EAAE;wBAClC,OAAOP,cAAcO,gBAAgB,CAACV,EAAE;oBAC1C;oBACA,OAAOV,2BACLO,WACAM,eACAZ,YAAYoB,OAAO;gBAEvB,OAAO,IAAIR,cAAcO,gBAAgB,EAAE;oBACzC,OAAOP,cAAcO,gBAAgB,CAACV,EAAE;gBAC1C;gBACA,OAAON;YACT,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,wEAAwE;gBACxE,2DAA2D;gBAC3D,OAAOL,0BACLc,cAAcS,YAAY,EAC1BX,UAAUI,KAAK,EACf;YAEJ,KAAK;gBACH,4DAA4D;gBAC5Db;gBACA;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,kDAAkD;YAClD,iEAAiE;YACjE,8CAA8C;YAC9C,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,iEAAiE;YACjE,sCAAsC;YACtC,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,4DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOE;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]} |
@@ -8,3 +8,3 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { describeStringPropertyAccess, wellKnownProperties } from '../../shared/lib/utils/reflect-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeHangingPromise, makePromiseFromTrigger, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeFallbackParamsHangingPromise, makePromiseFromTrigger, trackFallbackParamsAccessed, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'; | ||
@@ -215,3 +215,3 @@ import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'; | ||
| // resolves. | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, '`params`'); | ||
| return makeFallbackParamsHangingPromise(workUnitStore.renderSignal, workStore.route, '`params`', workUnitStore); | ||
| } | ||
@@ -458,2 +458,10 @@ } | ||
| [prop]: (...args)=>{ | ||
| // Record against the store that's active at access time: the | ||
| // hanging promise is cached by params object across prerender | ||
| // stores, so the store that created it may not be the one that's | ||
| // rendering when it's finally awaited. | ||
| const workUnitStore = workUnitAsyncStorage.getStore(); | ||
| if (workUnitStore !== undefined) { | ||
| trackFallbackParamsAccessed(workUnitStore); | ||
| } | ||
| const store = dynamicAccessAsyncStorage.getStore(); | ||
@@ -479,3 +487,6 @@ if (store) { | ||
| } | ||
| const promise = new Proxy(makeHangingPromise(prerenderStore.renderSignal, workStore.route, '`params`'), fallbackParamsProxyHandler); | ||
| const promise = new Proxy(makeFallbackParamsHangingPromise(prerenderStore.renderSignal, workStore.route, '`params`', // This promise is created for every segment on a fallback route whether | ||
| // or not it reads params, so recording the access at creation would mark | ||
| // every render. The access is tracked in the proxy traps instead. | ||
| null), fallbackParamsProxyHandler); | ||
| CachedParams.set(underlyingParams, promise); | ||
@@ -482,0 +493,0 @@ return promise; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n makePromiseFromTrigger,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`'\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsSessionShell`.\n const staticParamsStage = workUnitStore.needsSessionShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`'\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["workAsyncStorage","createVaryingParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeHangingPromise","makePromiseFromTrigger","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","isEmptyParams","hasFallbackRouteParams","allParamsAreRootParams","createParamsFromClient","underlyingParams","workStore","getStore","workUnitStore","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","optionalCatchAllParamName","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","createRenderParamsForPage","createPrerenderParamsForClientSegment","fallbackRouteParams","key","has","renderSignal","route","Promise","resolve","prerenderStore","makeHangingParams","stagedRendering","rootParams","staticParamsStage","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsSessionShell","trigger","reject","then","catch","noop","displayName","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","args","store","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","defineProperty","expression","dynamicTracking","enumerable","hasFallbackParams","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createParamsAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAGlD,SACEC,mBAAmB,EACnBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,QACf,kCAAiC;AAExC,SACEC,oBAAoB,EAKpBC,6BAA6B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AG;IAC7C,OAAO,qBAIN,CAJM,IAAImD,MACT,GAAGqB,OAAO,KAAK,EAAEb,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsSessionShell`.\n const staticParamsStage = workUnitStore.needsSessionShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["workAsyncStorage","createVaryingParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","describeStringPropertyAccess","wellKnownProperties","makeDevtoolsIOAwarePromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","trackFallbackParamsAccessed","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","dynamicAccessAsyncStorage","isEmptyParams","hasFallbackRouteParams","allParamsAreRootParams","createParamsFromClient","underlyingParams","workStore","getStore","workUnitStore","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","createServerParamsForMetadata","optionalCatchAllParamName","metadataVaryParamsAccumulator","createServerParamsForServerSegment","createServerParamsForRoute","createRuntimePrerenderParams","createRenderParamsForPage","createPrerenderParamsForClientSegment","fallbackRouteParams","key","has","renderSignal","route","Promise","resolve","prerenderStore","makeHangingParams","stagedRendering","rootParams","staticParamsStage","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsSessionShell","trigger","reject","then","catch","noop","displayName","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","args","undefined","store","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","defineProperty","expression","dynamicTracking","enumerable","hasFallbackParams","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createParamsAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAGlD,SACEC,mBAAmB,EACnBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,QACf,kCAAiC;AAExC,SACEC,oBAAoB,EAKpBC,6BAA6B,QAIxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,4BAA4B,EAC5BC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,0BAA0B,EAC1BC,gCAAgC,EAChCC,sBAAsB,EACtBC,2BAA2B,EAC3BC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SAASC,yBAAyB,QAAQ,sDAAqD;AAC/F,SACEC,aAAa,EACbC,sBAAsB,EACtBC,sBAAsB,QACjB,sBAAqB;AAK5B,OAAO,SAASC,uBACd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AAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
| import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { postponeWithTracking } from '../app-render/dynamic-rendering'; | ||
| import { throwInvariantForMissingStore, workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'; | ||
| import { makeHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { makeDynamicHangingPromise, makeFallbackParamsHangingPromise, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { InvariantError } from '../../shared/lib/invariant-error'; | ||
@@ -59,3 +59,3 @@ export function createServerPathnameForMetadata(underlyingPathname) { | ||
| if (workUnitStore.isSessionShell) { | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, '`pathname`'); | ||
| return makeDynamicHangingPromise(workUnitStore.renderSignal, workStore.route, '`pathname`'); | ||
| } else { | ||
@@ -81,3 +81,6 @@ return createRenderPathname(underlyingPathname); | ||
| if (fallbackParams && fallbackParams.size > 0) { | ||
| return makeHangingPromise(prerenderStore.renderSignal, workStore.route, '`pathname`'); | ||
| // The pathname only hangs when there are fallback params, and a | ||
| // concrete (ISR-upgraded) prerender resolves it — so this access is | ||
| // fallback-param data for the static-prefetch hint. | ||
| return makeFallbackParamsHangingPromise(prerenderStore.renderSignal, workStore.route, '`pathname`', prerenderStore); | ||
| } | ||
@@ -84,0 +87,0 @@ break; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n postponeWithTracking,\n type DynamicTrackingState,\n} from '../app-render/dynamic-rendering'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeErroringPathname(workStore, prerenderStore.dynamicTracking)\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction makeErroringPathname<T>(\n workStore: WorkStore,\n dynamicTracking: null | DynamicTrackingState\n): Promise<T> {\n let reject: null | ((reason: unknown) => void) = null\n const promise = new Promise<T>((_, re) => {\n reject = re\n })\n\n const originalThen = promise.then.bind(promise)\n\n // We instrument .then so that we can generate a tracking event only if you actually\n // await this promise, not just that it is created.\n promise.then = (onfulfilled, onrejected) => {\n if (reject) {\n try {\n postponeWithTracking(\n workStore.route,\n 'metadata relative url resolving',\n dynamicTracking\n )\n } catch (error) {\n reject(error)\n reject = null\n }\n }\n return originalThen(onfulfilled, onrejected)\n }\n\n // We wrap in a noop proxy to trick the runtime into thinking it\n // isn't a native promise (it's not really). This is so that awaiting\n // the promise will call the `then` property triggering the lazy postpone\n return new Proxy(promise, {})\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["workAsyncStorage","postponeWithTracking","throwInvariantForMissingStore","workUnitAsyncStorage","makeHangingPromise","RENDER_STAGES_BY_DATA_KIND","InvariantError","createServerPathnameForMetadata","underlyingPathname","workStore","getStore","workUnitStore","type","createPrerenderPathname","stagedRendering","pathnameStage","runtimeLinkData","delayUntilStage","undefined","isSessionShell","renderSignal","route","createRenderPathname","prerenderStore","fallbackParams","fallbackRouteParams","size","makeErroringPathname","dynamicTracking","Promise","resolve","reject","promise","_","re","originalThen","then","bind","onfulfilled","onrejected","error","Proxy"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,oBAAoB,QAEf,kCAAiC;AAExC,SACEC,6BAA6B,EAC7BC,oBAAoB,QAIf,iDAAgD;AACvD,SACEC,kBAAkB,EAClBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYT,iBAAiBU,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIH,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMK,gBAAgBR,qBAAqBO,QAAQ;IACnD,IAAIC,eAAe;QACjB,OAAQA,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLL,oBACAC,WACAE;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIL,eACR,6EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,eACR,4EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,eACR,sFADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBAAqB;oBACxB,iEAAiE;oBACjE,kDAAkD;oBAClD,4CAA4C;oBAC5C,sEAAsE;oBACtE,oDAAoD;oBACpD,iEAAiE;oBACjE,MAAM,EAAEQ,eAAe,EAAE,GAAGH;oBAC5B,IAAIG,iBAAiB;wBACnB,MAAMC,gBAAgBV,2BAA2BW,eAAe;wBAChE,OAAOF,gBAAgBG,eAAe,CACpCF,eACAG,WACAV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AAqE;IACrE,yEAAyE;IACzE,OAAO,IAAIE,MAAMT,SAAS,CAAC;AAC7B;AAEA,SAASV,qBAAqBd,kBAA0B;IACtD,OAAOqB,QAAQC,OAAO,CAACtB;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n postponeWithTracking,\n type DynamicTrackingState,\n} from '../app-render/dynamic-rendering'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeDynamicHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname only hangs when there are fallback params, and a\n // concrete (ISR-upgraded) prerender resolves it — so this access is\n // fallback-param data for the static-prefetch hint.\n return makeFallbackParamsHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeErroringPathname(workStore, prerenderStore.dynamicTracking)\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction makeErroringPathname<T>(\n workStore: WorkStore,\n dynamicTracking: null | DynamicTrackingState\n): Promise<T> {\n let reject: null | ((reason: unknown) => void) = null\n const promise = new Promise<T>((_, re) => {\n reject = re\n })\n\n const originalThen = promise.then.bind(promise)\n\n // We instrument .then so that we can generate a tracking event only if you actually\n // await this promise, not just that it is created.\n promise.then = (onfulfilled, onrejected) => {\n if (reject) {\n try {\n postponeWithTracking(\n workStore.route,\n 'metadata relative url resolving',\n dynamicTracking\n )\n } catch (error) {\n reject(error)\n reject = null\n }\n }\n return originalThen(onfulfilled, onrejected)\n }\n\n // We wrap in a noop proxy to trick the runtime into thinking it\n // isn't a native promise (it's not really). This is so that awaiting\n // the promise will call the `then` property triggering the lazy postpone\n return new Proxy(promise, {})\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["workAsyncStorage","postponeWithTracking","throwInvariantForMissingStore","workUnitAsyncStorage","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","RENDER_STAGES_BY_DATA_KIND","InvariantError","createServerPathnameForMetadata","underlyingPathname","workStore","getStore","workUnitStore","type","createPrerenderPathname","stagedRendering","pathnameStage","runtimeLinkData","delayUntilStage","undefined","isSessionShell","renderSignal","route","createRenderPathname","prerenderStore","fallbackParams","fallbackRouteParams","size","makeErroringPathname","dynamicTracking","Promise","resolve","reject","promise","_","re","originalThen","then","bind","onfulfilled","onrejected","error","Proxy"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,oBAAoB,QAEf,kCAAiC;AAExC,SACEC,6BAA6B,EAC7BC,oBAAoB,QAIf,iDAAgD;AACvD,SACEC,yBAAyB,EACzBC,gCAAgC,EAChCC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,cAAc,QAAQ,mCAAkC;AAEjE,OAAO,SAASC,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYV,iBAAiBW,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIH,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMK,gBAAgBT,qBAAqBQ,QAAQ;IACnD,IAAIC,eAAe;QACjB,OAAQA,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLL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mB;gBACzD,IAAID,kBAAkBA,eAAeE,IAAI,GAAG,GAAG;oBAC7C,OAAOC,qBAAqBlB,WAAWc,eAAeK,eAAe;gBACvE;gBACA;YACF;QACA,KAAK;YACH;QACF;YACEL;IACJ;IAEA,qFAAqF;IACrF,OAAOM,QAAQC,OAAO,CAACtB;AACzB;AAEA,SAASmB,qBACPlB,SAAoB,EACpBmB,eAA4C;IAE5C,IAAIG,SAA6C;IACjD,MAAMC,UAAU,IAAIH,QAAW,CAACI,GAAGC;QACjCH,SAASG;IACX;IAEA,MAAMC,eAAeH,QAAQI,IAAI,CAACC,IAAI,CAACL;IAEvC,oFAAoF;IACpF,mDAAmD;IACnDA,QAAQI,IAAI,GAAG,CAACE,aAAaC;QAC3B,IAAIR,QAAQ;YACV,IAAI;gBACF/B,qBACES,UAAUY,KAAK,EACf,mCACAO;YAEJ,EAAE,OAAOY,OAAO;gBACdT,OAAOS;gBACPT,SAAS;YACX;QACF;QACA,OAAOI,aAAaG,aAAaC;IACnC;IAEA,gEAAgE;IAChE,qEAAqE;IACrE,yEAAyE;IACzE,OAAO,IAAIE,MAAMT,SAAS,CAAC;AAC7B;AAEA,SAASV,qBAAqBd,kBAA0B;IACtD,OAAOqB,QAAQC,OAAO,CAACtB;AACzB","ignoreList":[0]} |
@@ -5,3 +5,3 @@ import { InvariantError } from '../../shared/lib/invariant-error'; | ||
| import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'; | ||
| import { makeHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'; | ||
| import { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'; | ||
@@ -148,3 +148,3 @@ import { actionAsyncStorage } from '../app-render/action-async-storage.external'; | ||
| if (prerenderStore.fallbackRouteParams && prerenderStore.fallbackRouteParams.has(paramName)) { | ||
| return makeHangingPromise(prerenderStore.renderSignal, workStore.route, apiName); | ||
| return makeFallbackParamsHangingPromise(prerenderStore.renderSignal, workStore.route, apiName, prerenderStore); | ||
| } | ||
@@ -151,0 +151,0 @@ break; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStorePPR\n | PrerenderStoreLegacy\n | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-ppr':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName\n )\n }\n break\n }\n case 'prerender-ppr': {\n // We aren't in a cacheComponents prerender, but the param is a fallback,\n // so we need to make an erroring params object which will postpone/error if you access it\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeErroringRootParamPromise(\n paramName,\n workStore,\n prerenderStore,\n apiName\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n\n/** Deliberately async -- we want to create a rejected promise, not error synchronously. */\nasync function makeErroringRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,\n apiName: string\n): Promise<ParamValue> {\n const expression = describeStringPropertyAccess(apiName, paramName)\n // In most dynamic APIs, we also throw if `dynamic = \"error\"`.\n // However, root params are only dynamic when we're generating a fallback shell,\n // and even with `dynamic = \"error\"` we still support generating dynamic fallback shells.\n // TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = \"error\"`\n switch (prerenderStore.type) {\n case 'prerender-ppr': {\n return postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n }\n case 'prerender-legacy': {\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n default: {\n prerenderStore satisfies never\n }\n }\n}\n"],"names":["InvariantError","postponeWithTracking","throwToInterruptStaticGeneration","workAsyncStorage","workUnitAsyncStorage","makeHangingPromise","describeStringPropertyAccess","actionAsyncStorage","accumulateRootVaryParam","getRootParam","paramName","apiName","workStore","getStore","workUnitStore","Error","route","actionStore","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","prerenderStore","underlyingParams","fallbackRouteParams","has","renderSignal","makeErroringRootParamPromise","expression","dynamicTracking"],"mappings":"AAAA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SACEC,oBAAoB,EACpBC,gCAAgC,QAC3B,kCAAiC;AACxC,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,oBAAoB,QAIf,iDAAgD;AACvD,SAASC,kBAAkB,QAAQ,6BAA4B;AAE/D,SAASC,4BAA4B,QAAQ,uCAAsC;AACnF,SAASC,kBAAkB,QAAQ,8CAA6C;AAChF,SAASC,uBAAuB,QAAQ,4BAA2B;AAEnE;;;CAGC,GACD,OAAO,SAASC,aAAaC,SAAiB;IAC5C,MAAMC,UAAU,CAAC,6BAA6B,EAAED,UAAU,IAAI,CAAC;IAE/D,MAAME,YAAYT,iBAAiBU,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAAqD,CAArD,IAAIZ,eAAe,CAAC,qBAAqB,EAAEW,SAAS,GAApD,qBAAA;mBAAA;wBAAA;0BAAA;QAAoD;IAC5D;IAEA,MAAMG,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAI,CAACC,eAAe;QAClB,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK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AAK;YAAa;gBAChB,yCAAyC;gBACzC,+DAA+D;gBAC/D,IACEgB,eAAeE,mBAAmB,IAClCF,eAAeE,mBAAmB,CAACC,GAAG,CAAC9B,YACvC;oBACA,OAAOL,mBACLgC,eAAeI,YAAY,EAC3B7B,UAAUI,KAAK,EACfL;gBAEJ;gBACA;YACF;QACA,KAAK;YAAiB;gBACpB,yEAAyE;gBACzE,0FAA0F;gBAC1F,IACE0B,eAAeE,mBAAmB,IAClCF,eAAeE,mBAAmB,CAACC,GAAG,CAAC9B,YACvC;oBACA,OAAOgC,6BACLhC,WACAE,WACAyB,gBACA1B;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBAEvB;YACF;QACA;YAAS;gBACP0B;YACF;IACF;IAEA,uFAAuF;IACvF7B,wBAAwBE;IACxB,OAAOe,QAAQC,OAAO,CAACY,gBAAgB,CAAC5B,UAAU;AACpD;AAEA,yFAAyF,GACzF,eAAegC,6BACbhC,SAAiB,EACjBE,SAAoB,EACpByB,cAAwD,EACxD1B,OAAe;IAEf,MAAMgC,aAAarC,6BAA6BK,SAASD;IACzD,8DAA8D;IAC9D,gFAAgF;IAChF,yFAAyF;IACzF,2GAA2G;IAC3G,OAAQ2B,eAAehB,IAAI;QACzB,KAAK;YAAiB;gBACpB,OAAOpB,qBACLW,UAAUI,KAAK,EACf2B,YACAN,eAAeO,eAAe;YAElC;QACA,KAAK;YAAoB;gBACvB,OAAO1C,iCACLyC,YACA/B,WACAyB;YAEJ;QACA;YAAS;gBACPA;YACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStorePPR\n | PrerenderStoreLegacy\n | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-ppr':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n // We aren't in a cacheComponents prerender, but the param is a fallback,\n // so we need to make an erroring params object which will postpone/error if you access it\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeErroringRootParamPromise(\n paramName,\n workStore,\n prerenderStore,\n apiName\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n\n/** Deliberately async -- we want to create a rejected promise, not error synchronously. */\nasync function makeErroringRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,\n apiName: string\n): Promise<ParamValue> {\n const expression = describeStringPropertyAccess(apiName, paramName)\n // In most dynamic APIs, we also throw if `dynamic = \"error\"`.\n // However, root params are only dynamic when we're generating a fallback shell,\n // and even with `dynamic = \"error\"` we still support generating dynamic fallback shells.\n // TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = \"error\"`\n switch (prerenderStore.type) {\n case 'prerender-ppr': {\n return postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n }\n case 'prerender-legacy': {\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n default: {\n prerenderStore satisfies never\n }\n }\n}\n"],"names":["InvariantError","postponeWithTracking","throwToInterruptStaticGeneration","workAsyncStorage","workUnitAsyncStorage","makeFallbackParamsHangingPromise","describeStringPropertyAccess","actionAsyncStorage","accumulateRootVaryParam","getRootParam","paramName","apiName","workStore","getStore","workUnitStore","Error","route","actionStore","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","prerenderStore","underlyingParams","fallbackRouteParams","has","renderSignal","makeErroringRootParamPromise","expression","dynamicTracking"],"mappings":"AAAA,SAASA,cAAc,QAAQ,mCAAkC;AACjE,SACEC,oBAAoB,EACpBC,gCAAgC,QAC3B,kCAAiC;AACxC,SACEC,gBAAgB,QAEX,4CAA2C;AAClD,SACEC,oBAAoB,QAIf,iDAAgD;AACvD,SAASC,gCAAgC,QAAQ,6BAA4B;AAE7E,SAASC,4BAA4B,QAAQ,uCAAsC;AACnF,SAASC,kBAAkB,QAAQ,8CAA6C;AAChF,SAASC,uBAAuB,QAAQ,4BAA2B;AAEnE;;;CAGC,GACD,OAAO,SAASC,aAAaC,SAAiB;IAC5C,MAAMC,UAAU,CAAC,6BAA6B,EAAED,UAAU,IAAI,CAAC;IAE/D,MAAME,YAAYT,iBAAiBU,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAAqD,CAArD,IAAIZ,eAAe,CAAC,qBAAqB,EAAEW,SAAS,GAApD,qBAAA;mBAAA;wBAAA;0BAAA;QAAoD;IAC5D;IAEA,MAAMG,gBAAgBV,qBAAqBS,QAAQ;IACnD,IAAI,CAACC,eAAe;QAClB,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,MAAM,EAAEL,QAAQ,oDAAoD,CAAC,GAD1F,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMM,cAAcV,mBAAmBM,QAAQ;IAC/C,IAAII,aAAa;QACf,IAAIA,YAAYC,UAAU,EAAE;YAC1B,oDAAoD;YACpD,MAAM,qBAEL,CAFK,IAAIH,MACR,CAAC,MAAM,EAAEH,UAAUI,KAAK,CAAC,MAAM,EAAEL,QAAQ,2GAA2G,CAAC,GADjJ,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AmB,CAACC,GAAG,CAAC9B,YACvC;oBACA,OAAOgC,6BACLhC,WACAE,WACAyB,gBACA1B;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBAEvB;YACF;QACA;YAAS;gBACP0B;YACF;IACF;IAEA,uFAAuF;IACvF7B,wBAAwBE;IACxB,OAAOe,QAAQC,OAAO,CAACY,gBAAgB,CAAC5B,UAAU;AACpD;AAEA,yFAAyF,GACzF,eAAegC,6BACbhC,SAAiB,EACjBE,SAAoB,EACpByB,cAAwD,EACxD1B,OAAe;IAEf,MAAMgC,aAAarC,6BAA6BK,SAASD;IACzD,8DAA8D;IAC9D,gFAAgF;IAChF,yFAAyF;IACzF,2GAA2G;IAC3G,OAAQ2B,eAAehB,IAAI;QACzB,KAAK;YAAiB;gBACpB,OAAOpB,qBACLW,UAAUI,KAAK,EACf2B,YACAN,eAAeO,eAAe;YAElC;QACA,KAAK;YAAoB;gBACvB,OAAO1C,iCACLyC,YACA/B,WACAyB;YAEJ;QACA;YAAS;gBACPA;YACF;IACF;AACF","ignoreList":[0]} |
@@ -8,3 +8,3 @@ import { workAsyncStorage } from '../app-render/work-async-storage.external'; | ||
| import { InvariantError } from '../../shared/lib/invariant-error'; | ||
| import { makeDevtoolsIOAwarePromise, makeHangingPromise, makePromiseFromTrigger, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { makeDevtoolsIOAwarePromise, makeRuntimeHangingPromise, makePromiseFromTrigger, trackRuntimeDataAccessed, RENDER_STAGES_BY_DATA_KIND } from '../dynamic-rendering-utils'; | ||
| import { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'; | ||
@@ -138,3 +138,3 @@ import { describeStringPropertyAccess, describeHasCheckingStringProperty, wellKnownProperties } from '../../shared/lib/utils/reflect-utils'; | ||
| // the promise to ensure the RSC side is considered dynamic | ||
| return makeHangingPromise(workUnitStore.renderSignal, workStore.route, '`searchParams`'); | ||
| return makeRuntimeHangingPromise(workUnitStore.renderSignal, workStore.route, '`searchParams`', workUnitStore); | ||
| case 'validation-client': | ||
@@ -274,3 +274,13 @@ throw Object.defineProperty(new InvariantError('createPrerenderSearchParamsForClientPage should not be called in a client validation.'), "__NEXT_ERROR_CODE", { | ||
| } | ||
| const promise = makeHangingPromise(prerenderStore.renderSignal, workStore.route, '`searchParams`'); | ||
| const promise = makeRuntimeHangingPromise(prerenderStore.renderSignal, workStore.route, '`searchParams`', // This promise is created for every page whether or not it reads search | ||
| // params, so recording the access at creation would mark every render. | ||
| // The access is tracked in the proxy traps below instead. | ||
| null); | ||
| const trackSearchParamsAccessed = ()=>{ | ||
| // Record against the store that's active at access time: the promise is | ||
| // created while the RSC payload is constructed, but typically accessed | ||
| // later, during the render, under a different store. | ||
| const workUnitStore = workUnitAsyncStorage.getStore(); | ||
| trackRuntimeDataAccessed(workUnitStore ?? prerenderStore); | ||
| }; | ||
| const proxyHandler = { | ||
@@ -293,2 +303,3 @@ get (target, prop, receiver) { | ||
| const expression = '`await searchParams`, `searchParams.then`, or similar'; | ||
| trackSearchParamsAccessed(); | ||
| annotateDynamicAccess(expression, prerenderStore); | ||
@@ -318,2 +329,3 @@ // Mirror `makeHangingParams`: when this never-resolving promise | ||
| const expression = '`use(searchParams)`, `searchParams.status`, or similar'; | ||
| trackSearchParamsAccessed(); | ||
| annotateDynamicAccess(expression, prerenderStore); | ||
@@ -320,0 +332,0 @@ return ReflectAdapter.get(target, prop, receiver); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStorePPR,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n makePromiseFromTrigger,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`'\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`'\n )\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["workAsyncStorage","createVaryingSearchParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","annotateDynamicAccess","dynamicAccessAsyncStorage","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","makeDevtoolsIOAwarePromise","makeHangingPromise","makePromiseFromTrigger","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","describeStringPropertyAccess","describeHasCheckingStringProperty","wellKnownProperties","throwWithStaticGenerationBailoutErrorWithDynamicError","throwForSearchParamsAccessInUseCache","createSearchParamsFromClient","underlyingSearchParams","workStore","getStore","workUnitStore","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","createServerSearchParamsForMetadata","metadataVaryParamsAccumulator","createServerSearchParamsForServerPage","varyParamsAccumulator","createRuntimePrerenderSearchParams","createPrerenderSearchParamsForClientPage","forceStatic","Promise","resolve","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","proxyHandler","target","prop","receiver","hasOwn","originalMethod","args","expression","dynamicAccessStore","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","dynamicTracking","makeErroringSearchParamsForUseCache","has","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createSearchAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,EACpBC,qBAAqB,QAChB,kCAAiC;AACxC,SAASC,yBAAyB,QAAQ,sDAAqD;AAE/F,SACEC,oBAAoB,EAMpBC,6BAA6B,QAGxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,kBAAkB,EAClBC,sBAAsB,EACtBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SACEC,4BAA4B,EAC5BC,iCAAiC,EACjCC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,qDAAqD,EACrDC,oCAAoC,QAC/B,UAAS;AAIhB,OAAO,SAASC,6BACdC,sBAAoC;IAEpC,MAAMC,YAAYvB,iBAAiBwB,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIb,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMe,gBAAgBjB,qBAAqBgB,QAAQ;IACnD,IAAIC,eAAe;QACjB,OAAQA,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOC,kCAAkCJ,WAAWE;YACtD,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIf,eACR,8EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,eACR,yEADI,qBA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QAC7B;QACAwB,SAAQzB,MAAM;YACZ,MAAMM,aAAa;YACnBuB,kBAAkBzF,UAAUmB,KAAK,EAAE+C;YACnC,OAAOkB,QAAQC,OAAO,CAACzB;QACzB;IACF;AACF;AAEA,MAAM6B,oBAAoBjG,4CACxBoG;AAGF,SAASA,wBACPzE,KAAyB,EACzB+C,UAAkB;IAElB,MAAM2B,SAAS1E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAImD,MACT,GAAGuB,OAAO,KAAK,EAAE3B,WAAW,EAAE,CAAC,GAC7B,CAAC,uHAAuH,CAAC,GACzH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF;AAEA,SAAS5D,qCACPP,sBAAoC,EACpCC,SAAoB,EACpBE,aAAoC;QAKtBA;IAHd,MAAM,EAAE6C,iCAAiC,EAAE,GACzCC,QAAQ;IACV,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAAClD,EAAAA,mCAAAA,cAAcG,iBAAiB,qBAA/BH,iCAAiCmD,YAAY,KAAI,CAAC;IAEhEtD,yBAAyBgD,kCACvBhD,wBACAkD,cACAjD,UAAUmB,KAAK;IAEjB,OAAOH,QAAQC,OAAO,CAAClB;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStorePPR,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n makePromiseFromTrigger,\n trackRuntimeDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeRuntimeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeRuntimeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // This promise is created for every page whether or not it reads search\n // params, so recording the access at creation would mark every render.\n // The access is tracked in the proxy traps below instead.\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)\n }\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["workAsyncStorage","createVaryingSearchParams","getMetadataVaryParamsAccumulator","ReflectAdapter","throwToInterruptStaticGeneration","postponeWithTracking","annotateDynamicAccess","dynamicAccessAsyncStorage","workUnitAsyncStorage","throwInvariantForMissingStore","InvariantError","makeDevtoolsIOAwarePromise","makeRuntimeHangingPromise","makePromiseFromTrigger","trackRuntimeDataAccessed","RENDER_STAGES_BY_DATA_KIND","createDedupedByCallsiteServerErrorLoggerDev","describeStringPropertyAccess","describeHasCheckingStringProperty","wellKnownProperties","throwWithStaticGenerationBailoutErrorWithDynamicError","throwForSearchParamsAccessInUseCache","createSearchParamsFromClient","underlyingSearchParams","workStore","getStore","workUnitStore","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","createServerSearchParamsForMetadata","metadataVaryParamsAccumulator","createServerSearchParamsForServerPage","varyParamsAccumulator","createRuntimePrerenderSearchParams","createPrerenderSearchParamsForClientPage","forceStatic","Promise","resolve","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","proxyHandler","target","prop","receiver","hasOwn","originalMethod","args","expression","dynamicAccessStore","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","dynamicTracking","makeErroringSearchParamsForUseCache","has","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createSearchAccessError","prefix"],"mappings":"AAAA,SACEA,gBAAgB,QAEX,4CAA2C;AAElD,SACEC,yBAAyB,EACzBC,gCAAgC,QAC3B,4BAA2B;AAElC,SAASC,cAAc,QAAQ,yCAAwC;AACvE,SACEC,gCAAgC,EAChCC,oBAAoB,EACpBC,qBAAqB,QAChB,kCAAiC;AACxC,SAASC,yBAAyB,QAAQ,sDAAqD;AAE/F,SACEC,oBAAoB,EAMpBC,6BAA6B,QAGxB,iDAAgD;AACvD,SAASC,cAAc,QAAQ,mCAAkC;AACjE,SACEC,0BAA0B,EAC1BC,yBAAyB,EACzBC,sBAAsB,EACtBC,wBAAwB,EACxBC,0BAA0B,QACrB,6BAA4B;AACnC,SAASC,2CAA2C,QAAQ,oDAAmD;AAC/G,SACEC,4BAA4B,EAC5BC,iCAAiC,EACjCC,mBAAmB,QACd,uCAAsC;AAC7C,SACEC,qDAAqD,EACrDC,oCAAoC,QAC/B,UAAS;AAIhB,OAAO,SAASC,6BACdC,sBAAoC;IAEpC,MAAMC,YAAYxB,iBAAiByB,QAAQ;IAC3C,IAAI,CAACD,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAId,eAAe,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMgB,gBAAgBlB,qBAAqBiB,QAAQ;IACnD,IAAIC,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vBhD,wBACAkD,cACAjD,UAAUmB,KAAK;IAEjB,OAAOH,QAAQC,OAAO,CAAClB;AACzB","ignoreList":[0]} |
@@ -245,3 +245,6 @@ import { RouteModule } from '../route-module'; | ||
| hmrRefreshHash: undefined, | ||
| varyParamsAccumulator: null | ||
| varyParamsAccumulator: null, | ||
| runtimeDataAccessed: null, | ||
| shouldAttemptStaticPrefetch: null, | ||
| isFallbackUpgradeable: false | ||
| }; | ||
@@ -319,3 +322,6 @@ let prospectiveResult; | ||
| hmrRefreshHash: undefined, | ||
| varyParamsAccumulator: null | ||
| varyParamsAccumulator: null, | ||
| runtimeDataAccessed: null, | ||
| shouldAttemptStaticPrefetch: null, | ||
| isFallbackUpgradeable: false | ||
| }; | ||
@@ -322,0 +328,0 @@ let responseHandled = false; |
@@ -63,2 +63,24 @@ /** | ||
| PrefetchHint[PrefetchHint["SubtreeHasInstantFalse"] = 8192] = "SubtreeHasInstantFalse"; | ||
| // The client should attempt a static prefetch for this route: the | ||
| // build-time prerender did not access any runtime data (cookies, headers, | ||
| // searchParams, ...), so a static prefetch is expected to be as complete | ||
| // as a runtime one. A fallback-param access only unsets the bit when the | ||
| // route can never be upgraded from a fallback to a concrete prerender — | ||
| // on an upgradeable route, ISR later produces the concrete prerender a | ||
| // static attempt would hit (until then, the static responses' own | ||
| // signal reports the insufficiency per response). Purely advisory, and | ||
| // both error directions are safe: if set when a runtime request is | ||
| // actually needed, that same response-level signal (the load-bearing | ||
| // `needsRuntimeRequest` promise combined with each segment's `isPartial`) | ||
| // directs the client to follow up — the cost is a wasted static attempt. | ||
| // If unset when static would have sufficed, the client goes straight to a | ||
| // runtime prefetch, which is a superset of the static response — the cost | ||
| // is only reduced cacheability. Like the other bits, this one is computed | ||
| // once per build and stays constant for the build's lifetime; it rides | ||
| // the prefetch-hints manifest into every response that carries hints — | ||
| // `/_tree` prefetch responses and the FlightRouterState of dynamic | ||
| // navigations alike. (Routes missing from the manifest — see the #91407 | ||
| // fallbacks — simply never carry it.) Set on every node of the tree, but | ||
| // does not propagate. | ||
| PrefetchHint[PrefetchHint["ShouldAttemptStaticPrefetch"] = 16384] = "ShouldAttemptStaticPrefetch"; | ||
| return PrefetchHint; | ||
@@ -65,0 +87,0 @@ }({}); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/shared/lib/app-router-types.ts"],"sourcesContent":["/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type { VaryParamsIterable } from './segment-cache/vary-params-decoding'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Cache node used in app-router / layout-router.\n */\n\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n prefetchHead: HeadData | null\n\n head: HeadData\n\n slots: Record<string, CacheNode> | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n\n /**\n * Globally-unique identifier minted from a monotonic counter when the\n * CacheNode is freshly created. Surfaced to user code as a string via\n * `useRouter().bfcacheId` and intended to be used as a React `key` to\n * opt out of Activity-based state preservation on fresh navigations.\n *\n * Preserved when the CacheNode is reused (shared layouts, refresh,\n * search/hash-only navigations) or restored from the BFCache during a\n * back/forward navigation.\n */\n bfcacheId: number\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and runtime prefetch\n * hints. Only set when non-zero.\n */\n prefetchHints?: number,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // This segment has a runtime prefetch enabled (via instant with\n // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.\n HasRuntimePrefetch = 0b00001,\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when a\n // truthy instant config is present, or `prefetch` is 'partial',\n // 'unstable_eager', or 'allow-runtime'. Propagates upward so the root segment\n // reflects the entire subtree.\n SubtreeHasPartialPrefetching = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n IsRootLayoutOrAbove = 0b10000,\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n ParentInlinedIntoSelf = 0b100000,\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // at the end of its SegmentPrefetch[] array.\n HeadInlinedIntoSelf = 0b10000000,\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n HeadOutlined = 0b100000000,\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n InliningHintsStale = 0b1000000000,\n // This segment has instant = false, opting out of all\n // prefetching entirely (neither static nor runtime).\n PrefetchDisabled = 0b10000000000,\n // This segment or one of its descendants has runtime prefetch enabled\n // (HasRuntimePrefetch). Propagates upward so the root reflects the\n // entire subtree.\n SubtreeHasRuntimePrefetch = 0b100000000000,\n // This segment or one of its descendants prefetches \"eagerly\" — i.e. its\n // effective prefetch strategy is anything other than 'partial' or\n // 'allow-runtime'. Used by App Shells: a non-eager subtree relies on the\n // shared app shell and skips its Speculative prefetch. Propagates upward so\n // the root reflects the entire subtree.\n SubtreeHasEagerPrefetch = 0b1000000000000,\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n SubtreeHasInstantFalse = 0b10000000000000,\n}\n\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped. Matches\n * if EITHER bit is set — i.e. the segment uses runtime prefetching\n * (HasRuntimePrefetch) OR prefetching is disabled entirely (PrefetchDisabled,\n * e.g. instant = false). The segment participates in the bundle chain\n * but with null data.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */\nexport const StaticPrefetchDisabled =\n PrefetchHint.HasRuntimePrefetch | PrefetchHint.PrefetchDisabled\n\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */\nexport const SubtreePrefetchHints =\n PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasLoadingBoundary |\n PrefetchHint.SubtreeHasRuntimePrefetch |\n PrefetchHint.SubtreeHasInstantFalse |\n PrefetchHint.SubtreeHasEagerPrefetch\n\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading boundary,\n * or it has a runtime prefetch) becomes the corresponding \"subtree\" flag on the\n * parent, so the root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a prefetch tree (createFlightRouterStateFromLoaderTree) and on the client when\n * merging a navigation patch into the existing tree (convertServerPatchToFullTree).\n * Keep these in sync by routing both through this helper.\n */\nexport function propagateSubtreeBits(\n parentHints: number,\n childHints: number\n): number {\n if (childHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n parentHints |= PrefetchHint.SubtreeHasPartialPrefetching\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (\n childHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)\n ) {\n parentHints |= PrefetchHint.SubtreeHasLoadingBoundary\n }\n // Likewise for runtime prefetch.\n if (\n childHints &\n (PrefetchHint.HasRuntimePrefetch | PrefetchHint.SubtreeHasRuntimePrefetch)\n ) {\n parentHints |= PrefetchHint.SubtreeHasRuntimePrefetch\n }\n // And for eager prefetch. The bit is set directly on each eager segment, so\n // there's no separate segment-local flag — propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasEagerPrefetch) {\n parentHints |= PrefetchHint.SubtreeHasEagerPrefetch\n }\n // And for `instant = false`. Like eager prefetch, the bit is set directly on\n // each opted-out segment, so propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasInstantFalse) {\n parentHints |= PrefetchHint.SubtreeHasInstantFalse\n }\n return parentHints\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n // TODO: This field is no longer used. Remove it.\n loading: null,\n isPartial: boolean,\n /**\n * An AsyncIterable that yields the route params this segment accessed during\n * server rendering (one name per yield, deduped). Used by the client router\n * to determine cache key specificity - segments that only access certain\n * params can be reused across navigations where unaccessed params change.\n *\n * Does NOT include root params; those are emitted once at the top level of\n * the response (see `r` on the payload) and unioned in by the consumer.\n *\n * - null: tracking was not enabled for this render (e.g., not a prerender).\n * Treat conservatively - assume all params vary.\n * - Drains to empty Set: segment accesses no params (e.g., client components,\n * or server components that don't read params). Can be shared across all\n * param values.\n * - Drains to non-empty Set: segment depends on those params. Can only reuse\n * when those specific params match.\n */\n varyParams: VaryParamsIterable | null,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array<FlightDataPath> | string\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record<string, PrefetchHints> | null\n}\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * headVaryParams - vary params for the head (metadata) of the response.\n * Does not include root params (see `r`).\n */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params, rather than the server folding them into each set.\n */\n r?: VaryParamsIterable\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** supportsPerSegmentPrefetching */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** staleTime - Only present in dynamic runtime prefetch responses. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /**\n * shellUsedSessionData - true if resolving session data\n * unblocked new content in the shell.\n * NOTE: only use this in runtime/session prefetch requests\n * where we have a proper session shell.\n * */\n u?: Promise<boolean>\n /** headVaryParams. Does not include root params (see `r`). */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params.\n */\n r?: VaryParamsIterable\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n\nexport type InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n"],"names":["PrefetchHint","StaticPrefetchDisabled","SubtreePrefetchHints","propagateSubtreeBits","parentHints","childHints"],"mappings":"AAAA;;;;;CAKC,GAiLD,OAAO,IAAA,AAAWA,sCAAAA;IAChB,gEAAgE;IAChE,2EAA2E;;IAE3E,6EAA6E;IAC7E,wEAAwE;IACxE,gEAAgE;IAChE,8EAA8E;IAC9E,+BAA+B;;IAE/B,kDAAkD;;IAElD,sEAAsE;IACtE,6DAA6D;;IAE7D,8EAA8E;IAC9E,2EAA2E;IAC3E,8BAA8B;;IAE9B,sEAAsE;IACtE,0DAA0D;;IAE1D,wEAAwE;IACxE,yEAAyE;;IAEzE,4EAA4E;IAC5E,6CAA6C;;IAE7C,wEAAwE;IACxE,4EAA4E;;IAE5E,oEAAoE;IACpE,0EAA0E;IAC1E,0EAA0E;IAC1E,kEAAkE;IAClE,0EAA0E;IAC1E,oBAAoB;;IAEpB,sDAAsD;IACtD,qDAAqD;;IAErD,sEAAsE;IACtE,mEAAmE;IACnE,kBAAkB;;IAElB,yEAAyE;IACzE,kEAAkE;IAClE,yEAAyE;IACzE,4EAA4E;IAC5E,wCAAwC;;IAExC,oEAAoE;IACpE,8EAA8E;IAC9E,kEAAkE;IAClE,+EAA+E;IAC/E,mCAAmC;;WAvDnBA;MAyDjB;AAED;;;;;;;;CAQC,GACD,OAAO,MAAMC,yBACXD,SAA+D;AAEjE;;;;;CAKC,GACD,OAAO,MAAME,uBACXF,2BAIoC;AAEtC;;;;;;;;;;CAUC,GACD,OAAO,SAASG,qBACdC,WAAmB,EACnBC,UAAkB;IAElB,IAAIA,gBAAwD;QAC1DD;IACF;IACA,+EAA+E;IAC/E,kDAAkD;IAClD,IACEC,aACCL,CAAAA,KACsC,GACvC;QACAI;IACF;IACA,iCAAiC;IACjC,IACEC,aACCL,CAAAA,QAAuE,GACxE;QACAI;IACF;IACA,4EAA4E;IAC5E,+DAA+D;IAC/D,IAAIC,mBAAmD;QACrDD;IACF;IACA,6EAA6E;IAC7E,iDAAiD;IACjD,IAAIC,mBAAkD;QACpDD;IACF;IACA,OAAOA;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/shared/lib/app-router-types.ts"],"sourcesContent":["/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type { VaryParamsIterable } from './segment-cache/vary-params-decoding'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Cache node used in app-router / layout-router.\n */\n\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n prefetchHead: HeadData | null\n\n head: HeadData\n\n slots: Record<string, CacheNode> | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n\n /**\n * Globally-unique identifier minted from a monotonic counter when the\n * CacheNode is freshly created. Surfaced to user code as a string via\n * `useRouter().bfcacheId` and intended to be used as a React `key` to\n * opt out of Activity-based state preservation on fresh navigations.\n *\n * Preserved when the CacheNode is reused (shared layouts, refresh,\n * search/hash-only navigations) or restored from the BFCache during a\n * back/forward navigation.\n */\n bfcacheId: number\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and runtime prefetch\n * hints. Only set when non-zero.\n */\n prefetchHints?: number,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // This segment has a runtime prefetch enabled (via instant with\n // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.\n HasRuntimePrefetch = 0b00001,\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when a\n // truthy instant config is present, or `prefetch` is 'partial',\n // 'unstable_eager', or 'allow-runtime'. Propagates upward so the root segment\n // reflects the entire subtree.\n SubtreeHasPartialPrefetching = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n IsRootLayoutOrAbove = 0b10000,\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n ParentInlinedIntoSelf = 0b100000,\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // at the end of its SegmentPrefetch[] array.\n HeadInlinedIntoSelf = 0b10000000,\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n HeadOutlined = 0b100000000,\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n InliningHintsStale = 0b1000000000,\n // This segment has instant = false, opting out of all\n // prefetching entirely (neither static nor runtime).\n PrefetchDisabled = 0b10000000000,\n // This segment or one of its descendants has runtime prefetch enabled\n // (HasRuntimePrefetch). Propagates upward so the root reflects the\n // entire subtree.\n SubtreeHasRuntimePrefetch = 0b100000000000,\n // This segment or one of its descendants prefetches \"eagerly\" — i.e. its\n // effective prefetch strategy is anything other than 'partial' or\n // 'allow-runtime'. Used by App Shells: a non-eager subtree relies on the\n // shared app shell and skips its Speculative prefetch. Propagates upward so\n // the root reflects the entire subtree.\n SubtreeHasEagerPrefetch = 0b1000000000000,\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n SubtreeHasInstantFalse = 0b10000000000000,\n // The client should attempt a static prefetch for this route: the\n // build-time prerender did not access any runtime data (cookies, headers,\n // searchParams, ...), so a static prefetch is expected to be as complete\n // as a runtime one. A fallback-param access only unsets the bit when the\n // route can never be upgraded from a fallback to a concrete prerender —\n // on an upgradeable route, ISR later produces the concrete prerender a\n // static attempt would hit (until then, the static responses' own\n // signal reports the insufficiency per response). Purely advisory, and\n // both error directions are safe: if set when a runtime request is\n // actually needed, that same response-level signal (the load-bearing\n // `needsRuntimeRequest` promise combined with each segment's `isPartial`)\n // directs the client to follow up — the cost is a wasted static attempt.\n // If unset when static would have sufficed, the client goes straight to a\n // runtime prefetch, which is a superset of the static response — the cost\n // is only reduced cacheability. Like the other bits, this one is computed\n // once per build and stays constant for the build's lifetime; it rides\n // the prefetch-hints manifest into every response that carries hints —\n // `/_tree` prefetch responses and the FlightRouterState of dynamic\n // navigations alike. (Routes missing from the manifest — see the #91407\n // fallbacks — simply never carry it.) Set on every node of the tree, but\n // does not propagate.\n ShouldAttemptStaticPrefetch = 0b100000000000000,\n}\n\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped. Matches\n * if EITHER bit is set — i.e. the segment uses runtime prefetching\n * (HasRuntimePrefetch) OR prefetching is disabled entirely (PrefetchDisabled,\n * e.g. instant = false). The segment participates in the bundle chain\n * but with null data.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */\nexport const StaticPrefetchDisabled =\n PrefetchHint.HasRuntimePrefetch | PrefetchHint.PrefetchDisabled\n\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */\nexport const SubtreePrefetchHints =\n PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasLoadingBoundary |\n PrefetchHint.SubtreeHasRuntimePrefetch |\n PrefetchHint.SubtreeHasInstantFalse |\n PrefetchHint.SubtreeHasEagerPrefetch\n\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading boundary,\n * or it has a runtime prefetch) becomes the corresponding \"subtree\" flag on the\n * parent, so the root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a prefetch tree (createFlightRouterStateFromLoaderTree) and on the client when\n * merging a navigation patch into the existing tree (convertServerPatchToFullTree).\n * Keep these in sync by routing both through this helper.\n */\nexport function propagateSubtreeBits(\n parentHints: number,\n childHints: number\n): number {\n if (childHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n parentHints |= PrefetchHint.SubtreeHasPartialPrefetching\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (\n childHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)\n ) {\n parentHints |= PrefetchHint.SubtreeHasLoadingBoundary\n }\n // Likewise for runtime prefetch.\n if (\n childHints &\n (PrefetchHint.HasRuntimePrefetch | PrefetchHint.SubtreeHasRuntimePrefetch)\n ) {\n parentHints |= PrefetchHint.SubtreeHasRuntimePrefetch\n }\n // And for eager prefetch. The bit is set directly on each eager segment, so\n // there's no separate segment-local flag — propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasEagerPrefetch) {\n parentHints |= PrefetchHint.SubtreeHasEagerPrefetch\n }\n // And for `instant = false`. Like eager prefetch, the bit is set directly on\n // each opted-out segment, so propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasInstantFalse) {\n parentHints |= PrefetchHint.SubtreeHasInstantFalse\n }\n return parentHints\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n // TODO: This field is no longer used. Remove it.\n loading: null,\n isPartial: boolean,\n /**\n * An AsyncIterable that yields the route params this segment accessed during\n * server rendering (one name per yield, deduped). Used by the client router\n * to determine cache key specificity - segments that only access certain\n * params can be reused across navigations where unaccessed params change.\n *\n * Does NOT include root params; those are emitted once at the top level of\n * the response (see `r` on the payload) and unioned in by the consumer.\n *\n * - null: tracking was not enabled for this render (e.g., not a prerender).\n * Treat conservatively - assume all params vary.\n * - Drains to empty Set: segment accesses no params (e.g., client components,\n * or server components that don't read params). Can be shared across all\n * param values.\n * - Drains to non-empty Set: segment depends on those params. Can only reuse\n * when those specific params match.\n */\n varyParams: VaryParamsIterable | null,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array<FlightDataPath> | string\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record<string, PrefetchHints> | null\n}\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * headVaryParams - vary params for the head (metadata) of the response.\n * Does not include root params (see `r`).\n */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params, rather than the server folding them into each set.\n */\n r?: VaryParamsIterable\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable<number>\n /**\n * runtimeDataAccessed — whether the render has accessed a data source that\n * hangs during a static prerender but would resolve during a runtime\n * prerender (cookies, headers, fallback params, searchParams, ...). The\n * flag is monotonic (false → true, at most once), so it's encoded as a\n * promise: resolved `true` at the moment of first access — the fulfillment\n * row's position in the stream records the stage the access happened in —\n * or resolved `false` when the prerender completes without one, a row that\n * lands past every stage boundary. A truncated (shell) decode therefore\n * reads the answer as of the shell stage: fulfilled `true` iff the access\n * happened during a stage it includes, pending (⇒ no access) otherwise.\n * Unlike an async iterable, a pending promise costs Flight no abort\n * listener on the render. Used when generating per-segment prefetch\n * responses (forwarded as the response-level `needsRuntimeRequest`).\n * The build-constant `PrefetchHint.ShouldAttemptStaticPrefetch` is\n * tracked directly on the prerender store instead (its\n * `shouldAttemptStaticPrefetch` cell) — it needs neither stream\n * positioning nor this flag's param/non-param blindness. Only present\n * for static prerenders when Cache Components is enabled.\n */\n u?: Promise<boolean>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** supportsPerSegmentPrefetching */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** staleTime - Only present in dynamic runtime prefetch responses. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /**\n * shellUsedSessionData - true if resolving session data\n * unblocked new content in the shell.\n * NOTE: only use this in runtime/session prefetch requests\n * where we have a proper session shell.\n * */\n u?: Promise<boolean>\n /** headVaryParams. Does not include root params (see `r`). */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params.\n */\n r?: VaryParamsIterable\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n\nexport type InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n"],"names":["PrefetchHint","StaticPrefetchDisabled","SubtreePrefetchHints","propagateSubtreeBits","parentHints","childHints"],"mappings":"AAAA;;;;;CAKC,GAiLD,OAAO,IAAA,AAAWA,sCAAAA;IAChB,gEAAgE;IAChE,2EAA2E;;IAE3E,6EAA6E;IAC7E,wEAAwE;IACxE,gEAAgE;IAChE,8EAA8E;IAC9E,+BAA+B;;IAE/B,kDAAkD;;IAElD,sEAAsE;IACtE,6DAA6D;;IAE7D,8EAA8E;IAC9E,2EAA2E;IAC3E,8BAA8B;;IAE9B,sEAAsE;IACtE,0DAA0D;;IAE1D,wEAAwE;IACxE,yEAAyE;;IAEzE,4EAA4E;IAC5E,6CAA6C;;IAE7C,wEAAwE;IACxE,4EAA4E;;IAE5E,oEAAoE;IACpE,0EAA0E;IAC1E,0EAA0E;IAC1E,kEAAkE;IAClE,0EAA0E;IAC1E,oBAAoB;;IAEpB,sDAAsD;IACtD,qDAAqD;;IAErD,sEAAsE;IACtE,mEAAmE;IACnE,kBAAkB;;IAElB,yEAAyE;IACzE,kEAAkE;IAClE,yEAAyE;IACzE,4EAA4E;IAC5E,wCAAwC;;IAExC,oEAAoE;IACpE,8EAA8E;IAC9E,kEAAkE;IAClE,+EAA+E;IAC/E,mCAAmC;;IAEnC,kEAAkE;IAClE,0EAA0E;IAC1E,yEAAyE;IACzE,yEAAyE;IACzE,wEAAwE;IACxE,uEAAuE;IACvE,kEAAkE;IAClE,uEAAuE;IACvE,mEAAmE;IACnE,qEAAqE;IACrE,0EAA0E;IAC1E,yEAAyE;IACzE,0EAA0E;IAC1E,0EAA0E;IAC1E,0EAA0E;IAC1E,uEAAuE;IACvE,uEAAuE;IACvE,mEAAmE;IACnE,wEAAwE;IACxE,yEAAyE;IACzE,sBAAsB;;WA7ENA;MA+EjB;AAED;;;;;;;;CAQC,GACD,OAAO,MAAMC,yBACXD,SAA+D;AAEjE;;;;;CAKC,GACD,OAAO,MAAME,uBACXF,2BAIoC;AAEtC;;;;;;;;;;CAUC,GACD,OAAO,SAASG,qBACdC,WAAmB,EACnBC,UAAkB;IAElB,IAAIA,gBAAwD;QAC1DD;IACF;IACA,+EAA+E;IAC/E,kDAAkD;IAClD,IACEC,aACCL,CAAAA,KACsC,GACvC;QACAI;IACF;IACA,iCAAiC;IACjC,IACEC,aACCL,CAAAA,QAAuE,GACxE;QACAI;IACF;IACA,4EAA4E;IAC5E,+DAA+D;IAC/D,IAAIC,mBAAmD;QACrDD;IACF;IACA,6EAA6E;IAC7E,iDAAiD;IACjD,IAAIC,mBAAkD;QACpDD;IACF;IACA,OAAOA;AACT","ignoreList":[0]} |
| export function isStableBuild() { | ||
| return !"16.3.0-canary.97"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| return !"16.3.0-canary.99"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| } | ||
@@ -4,0 +4,0 @@ export class CanaryOnlyConfigError extends Error { |
@@ -97,2 +97,10 @@ "use strict"; | ||
| body: JSON.stringify(proxyRequest), | ||
| // The header lets the ClientRequest interception in `httpget.ts` identify | ||
| // this request as part of the test proxy protocol. @mswjs/interceptors | ||
| // intercepts at the TCP level, so this request would otherwise be | ||
| // intercepted again when it's sent from within an interception listener, | ||
| // recursing indefinitely. | ||
| headers: { | ||
| 'next-test-internal': '1' | ||
| }, | ||
| next: { | ||
@@ -99,0 +107,0 @@ // @ts-ignore |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/experimental/testmode/fetch.ts"],"sourcesContent":["import type {\n ProxyFetchRequest,\n ProxyFetchResponse,\n ProxyResponse,\n} from './proxy'\nimport { getTestReqInfo, type TestRequestReader } from './context'\n\ntype Fetch = typeof fetch\ntype FetchInputArg = Parameters<Fetch>[0]\ntype FetchInitArg = Parameters<Fetch>[1]\n\nexport const reader: TestRequestReader<Request> = {\n url(req) {\n return req.url\n },\n header(req, name) {\n return req.headers.get(name)\n },\n}\n\nfunction getTestStack(): string {\n let stack = (new Error().stack ?? '').split('\\n')\n // Skip the first line and find first non-empty line.\n for (let i = 1; i < stack.length; i++) {\n if (stack[i].length > 0) {\n stack = stack.slice(i)\n break\n }\n }\n // Filter out franmework lines.\n stack = stack.filter((f) => !f.includes('/next/dist/'))\n // At most 5 lines.\n stack = stack.slice(0, 5)\n // Cleanup some internal info and trim.\n stack = stack.map((s) => s.replace('webpack-internal:///(rsc)/', '').trim())\n return stack.join(' ')\n}\n\nasync function buildProxyRequest(\n testData: string,\n request: Request\n): Promise<ProxyFetchRequest> {\n const {\n url,\n method,\n headers,\n body,\n cache,\n credentials,\n integrity,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n } = request\n return {\n testData,\n api: 'fetch',\n request: {\n url,\n method,\n headers: [...Array.from(headers), ['next-test-stack', getTestStack()]],\n body: body\n ? Buffer.from(await request.arrayBuffer()).toString('base64')\n : null,\n cache,\n credentials,\n integrity,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n },\n }\n}\n\nfunction buildResponse(proxyResponse: ProxyFetchResponse): Response {\n const { status, headers, body } = proxyResponse.response\n return new Response(body ? Buffer.from(body, 'base64') : null, {\n status,\n headers: new Headers(headers),\n })\n}\n\nexport async function handleFetch(\n originalFetch: Fetch,\n request: Request\n): Promise<Response> {\n const testInfo = getTestReqInfo(request, reader)\n if (!testInfo) {\n // Passthrough non-test requests.\n return originalFetch(request)\n }\n\n const { testData, proxyPort } = testInfo\n const proxyRequest = await buildProxyRequest(testData, request)\n\n const resp = await originalFetch(`http://localhost:${proxyPort}`, {\n method: 'POST',\n body: JSON.stringify(proxyRequest),\n next: {\n // @ts-ignore\n internal: true,\n },\n })\n if (!resp.ok) {\n throw new Error(`Proxy request failed: ${resp.status}`)\n }\n\n const proxyResponse = (await resp.json()) as ProxyResponse\n const { api } = proxyResponse\n switch (api) {\n case 'continue':\n return originalFetch(request)\n case 'abort':\n case 'unhandled':\n throw new Error(\n `Proxy request aborted [${request.method} ${request.url}]`\n )\n case 'fetch':\n return buildResponse(proxyResponse)\n default:\n return api satisfies never\n }\n}\n\nexport function interceptFetch(originalFetch: Fetch) {\n global.fetch = function testFetch(\n input: FetchInputArg,\n init?: FetchInitArg\n ): Promise<Response> {\n // Passthrough internal requests.\n // @ts-ignore\n if (init?.next?.internal) {\n return originalFetch(input, init)\n }\n return handleFetch(originalFetch, new Request(input, init))\n }\n return () => {\n global.fetch = originalFetch\n }\n}\n"],"names":["handleFetch","interceptFetch","reader","url","req","header","name","headers","get","getTestStack","stack","Error","split","i","length","slice","filter","f","includes","map","s","replace","trim","join","buildProxyRequest","testData","request","method","body","cache","credentials","integrity","mode","redirect","referrer","referrerPolicy","api","Array","from","Buffer","arrayBuffer","toString","buildResponse","proxyResponse","status","response","Response","Headers","originalFetch","testInfo","getTestReqInfo","proxyPort","proxyRequest","resp","JSON","stringify","next","internal","ok","json","global","fetch","testFetch","input","init","Request"],"mappings":";;;;;;;;;;;;;;;;IAoFsBA,WAAW;eAAXA;;IA0CNC,cAAc;eAAdA;;IAnHHC,MAAM;eAANA;;;yBAN0C;AAMhD,MAAMA,SAAqC;IAChDC,KAAIC,GAAG;QACL,OAAOA,IAAID,GAAG;IAChB;IACAE,QAAOD,GAAG,EAAEE,IAAI;QACd,OAAOF,IAAIG,OAAO,CAACC,GAAG,CAACF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,cAAce,OAAOC;QAC9B;QACA,OAAOhE,YAAYgD,eAAe,IAAIiB,QAAQF,OAAOC;IACvD;IACA,OAAO;QACLJ,OAAOC,KAAK,GAAGb;IACjB;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/experimental/testmode/fetch.ts"],"sourcesContent":["import type {\n ProxyFetchRequest,\n ProxyFetchResponse,\n ProxyResponse,\n} from './proxy'\nimport { getTestReqInfo, type TestRequestReader } from './context'\n\ntype Fetch = typeof fetch\ntype FetchInputArg = Parameters<Fetch>[0]\ntype FetchInitArg = Parameters<Fetch>[1]\n\nexport const reader: TestRequestReader<Request> = {\n url(req) {\n return req.url\n },\n header(req, name) {\n return req.headers.get(name)\n },\n}\n\nfunction getTestStack(): string {\n let stack = (new Error().stack ?? '').split('\\n')\n // Skip the first line and find first non-empty line.\n for (let i = 1; i < stack.length; i++) {\n if (stack[i].length > 0) {\n stack = stack.slice(i)\n break\n }\n }\n // Filter out franmework lines.\n stack = stack.filter((f) => !f.includes('/next/dist/'))\n // At most 5 lines.\n stack = stack.slice(0, 5)\n // Cleanup some internal info and trim.\n stack = stack.map((s) => s.replace('webpack-internal:///(rsc)/', '').trim())\n return stack.join(' ')\n}\n\nasync function buildProxyRequest(\n testData: string,\n request: Request\n): Promise<ProxyFetchRequest> {\n const {\n url,\n method,\n headers,\n body,\n cache,\n credentials,\n integrity,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n } = request\n return {\n testData,\n api: 'fetch',\n request: {\n url,\n method,\n headers: [...Array.from(headers), ['next-test-stack', getTestStack()]],\n body: body\n ? Buffer.from(await request.arrayBuffer()).toString('base64')\n : null,\n cache,\n credentials,\n integrity,\n mode,\n redirect,\n referrer,\n referrerPolicy,\n },\n }\n}\n\nfunction buildResponse(proxyResponse: ProxyFetchResponse): Response {\n const { status, headers, body } = proxyResponse.response\n return new Response(body ? Buffer.from(body, 'base64') : null, {\n status,\n headers: new Headers(headers),\n })\n}\n\nexport async function handleFetch(\n originalFetch: Fetch,\n request: Request\n): Promise<Response> {\n const testInfo = getTestReqInfo(request, reader)\n if (!testInfo) {\n // Passthrough non-test requests.\n return originalFetch(request)\n }\n\n const { testData, proxyPort } = testInfo\n const proxyRequest = await buildProxyRequest(testData, request)\n\n const resp = await originalFetch(`http://localhost:${proxyPort}`, {\n method: 'POST',\n body: JSON.stringify(proxyRequest),\n // The header lets the ClientRequest interception in `httpget.ts` identify\n // this request as part of the test proxy protocol. @mswjs/interceptors\n // intercepts at the TCP level, so this request would otherwise be\n // intercepted again when it's sent from within an interception listener,\n // recursing indefinitely.\n headers: {\n 'next-test-internal': '1',\n },\n next: {\n // @ts-ignore\n internal: true,\n },\n })\n if (!resp.ok) {\n throw new Error(`Proxy request failed: ${resp.status}`)\n }\n\n const proxyResponse = (await resp.json()) as ProxyResponse\n const { api } = proxyResponse\n switch (api) {\n case 'continue':\n return originalFetch(request)\n case 'abort':\n case 'unhandled':\n throw new Error(\n `Proxy request aborted [${request.method} ${request.url}]`\n )\n case 'fetch':\n return buildResponse(proxyResponse)\n default:\n return api satisfies never\n }\n}\n\nexport function interceptFetch(originalFetch: Fetch) {\n global.fetch = function testFetch(\n input: FetchInputArg,\n init?: FetchInitArg\n ): Promise<Response> {\n // Passthrough internal requests.\n // @ts-ignore\n if (init?.next?.internal) {\n return originalFetch(input, init)\n }\n return handleFetch(originalFetch, new Request(input, init))\n }\n return () => {\n global.fetch = originalFetch\n }\n}\n"],"names":["handleFetch","interceptFetch","reader","url","req","header","name","headers","get","getTestStack","stack","Error","split","i","length","slice","filter","f","includes","map","s","replace","trim","join","buildProxyRequest","testData","request","method","body","cache","credentials","integrity","mode","redirect","referrer","referrerPolicy","api","Array","from","Buffer","arrayBuffer","toString","buildResponse","proxyResponse","status","response","Response","Headers","originalFetch","testInfo","getTestReqInfo","proxyPort","proxyRequest","resp","JSON","stringify","next","internal","ok","json","global","fetch","testFetch","input","init","Request"],"mappings":";;;;;;;;;;;;;;;;IAoFsBA,WAAW;eAAXA;;IA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ADtD,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF,KAAK;YACH,OAAOuC,cAAcC;QACvB;YACE,OAAOP;IACX;AACF;AAEO,SAASnC,eAAe+C,aAAoB;IACjDY,OAAOC,KAAK,GAAG,SAASC,UACtBC,KAAoB,EACpBC,IAAmB;YAIfA;QAFJ,iCAAiC;QACjC,aAAa;QACb,IAAIA,yBAAAA,aAAAA,KAAMR,IAAI,qBAAVQ,WAAYP,QAAQ,EAAE;YACxB,OAAOT,cAAce,OAAOC;QAC9B;QACA,OAAOhE,YAAYgD,eAAe,IAAIiB,QAAQF,OAAOC;IACvD;IACA,OAAO;QACLJ,OAAOC,KAAK,GAAGb;IACjB;AACF","ignoreList":[0]} |
@@ -15,5 +15,12 @@ "use strict"; | ||
| const clientRequestInterceptor = new _ClientRequest.ClientRequestInterceptor(); | ||
| clientRequestInterceptor.on('request', async ({ request })=>{ | ||
| clientRequestInterceptor.on('request', async ({ request, controller })=>{ | ||
| if (request.headers.get('next-test-internal') === '1') { | ||
| // A request that's part of the test proxy protocol itself, sent by | ||
| // `handleFetch` from within this listener. Not responding lets the | ||
| // interceptor perform it against the real server. Handling it here | ||
| // instead would recurse indefinitely. | ||
| return; | ||
| } | ||
| const response = await (0, _fetch.handleFetch)(originalFetch, request); | ||
| request.respondWith(response); | ||
| controller.respondWith(response); | ||
| }); | ||
@@ -20,0 +27,0 @@ clientRequestInterceptor.apply(); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/experimental/testmode/httpget.ts"],"sourcesContent":["import { ClientRequestInterceptor } from 'next/dist/compiled/@mswjs/interceptors/ClientRequest'\nimport { handleFetch } from './fetch'\n\ntype Fetch = typeof fetch\n\nexport function interceptHttpGet(originalFetch: Fetch): () => void {\n const clientRequestInterceptor = new ClientRequestInterceptor()\n clientRequestInterceptor.on('request', async ({ request }) => {\n const response = await handleFetch(originalFetch, request)\n request.respondWith(response)\n })\n clientRequestInterceptor.apply()\n\n // Cleanup.\n return () => {\n clientRequestInterceptor.dispose()\n }\n}\n"],"names":["interceptHttpGet","originalFetch","clientRequestInterceptor","ClientRequestInterceptor","on","request","response","handleFetch","respondWith","apply","dispose"],"mappings":";;;;+BAKgBA;;;eAAAA;;;+BALyB;uBACb;AAIrB,SAASA,iBAAiBC,aAAoB;IACnD,MAAMC,2BAA2B,IAAIC,uCAAwB;IAC7DD,yBAAyBE,EAAE,CAAC,WAAW,OAAO,EAAEC,OAAO,EAAE;QACvD,MAAMC,WAAW,MAAMC,IAAAA,kBAAW,EAACN,eAAeI;QAClDA,QAAQG,WAAW,CAACF;IACtB;IACAJ,yBAAyBO,KAAK;IAE9B,WAAW;IACX,OAAO;QACLP,yBAAyBQ,OAAO;IAClC;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/experimental/testmode/httpget.ts"],"sourcesContent":["import { ClientRequestInterceptor } from 'next/dist/compiled/@mswjs/interceptors/ClientRequest'\nimport { handleFetch } from './fetch'\n\ntype Fetch = typeof fetch\n\nexport function interceptHttpGet(originalFetch: Fetch): () => void {\n const clientRequestInterceptor = new ClientRequestInterceptor()\n clientRequestInterceptor.on('request', async ({ request, controller }) => {\n if (request.headers.get('next-test-internal') === '1') {\n // A request that's part of the test proxy protocol itself, sent by\n // `handleFetch` from within this listener. Not responding lets the\n // interceptor perform it against the real server. Handling it here\n // instead would recurse indefinitely.\n return\n }\n const response = await handleFetch(originalFetch, request)\n controller.respondWith(response)\n })\n clientRequestInterceptor.apply()\n\n // Cleanup.\n return () => {\n clientRequestInterceptor.dispose()\n }\n}\n"],"names":["interceptHttpGet","originalFetch","clientRequestInterceptor","ClientRequestInterceptor","on","request","controller","headers","get","response","handleFetch","respondWith","apply","dispose"],"mappings":";;;;+BAKgBA;;;eAAAA;;;+BALyB;uBACb;AAIrB,SAASA,iBAAiBC,aAAoB;IACnD,MAAMC,2BAA2B,IAAIC,uCAAwB;IAC7DD,yBAAyBE,EAAE,CAAC,WAAW,OAAO,EAAEC,OAAO,EAAEC,UAAU,EAAE;QACnE,IAAID,QAAQE,OAAO,CAACC,GAAG,CAAC,0BAA0B,KAAK;YACrD,mEAAmE;YACnE,mEAAmE;YACnE,mEAAmE;YACnE,sCAAsC;YACtC;QACF;QACA,MAAMC,WAAW,MAAMC,IAAAA,kBAAW,EAACT,eAAeI;QAClDC,WAAWK,WAAW,CAACF;IACzB;IACAP,yBAAyBU,KAAK;IAE9B,WAAW;IACX,OAAO;QACLV,yBAAyBW,OAAO;IAClC;AACF","ignoreList":[0]} |
@@ -45,3 +45,13 @@ "use strict"; | ||
| }; | ||
| const interceptedSymbol = Symbol.for('next.testmode.intercepted'); | ||
| function interceptTestApis() { | ||
| // In development the render server runs in the same process as the router | ||
| // server, so both call this function. @mswjs/interceptors throws when its | ||
| // global replacements are applied a second time, so make repeated | ||
| // interception within the same process a no-op. | ||
| const globalState = globalThis; | ||
| if (globalState[interceptedSymbol] === true) { | ||
| return ()=>{}; | ||
| } | ||
| globalState[interceptedSymbol] = true; | ||
| const originalFetch = global.fetch; | ||
@@ -52,2 +62,3 @@ const restoreFetch = (0, _fetch.interceptFetch)(originalFetch); | ||
| return ()=>{ | ||
| globalState[interceptedSymbol] = false; | ||
| restoreFetch(); | ||
@@ -54,0 +65,0 @@ restoreHttpGet(); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/experimental/testmode/server.ts"],"sourcesContent":["import type { WorkerRequestHandler } from '../../server/lib/types'\nimport type { NodeRequestHandler } from '../../server/next-server'\nimport { withRequest, type TestRequestReader } from './context'\nimport { interceptFetch } from './fetch'\nimport { interceptHttpGet } from './httpget'\nimport type { IncomingMessage } from 'http'\n\nconst reader: TestRequestReader<IncomingMessage> = {\n url(req) {\n return req.url ?? ''\n },\n header(req, name) {\n const h = req.headers[name]\n if (h === undefined || h === null) {\n return null\n }\n if (typeof h === 'string') {\n return h\n }\n return h[0] ?? null\n },\n}\n\nexport function interceptTestApis(): () => void {\n const originalFetch = global.fetch\n const restoreFetch = interceptFetch(originalFetch)\n const restoreHttpGet = interceptHttpGet(originalFetch)\n\n // Cleanup.\n return () => {\n restoreFetch()\n restoreHttpGet()\n }\n}\n\nexport function wrapRequestHandlerWorker(\n handler: WorkerRequestHandler\n): WorkerRequestHandler {\n return (req, res) => withRequest(req, reader, () => handler(req, res))\n}\n\nexport function wrapRequestHandlerNode(\n handler: NodeRequestHandler\n): NodeRequestHandler {\n return (req, res, parsedUrl) =>\n withRequest(req, reader, () => handler(req, res, parsedUrl))\n}\n"],"names":["interceptTestApis","wrapRequestHandlerNode","wrapRequestHandlerWorker","reader","url","req","header","name","h","headers","undefined","originalFetch","global","fetch","restoreFetch","interceptFetch","restoreHttpGet","interceptHttpGet","handler","res","withRequest","parsedUrl"],"mappings":";;;;;;;;;;;;;;;;IAuBgBA,iBAAiB;eAAjBA;;IAkBAC,sBAAsB;eAAtBA;;IANAC,wBAAwB;eAAxBA;;;yBAjCoC;uBACrB;yBACE;AAGjC,MAAMC,SAA6C;IACjDC,KAAIC,GAAG;QACL,OAAOA,IAAID,GAAG,IAAI;IACpB;IACAE,QAAOD,GAAG,EAAEE,IAAI;QACd,MAAMC,IAAIH,IAAII,OAAO,CAACF,KAAK;QAC3B,IAAIC,MAAME,aAAaF,MAAM,MAAM;YACjC,OAAO;QACT;QACA,IAAI,OAAOA,MAAM,UAAU;YACzB,OAAOA;QACT;QACA,OAAOA,CAAC,CAAC,EAAE,IAAI;IACjB;AACF;AAEO,SAASR;IACd,MAAMW,gBAAgBC,OAAOC,KAAK;IAClC,MAAMC,eAAeC,IAAAA,qBAAc,EAACJ;IACpC,MAAMK,iBAAiBC,IAAAA,yBAAgB,EAACN;IAExC,WAAW;IACX,OAAO;QACLG;QACAE;IACF;AACF;AAEO,SAASd,yBACdgB,OAA6B;IAE7B,OAAO,CAACb,KAAKc,MAAQC,IAAAA,oBAAW,EAACf,KAAKF,QAAQ,IAAMe,QAAQb,KAAKc;AACnE;AAEO,SAASlB,uBACdiB,OAA2B;IAE3B,OAAO,CAACb,KAAKc,KAAKE,YAChBD,IAAAA,oBAAW,EAACf,KAAKF,QAAQ,IAAMe,QAAQb,KAAKc,KAAKE;AACrD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/experimental/testmode/server.ts"],"sourcesContent":["import type { WorkerRequestHandler } from '../../server/lib/types'\nimport type { NodeRequestHandler } from '../../server/next-server'\nimport { withRequest, type TestRequestReader } from './context'\nimport { interceptFetch } from './fetch'\nimport { interceptHttpGet } from './httpget'\nimport type { IncomingMessage } from 'http'\n\nconst reader: TestRequestReader<IncomingMessage> = {\n url(req) {\n return req.url ?? ''\n },\n header(req, name) {\n const h = req.headers[name]\n if (h === undefined || h === null) {\n return null\n }\n if (typeof h === 'string') {\n return h\n }\n return h[0] ?? null\n },\n}\n\nconst interceptedSymbol = Symbol.for('next.testmode.intercepted')\n\nexport function interceptTestApis(): () => void {\n // In development the render server runs in the same process as the router\n // server, so both call this function. @mswjs/interceptors throws when its\n // global replacements are applied a second time, so make repeated\n // interception within the same process a no-op.\n const globalState = globalThis as { [interceptedSymbol]?: boolean }\n if (globalState[interceptedSymbol] === true) {\n return () => {}\n }\n globalState[interceptedSymbol] = true\n\n const originalFetch = global.fetch\n const restoreFetch = interceptFetch(originalFetch)\n const restoreHttpGet = interceptHttpGet(originalFetch)\n\n // Cleanup.\n return () => {\n globalState[interceptedSymbol] = false\n restoreFetch()\n restoreHttpGet()\n }\n}\n\nexport function wrapRequestHandlerWorker(\n handler: WorkerRequestHandler\n): WorkerRequestHandler {\n return (req, res) => withRequest(req, reader, () => handler(req, res))\n}\n\nexport function wrapRequestHandlerNode(\n handler: NodeRequestHandler\n): NodeRequestHandler {\n return (req, res, parsedUrl) =>\n withRequest(req, reader, () => handler(req, res, parsedUrl))\n}\n"],"names":["interceptTestApis","wrapRequestHandlerNode","wrapRequestHandlerWorker","reader","url","req","header","name","h","headers","undefined","interceptedSymbol","Symbol","for","globalState","globalThis","originalFetch","global","fetch","restoreFetch","interceptFetch","restoreHttpGet","interceptHttpGet","handler","res","withRequest","parsedUrl"],"mappings":";;;;;;;;;;;;;;;;IAyBgBA,iBAAiB;eAAjBA;;IA6BAC,sBAAsB;eAAtBA;;IANAC,wBAAwB;eAAxBA;;;yBA9CoC;uBACrB;yBACE;AAGjC,MAAMC,SAA6C;IACjDC,KAAIC,GAAG;QACL,OAAOA,IAAID,GAAG,IAAI;IACpB;IACAE,QAAOD,GAAG,EAAEE,IAAI;QACd,MAAMC,IAAIH,IAAII,OAAO,CAACF,KAAK;QAC3B,IAAIC,MAAME,aAAaF,MAAM,MAAM;YACjC,OAAO;QACT;QACA,IAAI,OAAOA,MAAM,UAAU;YACzB,OAAOA;QACT;QACA,OAAOA,CAAC,CAAC,EAAE,IAAI;IACjB;AACF;AAEA,MAAMG,oBAAoBC,OAAOC,GAAG,CAAC;AAE9B,SAASb;IACd,0EAA0E;IAC1E,0EAA0E;IAC1E,kEAAkE;IAClE,gDAAgD;IAChD,MAAMc,cAAcC;IACpB,IAAID,WAAW,CAACH,kBAAkB,KAAK,MAAM;QAC3C,OAAO,KAAO;IAChB;IACAG,WAAW,CAACH,kBAAkB,GAAG;IAEjC,MAAMK,gBAAgBC,OAAOC,KAAK;IAClC,MAAMC,eAAeC,IAAAA,qBAAc,EAACJ;IACpC,MAAMK,iBAAiBC,IAAAA,yBAAgB,EAACN;IAExC,WAAW;IACX,OAAO;QACLF,WAAW,CAACH,kBAAkB,GAAG;QACjCQ;QACAE;IACF;AACF;AAEO,SAASnB,yBACdqB,OAA6B;IAE7B,OAAO,CAAClB,KAAKmB,MAAQC,IAAAA,oBAAW,EAACpB,KAAKF,QAAQ,IAAMoB,QAAQlB,KAAKmB;AACnE;AAEO,SAASvB,uBACdsB,OAA2B;IAE3B,OAAO,CAAClB,KAAKmB,KAAKE,YAChBD,IAAAA,oBAAW,EAACpB,KAAKF,QAAQ,IAAMoB,QAAQlB,KAAKmB,KAAKE;AACrD","ignoreList":[0]} |
@@ -75,3 +75,3 @@ "use strict"; | ||
| const data = await res.json(); | ||
| const versionData = data.versions["16.3.0-canary.97"]; | ||
| const versionData = data.versions["16.3.0-canary.99"]; | ||
| return { | ||
@@ -104,3 +104,3 @@ os: versionData.os, | ||
| lockfileParsed.dependencies[pkg] = { | ||
| version: "16.3.0-canary.97", | ||
| version: "16.3.0-canary.99", | ||
| resolved: pkgData.tarball, | ||
@@ -113,3 +113,3 @@ integrity: pkgData.integrity, | ||
| lockfileParsed.packages[pkg] = { | ||
| version: "16.3.0-canary.97", | ||
| version: "16.3.0-canary.99", | ||
| resolved: pkgData.tarball, | ||
@@ -116,0 +116,0 @@ integrity: pkgData.integrity, |
@@ -1,3 +0,3 @@ | ||
| import type { RequestInsight } from '../../../shared/request-insights'; | ||
| export declare function getActiveRequestId(requests: readonly RequestInsight[], selectedRequestId: string | null): string | null; | ||
| export declare function isPageLoadRequest(request: Pick<RequestInsight, 'requestId'>, initialRequestId: string | undefined): boolean; | ||
| import { type RequestInsight } from '../../../shared/request-insights'; | ||
| export declare function getActiveRequestKey(requests: readonly RequestInsight[], selectedRequestKey: string | null): string | null; | ||
| export declare function isPageLoadRequest(request: Pick<RequestInsight, 'requestId' | 'kind'>, initialRequestId: string | undefined): boolean; |
@@ -102,2 +102,3 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types'; | ||
| export declare const ACTION_REQUEST_INSIGHTS_UPDATE = "request-insights-update"; | ||
| export declare function updateRequestInsights(currentRequests: readonly RequestInsight[], insight: RequestInsight): RequestInsight[]; | ||
| export declare const STORAGE_KEY_PANEL_POSITION_PREFIX = "__nextjs-dev-tools-panel-position"; | ||
@@ -104,0 +105,0 @@ export declare const STORE_KEY_PANEL_SIZE_PREFIX = "__nextjs-dev-tools-panel-size"; |
@@ -0,1 +1,3 @@ | ||
| import type { RequestInsightKind } from '../../shared/lib/request-insights'; | ||
| export { getRequestInsightKey, getRequestInsightKind, type RequestInsightIdentity, type RequestInsightKind, } from '../../shared/lib/request-insights'; | ||
| type RequestInsightAttributeValue = string | number | boolean | Array<null | undefined | string> | Array<null | undefined | number> | Array<null | undefined | boolean>; | ||
@@ -38,2 +40,3 @@ export type RequestInsightSpan = { | ||
| requestId: string; | ||
| kind?: RequestInsightKind; | ||
| htmlRequestId: string; | ||
@@ -51,2 +54,1 @@ route?: string; | ||
| }; | ||
| export {}; |
@@ -5,2 +5,21 @@ "use strict"; | ||
| }); | ||
| 0 && (module.exports = { | ||
| getRequestInsightKey: null, | ||
| getRequestInsightKind: null | ||
| }); | ||
| function _export(target, all) { | ||
| for(var name in all)Object.defineProperty(target, name, { | ||
| enumerable: true, | ||
| get: all[name] | ||
| }); | ||
| } | ||
| _export(exports, { | ||
| getRequestInsightKey: function() { | ||
| return _requestinsights.getRequestInsightKey; | ||
| }, | ||
| getRequestInsightKind: function() { | ||
| return _requestinsights.getRequestInsightKind; | ||
| } | ||
| }); | ||
| const _requestinsights = require("../../shared/lib/request-insights"); | ||
@@ -7,0 +26,0 @@ if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":[],"names":[],"mappings":"","ignoreList":[]} | ||
| {"version":3,"sources":["../../../src/next-devtools/shared/request-insights.ts"],"sourcesContent":["import type { RequestInsightKind } from '../../shared/lib/request-insights'\n\nexport {\n getRequestInsightKey,\n getRequestInsightKind,\n type RequestInsightIdentity,\n type RequestInsightKind,\n} from '../../shared/lib/request-insights'\n\ntype RequestInsightAttributeValue =\n | string\n | number\n | boolean\n | Array<null | undefined | string>\n | Array<null | undefined | number>\n | Array<null | undefined | boolean>\n\nexport type RequestInsightSpan = {\n name: string\n startTime: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n attributes?: Record<string, RequestInsightAttributeValue>\n links?: Array<{\n traceId: string\n spanId: string\n attributes?: Record<string, RequestInsightAttributeValue>\n }>\n events?: Array<{\n name: string\n timestamp: number\n attributes?: Record<string, RequestInsightAttributeValue>\n }>\n error?: {\n type?: string\n message?: string\n }\n}\n\nexport type RequestInsightFetch = {\n url?: string\n method?: string\n statusCode?: number\n startTime?: number\n durationMs?: number\n cacheStatus?: string\n cacheReason?: string\n index?: number\n}\n\nexport type RequestInsight = {\n requestId: string\n kind?: RequestInsightKind\n htmlRequestId: string\n route?: string\n url?: string\n startTime: number\n durationMs?: number\n status: 'ok' | 'error' | 'pending'\n spans: RequestInsightSpan[]\n fetches: RequestInsightFetch[]\n}\n\nexport type RequestInsightsSnapshot = {\n requests: RequestInsight[]\n}\n"],"names":["getRequestInsightKey","getRequestInsightKind"],"mappings":";;;;;;;;;;;;;;;IAGEA,oBAAoB;eAApBA,qCAAoB;;IACpBC,qBAAqB;eAArBA,sCAAqB;;;iCAGhB","ignoreList":[0]} |
| import type { DynamicParamTypesShort, PrefetchHints } from '../../shared/lib/app-router-types'; | ||
| import type { VaryParamsIterable } from '../../shared/lib/segment-cache/vary-params-decoding'; | ||
| import type { ManifestNode } from '../../build/webpack/plugins/flight-manifest-plugin'; | ||
@@ -51,17 +52,94 @@ import { type SegmentRequestKey } from '../../shared/lib/segment-cache/segment-value-encoding'; | ||
| isUpgradeableISRFallback: boolean; | ||
| /** | ||
| * Shell byte boundary — the segment-level analogue of the route-level `a`. | ||
| * A promise because the value is only known mid-stream; its resolution row | ||
| * flushes past the boundary, so a truncated shell decode reads it as | ||
| * pending, which is harmless. | ||
| * | ||
| * - `> 0`: byte offset such that re-decoding the response truncated there | ||
| * yields the shell variant of every segment — param-dependent content | ||
| * reduced to still-pending references (which render as the param fallback). | ||
| * - `null`: the shell is the full response; no separate decode needed. | ||
| * - `0`: no shell (the page wasn't produced by staged rendering). Never a | ||
| * valid offset — an envelope always has bytes — so it doubles as the | ||
| * "none" sentinel. | ||
| */ | ||
| a: Promise<number | null>; | ||
| /** | ||
| * Root params accessed anywhere in this response, emitted once here rather | ||
| * than folded into each segment's `varyParams`, mirroring the route-level | ||
| * response's split of `r` from per-segment params. The client unions them | ||
| * back in via `readVaryParams`. | ||
| */ | ||
| rootVaryParams: VaryParamsIterable | null; | ||
| /** | ||
| * The page's runtime-data-access flag (the page payload's `u`), forwarded | ||
| * from the staged decode of the page data: whether the prerender accessed | ||
| * a data source that would have resolved during a runtime prerender | ||
| * (cookies, headers, fallback params, searchParams, ...). The flag is | ||
| * monotonic (false → true, at most once), so a promise suffices; the | ||
| * client takes the settled value visible in its decode. Fulfilled `true` | ||
| * means a runtime prefetch would return more than this static response; | ||
| * pending or fulfilled `false` means it wouldn't. The answer is rewindable | ||
| * because the fulfillment row lands on the same side of the shell byte | ||
| * boundary (`a`) as the access it records: a decode truncated at `a` reads | ||
| * pending for a post-shell access, i.e. `false` for the shell variant. | ||
| * | ||
| * Tracking is page-global, so this lives on the response envelope, not on | ||
| * each segment. (A pending promise also costs Flight no abort listener on | ||
| * the render, unlike an async iterable, which holds one for as long as | ||
| * it's open.) Per-segment granularity comes from combining it with each | ||
| * segment's `isPartial`: | ||
| * | ||
| * needsRuntimeRequest(segment) = (settled true) && (isPartial pending) | ||
| * | ||
| * A segment whose `isPartial` promise fulfilled is fully static, and a | ||
| * fully static segment gains nothing from a runtime request no matter what | ||
| * the page accessed. Conversely, a partial segment on a page that accessed | ||
| * no runtime data also reads `false`: its holes come from sources that hang | ||
| * in a runtime prerender too (`io()`, `connection()`, uncached IO), and are | ||
| * only filled by the navigation-time dynamic request. | ||
| * | ||
| * The derived value must never falsely claim that no runtime request is | ||
| * needed, so every fallback is conservative: pages that carry no `u` | ||
| * (legacy render paths) forward an already-resolved `true`. Unlike the | ||
| * build-constant prefetch hints (including the tree-level | ||
| * ShouldAttemptStaticPrefetch), this is computed per render and may change | ||
| * between responses for the same build — it reflects THIS response. | ||
| */ | ||
| needsRuntimeRequest: Promise<boolean>; | ||
| }; | ||
| export type SegmentPrefetch = { | ||
| rsc: React.ReactNode | null; | ||
| isPartial: boolean; | ||
| staleTime: number; | ||
| /** | ||
| * The set of params that this segment's output depends on. Used by the client | ||
| * cache to determine which entries can be reused across different param | ||
| * values. | ||
| * - `null` means vary params were not tracked (conservative: assume all | ||
| * params matter) | ||
| * - Empty set means no params were accessed (segment is reusable for any | ||
| * param values) | ||
| * Fulfilled once the segment is known to be fully static. A partial segment | ||
| * (dynamic holes a runtime request must fill) leaves this pending forever — | ||
| * the same way Flight encodes the holes themselves — so the client reads a | ||
| * pending `isPartial` as "partial". The fulfillment row, when there is one, | ||
| * flushes past the shell boundary, so a truncated shell decode also reads | ||
| * as partial: correct, since a shell has holes by construction. | ||
| * | ||
| * This monotonic pending → fulfilled encoding also serves as the | ||
| * per-segment half of the needs-runtime-request derivation — see | ||
| * `SegmentPrefetchResponse['needsRuntimeRequest']`. | ||
| */ | ||
| varyParams: Set<string> | null; | ||
| isPartial: Promise<void>; | ||
| /** | ||
| * The segment's stale time in seconds, forwarded as an async iterable for | ||
| * the same reason as the route-level `InitialRSCPayload.s`: its final value | ||
| * is only known late in the stream, and the async-iterable form survives a | ||
| * truncated/rewound shell decode (read via thenable status from the | ||
| * buffered response). The client takes the last yielded value. | ||
| */ | ||
| staleTime: AsyncIterable<number>; | ||
| /** | ||
| * The params this segment's own output depends on (not including the | ||
| * response-level root params — see `rootVaryParams`). Forwarded as an async | ||
| * iterable because, like the route-level response's params, the values are | ||
| * only known late in the stream. The client cache keys reusable entries on | ||
| * these. | ||
| * - `null`: not tracked; conservatively assume all params matter. | ||
| * - yields nothing: no params accessed; reusable for any param values. | ||
| */ | ||
| varyParams: VaryParamsIterable | null; | ||
| }; | ||
@@ -77,3 +155,19 @@ export declare function collectSegmentData(isCacheComponentsEnabled: boolean, fullPageDataBuffer: Buffer, staleTime: number, clientModules: ManifestNode, serverConsumerManifest: any, prefetchInlining: boolean, hints: PrefetchHints | null, isUpgradeableISRFallback: boolean): Promise<Map<SegmentRequestKey, Buffer>>; | ||
| * are output as separate entries vs. inlined into their parent. | ||
| * | ||
| * `shouldAttemptStaticPrefetch` (computed by the caller from the prerender's | ||
| * runtime-data tracking) is folded onto every node of the result, so the | ||
| * manifest delivers it to every response like the other hint bits. It's | ||
| * independent of the inlining feature: when `inlining` is false the sizing | ||
| * pass is skipped entirely — no inlining bits are emitted — and only the | ||
| * tree shape carrying the static-prefetch hint is built. | ||
| * | ||
| * Both kinds of hint have the same structure and the same lifetime — one | ||
| * bitmask per node of the route tree, measured once per build and constant | ||
| * for the deployment. They differ only in what they're derived from: the | ||
| * inlining bits from the size of each segment's encoded response, the | ||
| * static-prefetch bit from what the decoded body turned out to access. | ||
| */ | ||
| export declare function collectPrefetchHints(fullPageDataBuffer: Buffer, staleTime: number, clientModules: ManifestNode, serverConsumerManifest: any, maxSize: number, maxBundleSize: number): Promise<PrefetchHints>; | ||
| export declare function collectPrefetchHints(fullPageDataBuffer: Buffer, staleTime: number, clientModules: ManifestNode, serverConsumerManifest: any, inlining: { | ||
| maxSize: number; | ||
| maxBundleSize: number; | ||
| } | false, shouldAttemptStaticPrefetch: boolean): Promise<PrefetchHints>; |
@@ -25,8 +25,9 @@ /* eslint-disable @next/internal/no-ambiguous-jsx -- Bundled in entry-base so it gets the right JSX runtime. */ "use strict"; | ||
| const _approutertypes = require("../../shared/lib/app-router-types"); | ||
| const _varyparamsdecoding = require("../../shared/lib/segment-cache/vary-params-decoding"); | ||
| const _client = require("react-server-dom-webpack/client"); | ||
| const _static = require("react-server-dom-webpack/static"); | ||
| const _server = require("react-server-dom-webpack/server"); | ||
| const _nodewebstreamshelper = require("../stream-utils/node-web-streams-helper"); | ||
| const _segment = require("../../shared/lib/segment"); | ||
| const _scheduler = require("../../lib/scheduler"); | ||
| const _promisewithresolvers = require("../../shared/lib/promise-with-resolvers"); | ||
| const _segmentvalueencoding = require("../../shared/lib/segment-cache/segment-value-encoding"); | ||
@@ -77,4 +78,17 @@ const _createerrorhandler = require("./create-error-handler"); | ||
| // | ||
| // The warm-up decode also tells us the page's own shell byte boundary (its | ||
| // `a` field): a byte offset into fullPageDataBuffer marking the end of the | ||
| // page's shell stage, null if the shell is identical to the full static | ||
| // response, or undefined if the render wasn't staged (no shell exists). | ||
| // | ||
| // And it tells us whether the render accessed runtime data (cookies, | ||
| // headers, fallback params, searchParams, ...): the settled value of the | ||
| // page's embedded access flag (its `u` field). Conservatively true when | ||
| // the page carries no flag (legacy render paths) or the decode fails. | ||
| let pageShellByteLength = undefined; | ||
| let runtimeDataAccessed = true; | ||
| try { | ||
| await (0, _client.createFromReadableStream)((0, _nodewebstreamshelper.streamFromBuffer)(fullPageDataBuffer), { | ||
| const pagePayload = await (0, _client.createFromReadableStream)(// Use a stream that never closes so pending references (dynamic | ||
| // holes) can't error the decode. | ||
| createUnclosingPrefetchStream((0, _nodewebstreamshelper.streamFromBuffer)(fullPageDataBuffer)), { | ||
| findSourceMapURL, | ||
@@ -84,3 +98,45 @@ serverConsumerManifest | ||
| await (0, _scheduler.waitAtLeastOneReactRenderTask)(); | ||
| // `a` is a promise resolved mid-stream; the whole buffer is present, so | ||
| // it resolves. undefined means the render wasn't staged (no shell). | ||
| if (pagePayload.a !== undefined) { | ||
| pageShellByteLength = await pagePayload.a; | ||
| } | ||
| if (pagePayload.u !== undefined) { | ||
| runtimeDataAccessed = readRuntimeDataAccessed(pagePayload.u); | ||
| } | ||
| } catch {} | ||
| // All segment responses of a page share one decode of the page buffer, and | ||
| // one `release` promise that coordinates the two serialization stages: it | ||
| // resolves when the coordinator lets the shell-stage bytes settle into the | ||
| // rest of the page data (see renderSegmentPrefetch, which measures each | ||
| // response's shell boundary at that moment). Its resolved value is true | ||
| // when the page's shell is identical to its full static response — then so | ||
| // is every segment's, so each resolves `a` to null instead of a boundary. | ||
| // | ||
| // When the page has a real shell boundary the decode is staged: only the | ||
| // shell byte prefix is enqueued now, the rest held until the release. With | ||
| // no boundary there's nothing to stage on, so the whole buffer is decoded | ||
| // at once and the release is resolved eagerly (segment boundaries then fall | ||
| // out as 0 or null without any measurement). | ||
| const release = (0, _promisewithresolvers.createPromiseWithResolvers)(); | ||
| let pageDataStream; | ||
| if (typeof pageShellByteLength === 'number') { | ||
| const prefixLength = pageShellByteLength; | ||
| pageDataStream = new ReadableStream({ | ||
| async start (controller) { | ||
| // The shell byte prefix decodes to the page's shell variant: | ||
| // everything the staged page render serialized after its shell stage | ||
| // stays a pending reference until the release enqueues the rest. | ||
| controller.enqueue(fullPageDataBuffer.subarray(0, prefixLength)); | ||
| await release.promise; | ||
| controller.enqueue(fullPageDataBuffer.subarray(prefixLength)); | ||
| // Intentionally never closed, like createUnclosingPrefetchStream: | ||
| // the page stream may hold references that never resolve (dynamic | ||
| // holes), and Flight errors if the stream closes while any are pending. | ||
| } | ||
| }); | ||
| } else { | ||
| pageDataStream = createUnclosingPrefetchStream((0, _nodewebstreamshelper.streamFromBuffer)(fullPageDataBuffer)); | ||
| release.resolve(pageShellByteLength === null); | ||
| } | ||
| // Create an abort controller that we'll use to stop the stream. | ||
@@ -100,22 +156,48 @@ const abortController = new AbortController(); | ||
| const segmentTasks = []; | ||
| const { prelude: treeStream } = await (0, _static.prerender)(// RootTreePrefetch is not a valid return type for a React component, but | ||
| // we need to use a component so that when we decode the original stream | ||
| // inside of it, the side effects are transferred to the new stream. | ||
| // @ts-expect-error | ||
| /*#__PURE__*/ (0, _jsxruntime.jsx)(PrefetchTreeData, { | ||
| isClientParamParsingEnabled: isCacheComponentsEnabled, | ||
| fullPageDataBuffer: fullPageDataBuffer, | ||
| serverConsumerManifest: serverConsumerManifest, | ||
| clientModules: clientModules, | ||
| staleTime: staleTime, | ||
| segmentTasks: segmentTasks, | ||
| onCompletedProcessingRouteTree: onCompletedProcessingRouteTree, | ||
| prefetchInlining: prefetchInlining, | ||
| hints: hints, | ||
| isUpgradeableISRFallback: isUpgradeableISRFallback | ||
| }), clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError: onSegmentPrerenderError | ||
| }); | ||
| let treeStream; | ||
| try { | ||
| const prerenderResult = await (0, _static.prerender)(// RootTreePrefetch is not a valid return type for a React component, but | ||
| // we need to use a component so that when we decode the original stream | ||
| // inside of it, the side effects are transferred to the new stream. | ||
| // @ts-expect-error | ||
| /*#__PURE__*/ (0, _jsxruntime.jsx)(PrefetchTreeData, { | ||
| isClientParamParsingEnabled: isCacheComponentsEnabled, | ||
| pageDataStream: pageDataStream, | ||
| serverConsumerManifest: serverConsumerManifest, | ||
| clientModules: clientModules, | ||
| staleTime: staleTime, | ||
| segmentTasks: segmentTasks, | ||
| onCompletedProcessingRouteTree: onCompletedProcessingRouteTree, | ||
| prefetchInlining: prefetchInlining, | ||
| hints: hints, | ||
| isUpgradeableISRFallback: isUpgradeableISRFallback, | ||
| runtimeDataAccessed: runtimeDataAccessed, | ||
| shellStageRelease: release.promise | ||
| }), clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError: onSegmentPrerenderError | ||
| }); | ||
| treeStream = prerenderResult.prelude; | ||
| // The tree walk has spawned every segment render, each against the fully | ||
| // available shell prefix; one task later they've flushed their shells and | ||
| // are blocked on the release for the rest. | ||
| await (0, _scheduler.waitAtLeastOneReactRenderTask)(); | ||
| } catch (error) { | ||
| // The release still fires (finally below), so the spawned tasks run to | ||
| // completion — but the throw skips the Promise.all that observes them. | ||
| // Absorb their rejections so a failing task can't crash as an unhandled | ||
| // rejection and mask this error. | ||
| void Promise.allSettled(segmentTasks); | ||
| throw error; | ||
| } finally{ | ||
| // Start the second stage: settle the rest of the page data into the | ||
| // decode so each render can measure its boundary and finish. Runs on | ||
| // failure too, so a tree-render error can't strand the spawned tasks on | ||
| // a release that never comes. (false is inert here: a staged page's shell | ||
| // is always a strict prefix, and an unstaged release already resolved.) | ||
| // TODO: I don't think it's really necessary to unblock the spawned tasks. | ||
| // It's fine if they hang indefinitely; the tasks will be garbage collected. | ||
| release.resolve(false); | ||
| } | ||
| // Write the route tree to a special `/_tree` segment. | ||
@@ -126,5 +208,4 @@ const treeBuffer = await (0, _nodewebstreamshelper.streamToBuffer)(treeStream); | ||
| resultMap.set('/_full', fullPageDataBuffer); | ||
| // Now that we've finished rendering the route tree, all the segment tasks | ||
| // should have been spawned. Await them in parallel and write the segment | ||
| // prefetches to the result map. | ||
| // Await the segment tasks in parallel and write the segment prefetches to | ||
| // the result map. | ||
| let hasPageSegment = false; | ||
@@ -151,3 +232,3 @@ for (const [segmentPath, buffer] of (await Promise.all(segmentTasks))){ | ||
| } | ||
| async function collectPrefetchHints(fullPageDataBuffer, staleTime, clientModules, serverConsumerManifest, maxSize, maxBundleSize) { | ||
| async function collectPrefetchHints(fullPageDataBuffer, staleTime, clientModules, serverConsumerManifest, inlining, shouldAttemptStaticPrefetch) { | ||
| // Warm up the module cache, same as collectSegmentData. | ||
@@ -174,12 +255,36 @@ try { | ||
| const { buildId, flightRouterState, seedData, head } = flightData; | ||
| // Root params are emitted once at the top level; readVaryParams unions them | ||
| // into the head, and the iterable is threaded down so every segment below | ||
| // unions it too. | ||
| // The hints every node starts from. The static-prefetch-attempt hint is | ||
| // page-global (the tracking that feeds it is), so it goes on every node, | ||
| // non-propagating — the client reads it per segment, and the runtime | ||
| // hint merging walks the manifest tree node-by-node. | ||
| const baseHints = shouldAttemptStaticPrefetch ? _approutertypes.PrefetchHint.ShouldAttemptStaticPrefetch : 0; | ||
| if (inlining === false) { | ||
| // Prefetch inlining is disabled: nothing to measure, and no inlining | ||
| // bits may be emitted (the client would act on them even though the | ||
| // responses aren't bundled). Just mirror the route tree's shape with | ||
| // the base hints on every node. | ||
| return createUniformHintTree(flightRouterState, baseHints); | ||
| } | ||
| const { maxSize, maxBundleSize } = inlining; | ||
| // Root params are forwarded once at the top level of each segment | ||
| // response, same as the page response's own root vary params; the client | ||
| // unions them into each segment's set at read time. | ||
| const rootVaryParamsIterable = initialRSCPayload.r ?? null; | ||
| // The page's staleTime iterable, forwarded into each segment response. When | ||
| // Cache Components is off the page carries no `s`, so wrap the eager value. | ||
| const staleTimeIterable = initialRSCPayload.s ?? createStaleTimeIterable(staleTime); | ||
| // The page's runtime-data-access flag, forwarded into each segment | ||
| // response's `needsRuntimeRequest`. This pass only measures sizes, so a | ||
| // conservative already-resolved `true` stands in when the page carries | ||
| // no `u`. | ||
| const needsRuntimeRequest = initialRSCPayload.u ?? Promise.resolve(true); | ||
| // This pass only measures gzip sizes for inlining hints, so nothing is | ||
| // staged (each response's `a` falls out as the no-shell sentinel, 0), but | ||
| // the responses are byte-identical in shape to the real ones — the point | ||
| // of measuring. Pre-resolving false is the "nothing staged" release. | ||
| const shellStageRelease = Promise.resolve(false); | ||
| // Measure the head (metadata/viewport) gzip size so the main traversal | ||
| // can decide whether to inline it into a page's bundle. | ||
| const headVaryParams = (0, _varyparamsdecoding.readVaryParams)(initialRSCPayload.h, rootVaryParamsIterable); | ||
| const [, headBuffer] = await renderSegmentPrefetch(buildId, staleTime, head, _segmentvalueencoding.HEAD_REQUEST_KEY, headVaryParams, clientModules, null, // This pass only measures gzip sizes for inlining hints; fallback-ness | ||
| // doesn't affect size, so pass false. | ||
| false); | ||
| const [, headBuffer] = await renderSegmentPrefetch(buildId, staleTimeIterable, head, _segmentvalueencoding.HEAD_REQUEST_KEY, initialRSCPayload.h, rootVaryParamsIterable, clientModules, null, // Fallback-ness doesn't affect size, so pass false. | ||
| false, needsRuntimeRequest, shellStageRelease); | ||
| const headGzipSize = await getGzipSize(headBuffer); | ||
@@ -198,3 +303,3 @@ // Mutable accumulator: the first segment that accepts the head sets this | ||
| // Walk the tree with the parent-first, child-decides algorithm. | ||
| const { node } = await collectPrefetchHintsImpl(flightRouterState, buildId, staleTime, seedData, clientModules, _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY, null, maxSize, maxBundleSize, headGzipSize, headInlineState, subtreeHasRuntimePrefetch, rootVaryParamsIterable); | ||
| const { node } = await collectPrefetchHintsImpl(flightRouterState, buildId, staleTimeIterable, seedData, clientModules, _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY, null, baseHints, maxSize, maxBundleSize, headGzipSize, headInlineState, subtreeHasRuntimePrefetch, rootVaryParamsIterable, needsRuntimeRequest, shellStageRelease); | ||
| if (!headInlineState.inlined) { | ||
@@ -232,7 +337,9 @@ // No page could accept the head. Set HeadOutlined on the root so the | ||
| // parent) in a single pass. | ||
| async function collectPrefetchHintsImpl(route, buildId, staleTime, seedData, clientModules, // TODO: Consider persisting the computed requestKey into the hints output | ||
| async function collectPrefetchHintsImpl(route, buildId, staleTimeIterable, seedData, clientModules, // TODO: Consider persisting the computed requestKey into the hints output | ||
| // so it doesn't need to be recomputed during the build. This might also | ||
| // suggest renaming prefetch-hints.json to something like | ||
| // segment-manifest.json, since it would contain more than just hints. | ||
| requestKey, parentGzipSize, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable) { | ||
| requestKey, parentGzipSize, // Hints every node starts from (the page-global static-prefetch-attempt | ||
| // hint); the inlining bits computed here are OR'd on top. | ||
| baseHints, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable, needsRuntimeRequest, shellStageRelease) { | ||
| // Check if static prefetching is disabled for this segment (runtime | ||
@@ -250,5 +357,4 @@ // prefetch or instant = false). Such segments act as transparent | ||
| if (!isStaticPrefetchDisabled && seedData !== null) { | ||
| const varyParams = (0, _varyparamsdecoding.readVaryParams)(seedData[4], rootVaryParamsIterable); | ||
| const [, buffer] = await renderSegmentPrefetch(buildId, staleTime, seedData[0], requestKey, varyParams, clientModules, null, // Size-measurement pass only; fallback-ness is irrelevant here. | ||
| false); | ||
| const [, buffer] = await renderSegmentPrefetch(buildId, staleTimeIterable, seedData[0], requestKey, seedData[4], rootVaryParamsIterable, clientModules, null, // Size-measurement pass only; fallback-ness is irrelevant here. | ||
| false, needsRuntimeRequest, shellStageRelease); | ||
| currentGzipSize = await getGzipSize(buffer); | ||
@@ -290,4 +396,4 @@ } | ||
| const sizeToOfferChild = isStaticPrefetchDisabled ? parentGzipSize : sizeToInline; | ||
| const childResult = await collectPrefetchHintsImpl(childRoute, buildId, staleTime, childSeedData, clientModules, childRequestKey, // Once a child has accepted us, stop offering to remaining siblings. | ||
| didInlineIntoChild ? null : sizeToOfferChild, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable); | ||
| const childResult = await collectPrefetchHintsImpl(childRoute, buildId, staleTimeIterable, childSeedData, clientModules, childRequestKey, // Once a child has accepted us, stop offering to remaining siblings. | ||
| didInlineIntoChild ? null : sizeToOfferChild, baseHints, maxSize, maxBundleSize, headGzipSize, headInlineState, routeHasRuntimePrefetch, rootVaryParamsIterable, needsRuntimeRequest, shellStageRelease); | ||
| if (slots === null) { | ||
@@ -318,3 +424,3 @@ slots = {}; | ||
| // data is included in the accepting child's response instead. | ||
| let hints = 0; | ||
| let hints = baseHints; | ||
| if (didInlineIntoChild) { | ||
@@ -401,2 +507,23 @@ hints |= _approutertypes.PrefetchHint.InlinedIntoChild; | ||
| } | ||
| // Mirrors the route tree's shape with the same hints on every node. Used by | ||
| // collectPrefetchHints when prefetch inlining is disabled: there are no sizes | ||
| // to measure, but the static-prefetch-attempt hint still needs a manifest | ||
| // tree — the client reads the bit per node, and the runtime hint merging | ||
| // (createFlightRouterStateFromLoaderTree) walks the manifest tree in parallel | ||
| // with the loader tree, so a bit that's missing from a node never reaches the | ||
| // corresponding segment. | ||
| function createUniformHintTree(route, hints) { | ||
| let slots = null; | ||
| const children = route[1]; | ||
| for(const parallelRouteKey in children){ | ||
| if (slots === null) { | ||
| slots = {}; | ||
| } | ||
| slots[parallelRouteKey] = createUniformHintTree(children[parallelRouteKey], hints); | ||
| } | ||
| return { | ||
| hints, | ||
| slots | ||
| }; | ||
| } | ||
| // We use gzip size rather than raw size because it better reflects the actual | ||
@@ -416,3 +543,3 @@ // transfer cost. The inlining trade-off is about whether the overhead of an | ||
| } | ||
| async function PrefetchTreeData({ isClientParamParsingEnabled, fullPageDataBuffer, serverConsumerManifest, clientModules, staleTime, segmentTasks, onCompletedProcessingRouteTree, prefetchInlining, hints, isUpgradeableISRFallback }) { | ||
| async function PrefetchTreeData({ isClientParamParsingEnabled, pageDataStream, serverConsumerManifest, clientModules, staleTime, segmentTasks, onCompletedProcessingRouteTree, prefetchInlining, hints, isUpgradeableISRFallback, runtimeDataAccessed, shellStageRelease }) { | ||
| // We're currently rendering a Flight response for the route tree prefetch. | ||
@@ -423,3 +550,9 @@ // Inside this component, decode the Flight stream for the whole page. This is | ||
| // TODO: React needs a better way to do this. Needed for Server Actions, too. | ||
| const initialRSCPayload = await (0, _client.createFromReadableStream)(createUnclosingPrefetchStream((0, _nodewebstreamshelper.streamFromBuffer)(fullPageDataBuffer)), { | ||
| // | ||
| // This is the decode that everything downstream reads from: the route tree | ||
| // walk below and, through it, every segment task. When staged, the values | ||
| // extracted here hold pending references at the param-dependent holes; the | ||
| // shell byte prefix carries the full router tree and seed-data skeleton, so | ||
| // the root resolves from the prefix alone (the rest arrives at the release). | ||
| const initialRSCPayload = await (0, _client.createFromReadableStream)(pageDataStream, { | ||
| findSourceMapURL, | ||
@@ -433,9 +566,14 @@ serverConsumerManifest | ||
| const { buildId, flightRouterState, seedData, head } = flightData; | ||
| // Root params are emitted once at the top level; readVaryParams unions them | ||
| // into the head, and the iterable is threaded down so every segment below | ||
| // unions it too. The iterables should be drained to completion by now (the | ||
| // stream is buffered); a hanging one reads as the params yielded so far. | ||
| // Root params are forwarded once at the top level of each segment | ||
| // response, same as the page response's own root vary params; the client | ||
| // unions them into each segment's set at read time. | ||
| const rootVaryParamsIterable = initialRSCPayload.r ?? null; | ||
| // Extract the head vary params from the decoded response. | ||
| const headVaryParams = (0, _varyparamsdecoding.readVaryParams)(initialRSCPayload.h, rootVaryParamsIterable); | ||
| // The page's staleTime iterable, forwarded into each segment response. When | ||
| // Cache Components is off the page carries no `s`, so wrap the eager value. | ||
| const staleTimeIterable = initialRSCPayload.s ?? createStaleTimeIterable(staleTime); | ||
| // The page's runtime-data-access flag, forwarded into each segment | ||
| // response's `needsRuntimeRequest`. When the page carries no `u` (e.g. | ||
| // legacy render paths), wrap the flag the caller read from the warm-up | ||
| // decode in an already-resolved promise. | ||
| const needsRuntimeRequest = initialRSCPayload.u ?? Promise.resolve(runtimeDataAccessed); | ||
| // Only applies when prefetch inlining is enabled — the client doesn't | ||
@@ -450,10 +588,10 @@ // know to look for the head inside a page's response otherwise. | ||
| rsc: head, | ||
| varyParams: headVaryParams, | ||
| varyParams: initialRSCPayload.h, | ||
| next: null | ||
| } : null; | ||
| const tree = collectSegmentDataImpl(isClientParamParsingEnabled, flightRouterState, buildId, staleTime, seedData, clientModules, _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY, segmentTasks, prefetchInlining, hints, null, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback); | ||
| const tree = collectSegmentDataImpl(isClientParamParsingEnabled, flightRouterState, buildId, staleTimeIterable, seedData, clientModules, _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY, segmentTasks, prefetchInlining, hints, null, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease); | ||
| // Spawn a task to produce a prefetch response for the "head" segment, | ||
| // unless it was inlined into a page's bundle. | ||
| if (!headIsInlined) { | ||
| segmentTasks.push((0, _scheduler.waitAtLeastOneReactRenderTask)().then(()=>renderSegmentPrefetch(buildId, staleTime, head, _segmentvalueencoding.HEAD_REQUEST_KEY, headVaryParams, clientModules, null, isUpgradeableISRFallback))); | ||
| segmentTasks.push((0, _scheduler.waitAtLeastOneReactRenderTask)().then(()=>renderSegmentPrefetch(buildId, staleTimeIterable, head, _segmentvalueencoding.HEAD_REQUEST_KEY, initialRSCPayload.h, rootVaryParamsIterable, clientModules, null, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease))); | ||
| } | ||
@@ -474,3 +612,3 @@ // Notify the abort controller that we're done processing the route tree. | ||
| } | ||
| function collectSegmentDataImpl(isClientParamParsingEnabled, route, buildId, staleTime, seedData, clientModules, requestKey, segmentTasks, prefetchInlining, hintTree, parentBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback) { | ||
| function collectSegmentDataImpl(isClientParamParsingEnabled, route, buildId, staleTimeIterable, seedData, clientModules, requestKey, segmentTasks, prefetchInlining, hintTree, parentBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease) { | ||
| // Union the hints already embedded in the FlightRouterState with the | ||
@@ -488,5 +626,5 @@ // separately-computed build-time hints. During the initial build, the | ||
| const prefetchHints = ((route[4] ?? 0) | (hintTree !== null ? hintTree.hints : 0)) & ~_approutertypes.PrefetchHint.InliningHintsStale; | ||
| // Determine which params this segment varies on, unioning in the | ||
| // response-level root params. | ||
| const varyParams = (0, _varyparamsdecoding.readVaryParams)(seedData !== null ? seedData[4] : null, rootVaryParamsIterable); | ||
| // The params this segment's own output varies on, forwarded into its | ||
| // response as-is. Root params are forwarded separately, once per response. | ||
| const varyParams = seedData !== null ? seedData[4] : null; | ||
| // If static prefetching is disabled for this segment (runtime prefetch or | ||
@@ -531,3 +669,3 @@ // instant = false), it still participates in the bundle chain but with | ||
| } | ||
| segmentTasks.push((0, _scheduler.waitAtLeastOneReactRenderTask)().then(()=>renderSegmentPrefetch(buildId, staleTime, rsc, requestKey, varyParams, clientModules, bundle, isUpgradeableISRFallback))); | ||
| segmentTasks.push((0, _scheduler.waitAtLeastOneReactRenderTask)().then(()=>renderSegmentPrefetch(buildId, staleTimeIterable, rsc, requestKey, varyParams, rootVaryParamsIterable, clientModules, bundle, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease))); | ||
| } | ||
@@ -547,3 +685,3 @@ // childBundle stays null — reset the accumulator for children. | ||
| const childHintTree = hintTree !== null && hintTree.slots !== null ? hintTree.slots[parallelRouteKey] ?? null : null; | ||
| const childTree = collectSegmentDataImpl(isClientParamParsingEnabled, childRoute, buildId, staleTime, childSeedData, clientModules, childRequestKey, segmentTasks, prefetchInlining, childHintTree, childBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback); | ||
| const childTree = collectSegmentDataImpl(isClientParamParsingEnabled, childRoute, buildId, staleTimeIterable, childSeedData, clientModules, childRequestKey, segmentTasks, prefetchInlining, childHintTree, childBundle, headBundle, rootVaryParamsIterable, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease); | ||
| if (slotMetadata === null) { | ||
@@ -579,90 +717,201 @@ slotMetadata = {}; | ||
| } | ||
| async function renderSegmentPrefetch(buildId, staleTime, rsc, requestKey, varyParams, clientModules, bundle, isUpgradeableISRFallback) { | ||
| // Build the SegmentPrefetch for the terminal (requested) segment. | ||
| // The terminal always has non-null rsc data — disabled segments are | ||
| // skipped by the caller and don't reach this function. | ||
| const selfPrefetch = { | ||
| /** | ||
| * Renders one segment prefetch response, and with it a shell byte boundary | ||
| * (`a`) — the per-segment analogue of the route-level `a`. The boundary lets a | ||
| * client later truncate the buffered response and re-decode the prefix into | ||
| * the segment's shell variant (param-dependent content reduced to pending | ||
| * references) without a second request. | ||
| * | ||
| * That boundary is the whole reason this isn't a plain re-serialize. A shell | ||
| * is a temporal property of the staged page render, already collapsed by the | ||
| * time the page stream is decoded, so it can't be recovered from the settled | ||
| * values. Instead the response is serialized against a staged decode of the | ||
| * page (the caller drip-feeds it in two stages): the shell rows flush first, | ||
| * and the byte count when the rest is released is the boundary. | ||
| * | ||
| * Uses the streaming renderer, not `prerender`, because the boundary must be | ||
| * observed mid-stream — `prerender` only exposes its prelude once finished. | ||
| */ async function renderSegmentPrefetch(buildId, staleTime, rsc, requestKey, varyParams, rootVaryParams, clientModules, bundle, isUpgradeableISRFallback, needsRuntimeRequest, shellStageRelease) { | ||
| const streamInfoStage = (0, _promisewithresolvers.createPromiseWithResolvers)(); | ||
| // Build the data array by walking the bundle list, terminal (requested) | ||
| // segment first. Always an array, even for a single segment; the terminal | ||
| // always has non-null rsc — disabled segments are skipped by the caller. | ||
| const data = []; | ||
| let node = { | ||
| rsc, | ||
| isPartial: await isPartialRSCData(rsc, clientModules), | ||
| staleTime, | ||
| varyParams | ||
| varyParams, | ||
| next: bundle | ||
| }; | ||
| // Build the data array. Always an array, even for a single segment. | ||
| const data = [ | ||
| selfPrefetch | ||
| ]; | ||
| if (bundle !== null) { | ||
| // Walk the bundle linked list and append each entry to the array. | ||
| let node = bundle; | ||
| while(node !== null){ | ||
| if (node.rsc !== null) { | ||
| data.push({ | ||
| rsc: node.rsc, | ||
| isPartial: await isPartialRSCData(node.rsc, clientModules), | ||
| staleTime, | ||
| varyParams: node.varyParams | ||
| while(node !== null){ | ||
| const elementRsc = node.rsc; | ||
| if (elementRsc === null) { | ||
| // Static prefetching disabled (runtime prefetch or instant=false): a | ||
| // null placeholder keeps the array aligned with the client's bundle | ||
| // list, which skips a cache entry for the slot. | ||
| data.push(null); | ||
| } else { | ||
| // We can determine if a segment contains only partial data if it takes | ||
| // longer than a task to encode, because dynamic data is encoded as an | ||
| // infinite promise. We must do this in a separate Flight prerender from | ||
| // the one that actually generates the prefetch stream because we need | ||
| // to include the result in the stream itself. | ||
| const contentIsComplete = new Promise(async (resolve)=>{ | ||
| // Wait for the input stream to be fully unblocked before checking if | ||
| // the data can be decoded synchronously. | ||
| await streamInfoStage.promise; | ||
| // If the data is fully static, this will resolve synchronously. | ||
| // Otherwise, the promise stays unresolved forever, and so does | ||
| // whatever field it's encoded into in the outer response. | ||
| await (0, _static.prerender)(elementRsc, clientModules, { | ||
| filterStackFrame, | ||
| onError () {} | ||
| }); | ||
| } else { | ||
| // This segment has static prefetching disabled (runtime prefetch | ||
| // or instant = false). Emit null as a placeholder so the array | ||
| // indices stay aligned with the client's SegmentBundle linked | ||
| // list. The client will skip creating a cache entry for this slot. | ||
| data.push(null); | ||
| } | ||
| node = node.next; | ||
| resolve(); | ||
| }); | ||
| data.push({ | ||
| rsc: elementRsc, | ||
| isPartial: contentIsComplete, | ||
| staleTime, | ||
| varyParams: node.varyParams | ||
| }); | ||
| } | ||
| node = node.next; | ||
| } | ||
| const responseKey = requestKey === _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY ? '/_index' : requestKey; | ||
| // `a` (see SegmentPrefetchResponse['a']) is resolved below, once the shell | ||
| // stage's bytes have been counted. | ||
| let totalByteLength = 0; | ||
| const shellByteOffset = (0, _promisewithresolvers.createPromiseWithResolvers)(); | ||
| // Wrap in the response envelope with the build ID at the top level. | ||
| // isUpgradeableISRFallback tells the client whether this came from a fallback shell | ||
| // render (so it knows to retry — a more complete version may become | ||
| // available once the server's background regeneration finishes). | ||
| const payload = { | ||
| buildId: buildId ?? '', | ||
| data, | ||
| isUpgradeableISRFallback | ||
| isUpgradeableISRFallback, | ||
| a: shellByteOffset.promise, | ||
| rootVaryParams, | ||
| needsRuntimeRequest | ||
| }; | ||
| // Since all we're doing is decoding and re-encoding a cached prerender, if | ||
| // it takes longer than a microtask, it must because of hanging promises | ||
| // caused by dynamic data. Abort the stream at the end of the current task. | ||
| const abortController = new AbortController(); | ||
| (0, _scheduler.waitAtLeastOneReactRenderTask)().then(()=>abortController.abort()); | ||
| const { prelude: segmentStream } = await (0, _static.prerender)(payload, clientModules, { | ||
| const segmentStream = (0, _server.renderToReadableStream)(payload, clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError: onSegmentPrerenderError | ||
| onError (error) { | ||
| if (abortController.signal.aborted) { | ||
| // Expected: aborting the render "errors" every reference that is | ||
| // still pending, i.e. the dynamic holes. The corresponding error | ||
| // rows are discarded below. | ||
| return undefined; | ||
| } | ||
| return onSegmentPrerenderError(error); | ||
| } | ||
| }); | ||
| const segmentBuffer = await (0, _nodewebstreamshelper.streamToBuffer)(segmentStream); | ||
| if (requestKey === _segmentvalueencoding.ROOT_SEGMENT_REQUEST_KEY) { | ||
| return [ | ||
| '/_index', | ||
| segmentBuffer | ||
| ]; | ||
| // Consume the stream as it's emitted, counting bytes so the shell boundary | ||
| // can be measured. Reads settle within a microtask of each enqueue, so by | ||
| // the time the release resolves (in a task after the renderer's last | ||
| // flush), every byte the renderer has emitted has been counted. | ||
| const reader = segmentStream.getReader(); | ||
| const chunksPromise = new Promise(async (resolve)=>{ | ||
| const chunks = []; | ||
| while(true){ | ||
| const { done, value } = await reader.read(); | ||
| if (done) { | ||
| break; | ||
| } | ||
| if (abortController.signal.aborted) { | ||
| continue; | ||
| } | ||
| chunks.push(value); | ||
| totalByteLength += value.byteLength; | ||
| } | ||
| resolve(chunks); | ||
| }); | ||
| // The release's value is true when the page's shell is its entire static | ||
| // response — then so is every segment's, so `a` is null (no separate shell | ||
| // to extract). Otherwise we measure. | ||
| const shellIsFullResponse = await shellStageRelease; | ||
| // The shell stage is complete: everything the render can emit from the shell | ||
| // prefix has flushed, so this is the shell's byte length. | ||
| const byteLengthAfterShellStage = totalByteLength; | ||
| // Wait one task for the rest of the segment data (past the page's own shell | ||
| // boundary) to flush, per the timing rule: one macrotask after the release | ||
| // enqueues it into the input decode, the render has emitted all of it. | ||
| await (0, _scheduler.waitAtLeastOneReactRenderTask)(); | ||
| // Resolve `a`: null when the page said its shell is the whole response | ||
| // (shellIsFullResponse) — then so is every segment's. Otherwise resolve the | ||
| // measured boundary, even if no segment *content* follows it: the | ||
| // stage-dependent metadata (`staleTime`, `needsRuntimeRequest`) always | ||
| // lands its post-shell values and completion rows after this point, so a | ||
| // truncated decode is meaningful for every segment of a staged page. When | ||
| // the page wasn't staged at all, the release resolved before any bytes | ||
| // flushed and the measured boundary falls out as 0, the "no shell" | ||
| // sentinel. | ||
| if (shellIsFullResponse) { | ||
| shellByteOffset.resolve(null); | ||
| } else { | ||
| return [ | ||
| requestKey, | ||
| segmentBuffer | ||
| ]; | ||
| shellByteOffset.resolve(byteLengthAfterShellStage); | ||
| } | ||
| // Now write the stream metadata (`a`, the `isPartial` promises, and a | ||
| // post-shell `needsRuntimeRequest` resolution). This is gated behind | ||
| // streamInfoStage so it lands strictly after the boundary measurement | ||
| // above — the post-shell values must not count as (or leak into) the | ||
| // shell prefix. | ||
| streamInfoStage.resolve(); | ||
| // Wait for the metadata rows to flush before halting — two macrotasks, | ||
| // each a distinct hop: | ||
| // 1. streamInfoStage unblocks the completeness probe renders; a static | ||
| // segment's probe resolves within this task (a partial one never does, | ||
| // which is how it stays pending → read as partial). | ||
| // 2. those resolutions (and the already-resolved `a`) ping the render, | ||
| // which emits their rows; the consumer reads that chunk here. | ||
| // Halting after only the first hop would drop the not-yet-flushed metadata. | ||
| await (0, _scheduler.waitAtLeastOneReactRenderTask)(); | ||
| await (0, _scheduler.waitAtLeastOneReactRenderTask)(); | ||
| // We're done writing, so we can abort the stream. | ||
| abortController.abort(); | ||
| return [ | ||
| responseKey, | ||
| Buffer.concat(await chunksPromise) | ||
| ]; | ||
| } | ||
| async function isPartialRSCData(rsc, clientModules) { | ||
| // We can determine if a segment contains only partial data if it takes longer | ||
| // than a task to encode, because dynamic data is encoded as an infinite | ||
| // promise. We must do this in a separate Flight prerender from the one that | ||
| // actually generates the prefetch stream because we need to include | ||
| // `isPartial` in the stream itself. | ||
| let isPartial = false; | ||
| const abortController = new AbortController(); | ||
| (0, _scheduler.waitAtLeastOneReactRenderTask)().then(()=>{ | ||
| // If we haven't yet finished the outer task, then it must be because we | ||
| // accessed dynamic data. | ||
| isPartial = true; | ||
| abortController.abort(); | ||
| }); | ||
| await (0, _static.prerender)(rsc, clientModules, { | ||
| filterStackFrame, | ||
| signal: abortController.signal, | ||
| onError () {} | ||
| }); | ||
| return isPartial; | ||
| /** | ||
| * Reads the page's runtime-data-access flag (the payload's `u`) from a decode | ||
| * of the fully-settled page buffer. Because every byte is present, the | ||
| * promise's row (if the render emitted one) is already visible on its | ||
| * thenable status, so this never blocks — the same trick the client cache | ||
| * uses to read staleTime from a buffered response. | ||
| * | ||
| * - fulfilled: the recorded flag. | ||
| * - pending: `false`. A successful render always settles the flag (prerender | ||
| * completion resolves `false`), so a pending row can only appear in an | ||
| * aborted render's buffer, where it means no access was recorded before | ||
| * the abort. | ||
| * - rejected: `true`, conservatively — an abort errors rows that were still | ||
| * pending when it happened. | ||
| */ function readRuntimeDataAccessed(runtimeDataAccessed) { | ||
| const promise = runtimeDataAccessed; | ||
| // Force Flight to unwrap a received-but-not-yet-settled row. | ||
| promise.then(ignoreChunk, ignoreChunk); | ||
| switch(promise.status){ | ||
| case 'fulfilled': | ||
| return promise.value === true; | ||
| case 'rejected': | ||
| return true; | ||
| case undefined: | ||
| default: | ||
| return false; | ||
| } | ||
| } | ||
| function ignoreChunk() {} | ||
| // Wraps a known staleTime value in the same async-iterable shape as the page | ||
| // response's `s`, so segment responses carry staleTime uniformly (and | ||
| // rewindably) whether or not Cache Components supplied a real `s` iterable. | ||
| // Re-consumable: each consumer gets a fresh generator (one segment response's | ||
| // render, and there can be several). | ||
| function createStaleTimeIterable(staleTime) { | ||
| return { | ||
| async *[Symbol.asyncIterator] () { | ||
| yield staleTime; | ||
| } | ||
| }; | ||
| } | ||
| function createUnclosingPrefetchStream(originalFlightStream) { | ||
@@ -669,0 +918,0 @@ // When PPR is enabled, prefetch streams may contain references that never |
@@ -342,2 +342,10 @@ /** | ||
| function abortAndThrowOnSynchronousRequestDataAccess(route, expression, errorWithStack, prerenderStore) { | ||
| // The synchronously accessed request data would have been available during | ||
| // a runtime prerender, which would have rendered past this point instead of | ||
| // aborting — so a runtime prefetch would produce more content than this | ||
| // render. Record that, same as when request data access creates a hanging | ||
| // promise (see makeRuntimeHangingPromise). Unlike | ||
| // `abortOnSynchronousPlatformIOAccess`, which aborts a runtime prerender | ||
| // all the same and therefore must not record anything. | ||
| (0, _dynamicrenderingutils.trackRuntimeDataAccessed)(prerenderStore); | ||
| const prerenderSignal = prerenderStore.controller.signal; | ||
@@ -344,0 +352,0 @@ if (prerenderSignal.aborted === false) { |
@@ -254,3 +254,3 @@ "use strict"; | ||
| const promise = process.env.NODE_ENV === 'development' ? makeDevtoolsIOPromiseFromIOTrigger(stagePromise, displayName, resolvedValue) : stagePromise.then(()=>resolvedValue); | ||
| // Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked. | ||
| // Analogously to `makeDynamicHangingPromise`, we might reject this promise if the signal is invoked. | ||
| // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it). | ||
@@ -257,0 +257,0 @@ // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/app-render/staged-rendering.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n Before = 1,\n //\n ShellStatic = 11,\n Static = 13,\n //\n ShellRuntime = 21,\n Runtime = 23,\n //\n Dynamic = 30,\n //\n Abandoned = 40,\n}\n\nexport type AdvanceableRenderStage = Exclude<\n RenderStage,\n RenderStage.Before | RenderStage.Abandoned\n>\n\nexport const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [\n RenderStage.ShellStatic,\n RenderStage.Static,\n //\n RenderStage.ShellRuntime,\n RenderStage.Runtime,\n //\n RenderStage.Dynamic,\n]\n\nexport function getNextStage(\n stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>\n) {\n return RENDER_STAGE_ADVANCE_ORDER[\n RENDER_STAGE_ADVANCE_ORDER.indexOf(stage) + 1\n ]\n}\n\nexport function isAdvanceableRenderStage(\n stage: RenderStage\n): stage is AdvanceableRenderStage {\n return RenderStage.Before < stage && stage <= RenderStage.Dynamic\n}\n\nexport enum SyncIOMode {\n /** Sync IO does not error in any stage. */\n Untracked = 1,\n /** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */\n AllowedInRuntimeOrDynamic = 2,\n /** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */\n AllowedInDynamic = 3,\n}\n\nexport class StagedRenderingController {\n private abortSignal: AbortSignal | null\n private abandonController: AbortController | null\n private syncIOMode: SyncIOMode\n public readonly finalStage: AdvanceableRenderStage | null\n\n currentStage: RenderStage = RenderStage.Before\n\n syncInterruptReason: Error | null = null\n\n triggers: Record<AdvanceableRenderStage, StageTrigger> = {\n [RenderStage.ShellStatic]: createStageTrigger(),\n [RenderStage.Static]: createStageTrigger(),\n //\n [RenderStage.ShellRuntime]: createStageTrigger(),\n [RenderStage.Runtime]: createStageTrigger(),\n //\n [RenderStage.Dynamic]: createStageTrigger(),\n }\n\n constructor({\n abortSignal,\n abandonController,\n syncIO,\n finalStage,\n }: {\n abortSignal: AbortSignal | null\n abandonController: AbortController | null\n syncIO: SyncIOMode\n finalStage: AdvanceableRenderStage | null\n }) {\n this.abortSignal = abortSignal\n this.abandonController = abandonController\n this.syncIOMode = syncIO\n this.finalStage = finalStage\n\n if (abortSignal) {\n abortSignal.addEventListener(\n 'abort',\n () => {\n // Reject all stage promises that haven't already been resolved.\n // `cancelStageTrigger` is a noop if the trigger already resolved.\n const { reason } = abortSignal\n for (const trigger of Object.values(this.triggers)) {\n cancelStageTrigger(trigger, reason)\n }\n },\n { once: true }\n )\n }\n\n if (abandonController) {\n abandonController.signal.addEventListener(\n 'abort',\n () => {\n this.abandonRender()\n },\n { once: true }\n )\n }\n }\n\n onStage(stage: AdvanceableRenderStage, callback: () => void) {\n addSyncTriggerListener(this.triggers[stage], callback)\n }\n\n shouldTrackSyncInterrupt(): boolean {\n if (this.syncIOMode === SyncIOMode.Untracked) {\n return false\n }\n\n switch (this.currentStage) {\n case RenderStage.Before:\n // If we haven't started the render yet, it can't be interrupted.\n return false\n case RenderStage.ShellStatic:\n case RenderStage.Static:\n return true\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n switch (this.syncIOMode) {\n case SyncIOMode.AllowedInRuntimeOrDynamic: {\n // Before `partialPrefetching`: Sync IO only errors in static stages.\n return false\n }\n case SyncIOMode.AllowedInDynamic: {\n return true\n }\n }\n // NOT a fallthrough, but eslint doesn't understand that\n }\n case RenderStage.Dynamic:\n case RenderStage.Abandoned:\n return false\n default:\n this.currentStage satisfies never\n return false\n }\n }\n\n /** Note: only call this if `shouldTrackSyncInterrupt()` returned true */\n syncInterruptCurrentStageWithReason(reason: Error) {\n const { currentStage } = this\n if (\n currentStage === RenderStage.Before ||\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Not interruptible. Defensive noop.\n return\n }\n\n // If Sync IO occurs during an abandonable render, we trigger the abandon.\n // The abandon listener will call abandonRender which advances through\n // stages to let caches fill before marking as Abandoned.\n if (this.abandonController) {\n this.abandonController.abort()\n return\n }\n\n if (this.abortSignal) {\n // If this is an abortable render, we capture the interruption reason and stop advancing.\n // We don't release any more promises.\n // The caller is expected to abort the signal.\n this.syncInterruptReason = reason\n this.currentStage = RenderStage.Abandoned\n return\n }\n\n // If we're in a non-abandonable & non-abortable render,\n // we need to advance to the Dynamic stage and capture the interruption reason.\n // (in dev, this will be the restarted render)\n this.syncInterruptReason = reason\n this.advanceStage(RenderStage.Dynamic)\n }\n\n getSyncInterruptReason() {\n return this.syncInterruptReason\n }\n\n getStaticStageEndTime() {\n // The Static stage ends when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Static)].triggeredAt ?? Infinity\n )\n }\n\n getRuntimeStageEndTime() {\n // The Runtime stage ended when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Runtime)].triggeredAt ?? Infinity\n )\n }\n\n private abandonRender() {\n // In staged rendering, only the initial render is abandonable.\n // We can abandon the initial render if\n // 1. We notice a cache miss, and need to wait for caches to fill\n // 2. A sync IO error occurs, and the render should be interrupted\n // (this might be a lazy intitialization of a module,\n // so we still want to restart in this case and see if it still occurs)\n // In either case, we'll be doing another render after this one,\n // so we only want to unblock the next stage, not Dynamic, because\n // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n\n const { currentStage } = this\n\n if (currentStage === RenderStage.Before) {\n throw new InvariantError(\n \"A render that hasn't started yet cannot be abandoned\"\n )\n }\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // We shouldn't ever trigger an abandon in these. Defensive noop.\n return\n }\n\n // Resolve all stages after the current one, up to runtime (excluding dynamic)\n const nextStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const dynamicStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(\n RenderStage.Dynamic\n )\n for (let i = nextStageIx; i < dynamicStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n\n this.currentStage = RenderStage.Abandoned\n }\n\n advanceStage(targetStage: AdvanceableRenderStage) {\n if (this.finalStage !== null && targetStage > this.finalStage) {\n throw new InvariantError(\n `Attempted to advance to stage ${RenderStage[targetStage]} but the render is limited to ${RenderStage[this.finalStage]}`\n )\n }\n const { currentStage } = this\n\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Terminal stages, nowhere left to advance.\n return\n }\n\n // If we're already at the target stage or beyond, do nothing.\n if (targetStage <= currentStage) {\n return\n }\n\n this.currentStage = targetStage\n\n // Resolve all stages between the current stage and the target.\n const nextStageIx =\n currentStage === RenderStage.Before\n ? 0\n : RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const targetStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(targetStage)\n for (let i = nextStageIx; i <= targetStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n }\n\n private resolveStage(stage: AdvanceableRenderStage) {\n fireStageTrigger(this.triggers[stage])\n }\n\n private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n return this.triggers[stage].promise\n }\n\n waitForStage(stage: AdvanceableRenderStage) {\n return this.getStagePromise(stage)\n }\n\n delayUntilStage<T>(\n stage: AdvanceableRenderStage,\n displayName: string | undefined,\n resolvedValue: T\n ): Promise<T> {\n const stagePromise = this.getStagePromise(stage)\n\n const promise =\n process.env.NODE_ENV === 'development'\n ? makeDevtoolsIOPromiseFromIOTrigger(\n stagePromise,\n displayName,\n resolvedValue\n )\n : stagePromise.then(() => resolvedValue)\n\n // Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked.\n // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n if (this.abortSignal) {\n promise.catch(ignoreReject)\n }\n return promise\n }\n}\n\nfunction ignoreReject() {}\n\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger<T>(\n ioTrigger: Promise<any>,\n displayName: string | undefined,\n resolvedValue: T\n): Promise<T> {\n // If we create a `new Promise` and give it a displayName\n // (with no userspace code above us in the stack)\n // React Devtools will use it as the IO cause when determining \"suspended by\".\n // In particular, it should shadow any inner IO that resolved/rejected the promise\n // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n const promise = new Promise<T>((resolve, reject) => {\n ioTrigger.then(resolve.bind(null, resolvedValue), reject)\n })\n if (displayName !== undefined) {\n // @ts-expect-error\n promise.displayName = displayName\n }\n return promise\n}\n\ntype StageTrigger = {\n state: 'pending' | 'triggered' | 'cancelled'\n triggeredAt: number | null\n promise: Promise<void>\n _listeners: Array<() => void>\n _resolvePromise: () => void\n _rejectPromise: (reason: unknown) => void\n}\n\nfunction addSyncTriggerListener(trigger: StageTrigger, listener: () => void) {\n if (trigger.state === 'pending') {\n trigger._listeners.push(listener)\n } else {\n listener()\n }\n}\n\nfunction createStageTrigger(): StageTrigger {\n const { promise, resolve, reject } = createPromiseWithResolvers<void>()\n return {\n state: 'pending',\n triggeredAt: null,\n promise,\n _listeners: [],\n _resolvePromise: resolve,\n _rejectPromise: reject,\n }\n}\n\nfunction fireStageTrigger(trigger: StageTrigger) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'triggered'\n trigger.triggeredAt = performance.now() + performance.timeOrigin\n try {\n const { _listeners: listeners } = trigger\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n listeners.length = 0\n } finally {\n trigger._resolvePromise()\n }\n}\n\nfunction cancelStageTrigger(trigger: StageTrigger, reason: unknown) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'cancelled'\n // we didn't trigger, so don't save `triggeredAt`.\n\n // We're not gonna fire the listeners, we may as well free them.\n trigger._listeners.length = 0\n\n // Suppress unhandled rejection warnings for promises that no one is awaiting.\n trigger.promise.catch(ignoreReject)\n trigger._rejectPromise(reason)\n}\n"],"names":["RENDER_STAGE_ADVANCE_ORDER","RenderStage","StagedRenderingController","SyncIOMode","getNextStage","isAdvanceableRenderStage","stage","indexOf","constructor","abortSignal","abandonController","syncIO","finalStage","currentStage","syncInterruptReason","triggers","createStageTrigger","syncIOMode","addEventListener","reason","trigger","Object","values","cancelStageTrigger","once","signal","abandonRender","onStage","callback","addSyncTriggerListener","shouldTrackSyncInterrupt","syncInterruptCurrentStageWithReason","abort","advanceStage","getSyncInterruptReason","getStaticStageEndTime","triggeredAt","Infinity","getRuntimeStageEndTime","InvariantError","nextStageIx","dynamicStageIx","i","resolveStage","targetStage","targetStageIx","fireStageTrigger","getStagePromise","promise","waitForStage","delayUntilStage","displayName","resolvedValue","stagePromise","process","env","NODE_ENV","makeDevtoolsIOPromiseFromIOTrigger","then","catch","ignoreReject","ioTrigger","Promise","resolve","reject","bind","undefined","listener","state","_listeners","push","createPromiseWithResolvers","_resolvePromise","_rejectPromise","performance","now","timeOrigin","listeners","length"],"mappings":";;;;;;;;;;;;;;;;;;;IAsBaA,0BAA0B;eAA1BA;;IAnBDC,WAAW;eAAXA;;IAoDCC,yBAAyB;eAAzBA;;IATDC,UAAU;eAAVA;;IAdIC,YAAY;eAAZA;;IAQAC,wBAAwB;eAAxBA;;;gCAxCe;sCACY;AAEpC,IAAA,AAAKJ,qCAAAA;;IAEV,EAAE;;;IAGF,EAAE;;;IAGF,EAAE;;IAEF,EAAE;;WAVQA;;AAmBL,MAAMD,6BAAuD;;;;;;CAQnE;AAEM,SAASI,aACdE,KAA2D;IAE3D,OAAON,0BAA0B,CAC/BA,2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AC/D,OAAO;QACLH,OAAO;QACPhC,aAAa;QACbY;QACAqB,YAAY,EAAE;QACdG,iBAAiBT;QACjBU,gBAAgBT;IAClB;AACF;AAEA,SAASlB,iBAAiB1B,OAAqB;IAC7C,IAAIA,QAAQgD,KAAK,KAAK,WAAW;QAC/B;IACF;IACAhD,QAAQgD,KAAK,GAAG;IAChBhD,QAAQgB,WAAW,GAAGsC,YAAYC,GAAG,KAAKD,YAAYE,UAAU;IAChE,IAAI;QACF,MAAM,EAAEP,YAAYQ,SAAS,EAAE,GAAGzD;QAClC,IAAK,IAAIsB,IAAI,GAAGA,IAAImC,UAAUC,MAAM,EAAEpC,IAAK;YACzCmC,SAAS,CAACnC,EAAE;QACd;QACAmC,UAAUC,MAAM,GAAG;IACrB,SAAU;QACR1D,QAAQoD,eAAe;IACzB;AACF;AAEA,SAASjD,mBAAmBH,OAAqB,EAAED,MAAe;IAChE,IAAIC,QAAQgD,KAAK,KAAK,WAAW;QAC/B;IACF;IACAhD,QAAQgD,KAAK,GAAG;IAChB,kDAAkD;IAElD,gEAAgE;IAChEhD,QAAQiD,UAAU,CAACS,MAAM,GAAG;IAE5B,8EAA8E;IAC9E1D,QAAQ4B,OAAO,CAACW,KAAK,CAACC;IACtBxC,QAAQqD,cAAc,CAACtD;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/app-render/staged-rendering.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n Before = 1,\n //\n ShellStatic = 11,\n Static = 13,\n //\n ShellRuntime = 21,\n Runtime = 23,\n //\n Dynamic = 30,\n //\n Abandoned = 40,\n}\n\nexport type AdvanceableRenderStage = Exclude<\n RenderStage,\n RenderStage.Before | RenderStage.Abandoned\n>\n\nexport const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [\n RenderStage.ShellStatic,\n RenderStage.Static,\n //\n RenderStage.ShellRuntime,\n RenderStage.Runtime,\n //\n RenderStage.Dynamic,\n]\n\nexport function getNextStage(\n stage: Exclude<AdvanceableRenderStage, RenderStage.Dynamic>\n) {\n return RENDER_STAGE_ADVANCE_ORDER[\n RENDER_STAGE_ADVANCE_ORDER.indexOf(stage) + 1\n ]\n}\n\nexport function isAdvanceableRenderStage(\n stage: RenderStage\n): stage is AdvanceableRenderStage {\n return RenderStage.Before < stage && stage <= RenderStage.Dynamic\n}\n\nexport enum SyncIOMode {\n /** Sync IO does not error in any stage. */\n Untracked = 1,\n /** Before `partialPrefetching`: Sync IO errors in static stages, and is allowed otherwise. */\n AllowedInRuntimeOrDynamic = 2,\n /** After `partialPrefetching`: Sync IO errors in all stages other than dynamic. */\n AllowedInDynamic = 3,\n}\n\nexport class StagedRenderingController {\n private abortSignal: AbortSignal | null\n private abandonController: AbortController | null\n private syncIOMode: SyncIOMode\n public readonly finalStage: AdvanceableRenderStage | null\n\n currentStage: RenderStage = RenderStage.Before\n\n syncInterruptReason: Error | null = null\n\n triggers: Record<AdvanceableRenderStage, StageTrigger> = {\n [RenderStage.ShellStatic]: createStageTrigger(),\n [RenderStage.Static]: createStageTrigger(),\n //\n [RenderStage.ShellRuntime]: createStageTrigger(),\n [RenderStage.Runtime]: createStageTrigger(),\n //\n [RenderStage.Dynamic]: createStageTrigger(),\n }\n\n constructor({\n abortSignal,\n abandonController,\n syncIO,\n finalStage,\n }: {\n abortSignal: AbortSignal | null\n abandonController: AbortController | null\n syncIO: SyncIOMode\n finalStage: AdvanceableRenderStage | null\n }) {\n this.abortSignal = abortSignal\n this.abandonController = abandonController\n this.syncIOMode = syncIO\n this.finalStage = finalStage\n\n if (abortSignal) {\n abortSignal.addEventListener(\n 'abort',\n () => {\n // Reject all stage promises that haven't already been resolved.\n // `cancelStageTrigger` is a noop if the trigger already resolved.\n const { reason } = abortSignal\n for (const trigger of Object.values(this.triggers)) {\n cancelStageTrigger(trigger, reason)\n }\n },\n { once: true }\n )\n }\n\n if (abandonController) {\n abandonController.signal.addEventListener(\n 'abort',\n () => {\n this.abandonRender()\n },\n { once: true }\n )\n }\n }\n\n onStage(stage: AdvanceableRenderStage, callback: () => void) {\n addSyncTriggerListener(this.triggers[stage], callback)\n }\n\n shouldTrackSyncInterrupt(): boolean {\n if (this.syncIOMode === SyncIOMode.Untracked) {\n return false\n }\n\n switch (this.currentStage) {\n case RenderStage.Before:\n // If we haven't started the render yet, it can't be interrupted.\n return false\n case RenderStage.ShellStatic:\n case RenderStage.Static:\n return true\n case RenderStage.ShellRuntime:\n case RenderStage.Runtime: {\n switch (this.syncIOMode) {\n case SyncIOMode.AllowedInRuntimeOrDynamic: {\n // Before `partialPrefetching`: Sync IO only errors in static stages.\n return false\n }\n case SyncIOMode.AllowedInDynamic: {\n return true\n }\n }\n // NOT a fallthrough, but eslint doesn't understand that\n }\n case RenderStage.Dynamic:\n case RenderStage.Abandoned:\n return false\n default:\n this.currentStage satisfies never\n return false\n }\n }\n\n /** Note: only call this if `shouldTrackSyncInterrupt()` returned true */\n syncInterruptCurrentStageWithReason(reason: Error) {\n const { currentStage } = this\n if (\n currentStage === RenderStage.Before ||\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Not interruptible. Defensive noop.\n return\n }\n\n // If Sync IO occurs during an abandonable render, we trigger the abandon.\n // The abandon listener will call abandonRender which advances through\n // stages to let caches fill before marking as Abandoned.\n if (this.abandonController) {\n this.abandonController.abort()\n return\n }\n\n if (this.abortSignal) {\n // If this is an abortable render, we capture the interruption reason and stop advancing.\n // We don't release any more promises.\n // The caller is expected to abort the signal.\n this.syncInterruptReason = reason\n this.currentStage = RenderStage.Abandoned\n return\n }\n\n // If we're in a non-abandonable & non-abortable render,\n // we need to advance to the Dynamic stage and capture the interruption reason.\n // (in dev, this will be the restarted render)\n this.syncInterruptReason = reason\n this.advanceStage(RenderStage.Dynamic)\n }\n\n getSyncInterruptReason() {\n return this.syncInterruptReason\n }\n\n getStaticStageEndTime() {\n // The Static stage ends when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Static)].triggeredAt ?? Infinity\n )\n }\n\n getRuntimeStageEndTime() {\n // The Runtime stage ended when the stage after it began.\n return (\n this.triggers[getNextStage(RenderStage.Runtime)].triggeredAt ?? Infinity\n )\n }\n\n private abandonRender() {\n // In staged rendering, only the initial render is abandonable.\n // We can abandon the initial render if\n // 1. We notice a cache miss, and need to wait for caches to fill\n // 2. A sync IO error occurs, and the render should be interrupted\n // (this might be a lazy intitialization of a module,\n // so we still want to restart in this case and see if it still occurs)\n // In either case, we'll be doing another render after this one,\n // so we only want to unblock the next stage, not Dynamic, because\n // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n\n const { currentStage } = this\n\n if (currentStage === RenderStage.Before) {\n throw new InvariantError(\n \"A render that hasn't started yet cannot be abandoned\"\n )\n }\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // We shouldn't ever trigger an abandon in these. Defensive noop.\n return\n }\n\n // Resolve all stages after the current one, up to runtime (excluding dynamic)\n const nextStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const dynamicStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(\n RenderStage.Dynamic\n )\n for (let i = nextStageIx; i < dynamicStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n\n this.currentStage = RenderStage.Abandoned\n }\n\n advanceStage(targetStage: AdvanceableRenderStage) {\n if (this.finalStage !== null && targetStage > this.finalStage) {\n throw new InvariantError(\n `Attempted to advance to stage ${RenderStage[targetStage]} but the render is limited to ${RenderStage[this.finalStage]}`\n )\n }\n const { currentStage } = this\n\n if (\n currentStage === RenderStage.Dynamic ||\n currentStage === RenderStage.Abandoned\n ) {\n // Terminal stages, nowhere left to advance.\n return\n }\n\n // If we're already at the target stage or beyond, do nothing.\n if (targetStage <= currentStage) {\n return\n }\n\n this.currentStage = targetStage\n\n // Resolve all stages between the current stage and the target.\n const nextStageIx =\n currentStage === RenderStage.Before\n ? 0\n : RENDER_STAGE_ADVANCE_ORDER.indexOf(currentStage) + 1\n const targetStageIx = RENDER_STAGE_ADVANCE_ORDER.indexOf(targetStage)\n for (let i = nextStageIx; i <= targetStageIx; i++) {\n this.resolveStage(RENDER_STAGE_ADVANCE_ORDER[i])\n }\n }\n\n private resolveStage(stage: AdvanceableRenderStage) {\n fireStageTrigger(this.triggers[stage])\n }\n\n private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n return this.triggers[stage].promise\n }\n\n waitForStage(stage: AdvanceableRenderStage) {\n return this.getStagePromise(stage)\n }\n\n delayUntilStage<T>(\n stage: AdvanceableRenderStage,\n displayName: string | undefined,\n resolvedValue: T\n ): Promise<T> {\n const stagePromise = this.getStagePromise(stage)\n\n const promise =\n process.env.NODE_ENV === 'development'\n ? makeDevtoolsIOPromiseFromIOTrigger(\n stagePromise,\n displayName,\n resolvedValue\n )\n : stagePromise.then(() => resolvedValue)\n\n // Analogously to `makeDynamicHangingPromise`, we might reject this promise if the signal is invoked.\n // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n if (this.abortSignal) {\n promise.catch(ignoreReject)\n }\n return promise\n }\n}\n\nfunction ignoreReject() {}\n\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger<T>(\n ioTrigger: Promise<any>,\n displayName: string | undefined,\n resolvedValue: T\n): Promise<T> {\n // If we create a `new Promise` and give it a displayName\n // (with no userspace code above us in the stack)\n // React Devtools will use it as the IO cause when determining \"suspended by\".\n // In particular, it should shadow any inner IO that resolved/rejected the promise\n // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n const promise = new Promise<T>((resolve, reject) => {\n ioTrigger.then(resolve.bind(null, resolvedValue), reject)\n })\n if (displayName !== undefined) {\n // @ts-expect-error\n promise.displayName = displayName\n }\n return promise\n}\n\ntype StageTrigger = {\n state: 'pending' | 'triggered' | 'cancelled'\n triggeredAt: number | null\n promise: Promise<void>\n _listeners: Array<() => void>\n _resolvePromise: () => void\n _rejectPromise: (reason: unknown) => void\n}\n\nfunction addSyncTriggerListener(trigger: StageTrigger, listener: () => void) {\n if (trigger.state === 'pending') {\n trigger._listeners.push(listener)\n } else {\n listener()\n }\n}\n\nfunction createStageTrigger(): StageTrigger {\n const { promise, resolve, reject } = createPromiseWithResolvers<void>()\n return {\n state: 'pending',\n triggeredAt: null,\n promise,\n _listeners: [],\n _resolvePromise: resolve,\n _rejectPromise: reject,\n }\n}\n\nfunction fireStageTrigger(trigger: StageTrigger) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'triggered'\n trigger.triggeredAt = performance.now() + performance.timeOrigin\n try {\n const { _listeners: listeners } = trigger\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n listeners.length = 0\n } finally {\n trigger._resolvePromise()\n }\n}\n\nfunction cancelStageTrigger(trigger: StageTrigger, reason: unknown) {\n if (trigger.state !== 'pending') {\n return\n }\n trigger.state = 'cancelled'\n // we didn't trigger, so don't save `triggeredAt`.\n\n // We're not gonna fire the listeners, we may as well free them.\n trigger._listeners.length = 0\n\n // Suppress unhandled rejection warnings for promises that no one is awaiting.\n trigger.promise.catch(ignoreReject)\n trigger._rejectPromise(reason)\n}\n"],"names":["RENDER_STAGE_ADVANCE_ORDER","RenderStage","StagedRenderingController","SyncIOMode","getNextStage","isAdvanceableRenderStage","stage","indexOf","constructor","abortSignal","abandonController","syncIO","finalStage","currentStage","syncInterruptReason","triggers","createStageTrigger","syncIOMode","addEventListener","reason","trigger","Object","values","cancelStageTrigger","once","signal","abandonRender","onStage","callback","addSyncTriggerListener","shouldTrackSyncInterrupt","syncInterruptCurrentStageWithReason","abort","advanceStage","getSyncInterruptReason","getStaticStageEndTime","triggeredAt","Infinity","getRuntimeStageEndTime","InvariantError","nextStageIx","dynamicStageIx","i","resolveStage","targetStage","targetStageIx","fireStageTrigger","getStagePromise","promise","waitForStage","delayUntilStage","displayName","resolvedValue","stagePromise","process","env","NODE_ENV","makeDevtoolsIOPromiseFromIOTrigger","then","catch","ignoreReject","ioTrigger","Promise","resolve","reject","bind","undefined","listener","state","_listeners","push","createPromiseWithResolvers","_resolvePromise","_rejectPromise","performance","now","timeOrigin","listeners","length"],"mappings":";;;;;;;;;;;;;;;;;;;IAsBaA,0BAA0B;eAA1BA;;IAnBDC,WAAW;eAAXA;;IAoDCC,yBAAyB;eAAzBA;;IATDC,UAAU;eAAVA;;IAdIC,YAAY;eAAZA;;IAQAC,wBAAwB;eAAxBA;;;gCAxCe;sCACY;AAEpC,IAAA,AAAKJ,qCAAAA;;IAEV,EAAE;;;IAGF,EAAE;;;IAGF,EAAE;;IAEF,EAAE;;WAVQA;;AAmBL,MAAMD,6BAAuD;;;;;;CAQnE;AAEM,SAASI,aACdE,KAA2D;IAE3D,OAAON,0BAA0B,CAC/BA,2BAA2BO,OAAO,CAACD,SAAS,EAC7C;AACH;AAEO,SAASD,yBACdC,KAAkB;IAElB,OAAOL,IAAqBK,SAASA;AACvC;AAEO,IAAA,AAAKH,oCAAAA;IACV,yCAAyC;IAEzC,4FAA4F;IAE5F,iFAAiF;WALvEA;;AASL,MAAMD;IAoBXM,YAAY,EACVC,WAAW,EACXC,iBAAiB,EACjBC,MAAM,EACNC,UAAU,EAMX,CAAE;aAxBHC;aAEAC,sBAAoC;aAEpCC,WAAyD;YACvD,IAAyB,EAAEC;YAC3B,IAAoB,EAAEA;YACtB,EAAE;YACF,IAA0B,EAAEA;YAC5B,IAAqB,EAAEA;YACvB,EAAE;YACF,IAAqB,EAAEA;QACzB;QAaE,IAAI,CAACP,WAAW,GAAGA;QACnB,IAAI,CAACC,iBAAiB,GAAGA;QACzB,IAAI,CAACO,UAAU,GAAGN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AAqB,EAAED,MAAe;IAChE,IAAIC,QAAQgD,KAAK,KAAK,WAAW;QAC/B;IACF;IACAhD,QAAQgD,KAAK,GAAG;IAChB,kDAAkD;IAElD,gEAAgE;IAChEhD,QAAQiD,UAAU,CAACS,MAAM,GAAG;IAE5B,8EAA8E;IAC9E1D,QAAQ4B,OAAO,CAACW,KAAK,CAACC;IACtBxC,QAAQqD,cAAc,CAACtD;AACzB","ignoreList":[0]} |
@@ -110,2 +110,51 @@ import type { AsyncLocalStorage } from 'async_hooks'; | ||
| readonly stagedRendering: StagedRenderingController | null; | ||
| /** | ||
| * When not null, records whether the render has accessed a data source | ||
| * that hangs during a static prerender but would resolve during a runtime | ||
| * prerender — cookies, headers, fallback params, searchParams, and cache | ||
| * entries excluded only from static prerenders. Call sites go through | ||
| * `trackRuntimeDataAccessed`, which resolves the promise `true` on the | ||
| * first access; it's resolved `false` when the prerender completes without | ||
| * one. Promise resolution is idempotent, so the flag is monotonic with no | ||
| * extra state. | ||
| * | ||
| * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`) | ||
| * so the fulfillment row's stream position records the stage the access | ||
| * happened in; the per-segment prefetch encoding (`collectSegmentData`) | ||
| * extracts it from the page data to tell the client whether a runtime | ||
| * prefetch request could be skipped. Tracking is page-global: an access | ||
| * anywhere in the page poisons all segments (per-segment granularity is | ||
| * recovered downstream for segments whose content is provably complete). | ||
| * Shared between the payload prerender store and the render store because | ||
| * request-data props are created during payload construction, before the | ||
| * render store exists. Null for warmup, route-handler, and error prerender | ||
| * stores. | ||
| */ | ||
| readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null; | ||
| /** | ||
| * Mutable single-boolean companion to `runtimeDataAccessed`, holding this | ||
| * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement | ||
| * directly — the value that becomes the route's build-constant hint: | ||
| * starts `true`, and a disqualifying runtime-data access flips it to | ||
| * `false`. Not every access that resolves the promise disqualifies — | ||
| * fallback-param accesses on a fallback-upgradeable route are transient | ||
| * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies | ||
| * the rule at access time using `isFallbackUpgradeable` below). A plain | ||
| * boolean suffices because the hint needs no stream positioning: unlike | ||
| * `runtimeDataAccessed`, whose fulfillment position encodes which stage | ||
| * the access happened in, this is read once after the prerender settles. | ||
| * Held in a cell so it can be shared. Same sharing and null rules as | ||
| * `runtimeDataAccessed`. | ||
| */ | ||
| readonly shouldAttemptStaticPrefetch: { | ||
| current: boolean; | ||
| } | null; | ||
| /** | ||
| * Whether a fallback shell produced by this prerender could later be | ||
| * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`: | ||
| * at least one fallback param is a `generateStaticParams` candidate). | ||
| * Consulted by `trackRuntimeDataAccessed` to decide whether a | ||
| * fallback-param access disqualifies the static-prefetch hint. | ||
| */ | ||
| readonly isFallbackUpgradeable: boolean; | ||
| } | ||
@@ -112,0 +161,0 @@ export interface PrerenderStoreModernRuntime extends PrerenderStoreModernCommon { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n needsSessionShell?: boolean // DEV-only\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["getCacheSignal","getDraftModeProviderForCacheScope","getHmrRefreshHash","getResumeDataCache","getServerComponentsHmrCache","getStagedRenderingController","getVaryParamsAccumulator","isHmrRefresh","throwForMissingRequestStore","throwInvariantForMissingStore","workUnitAsyncStorage","workUnitAsyncStorageInstance","callingExpression","Error","InvariantError","workUnitStore","type","resumeDataCache","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","serverComponentsHmrCache","workStore","isDraftMode","draftMode","stagedRendering","cacheSignal","varyParamsAccumulator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;IAgjBgBA,cAAc;eAAdA;;IAjDAC,iCAAiC;eAAjCA;;IA/EAC,iBAAiB;eAAjBA;;IAtBAC,kBAAkB;eAAlBA;;IAwEAC,2BAA2B;eAA3BA;;IAwDAC,4BAA4B;eAA5BA;;IAkD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AAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAcc,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACEd;YACA,OAAO;IACX;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/app-render/work-unit-async-storage.external.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { DraftModeProvider } from '../async-storage/draft-mode-provider'\nimport type { ResponseCookies } from '../web/spec-extension/cookies'\nimport type { ReadonlyHeaders } from '../web/spec-extension/adapters/headers'\nimport type { ReadonlyRequestCookies } from '../web/spec-extension/adapters/request-cookies'\nimport type { CacheSignal } from './cache-signal'\nimport type { ResponseVaryParamsAccumulator } from './vary-params'\nimport type { DynamicTrackingState } from './dynamic-rendering'\nimport type { OpaqueFallbackRouteParams } from '../request/fallback-params'\n\n// Share the instance module in the next-shared layer\nimport { workUnitAsyncStorageInstance } from './work-unit-async-storage-instance' with { 'turbopack-transition': 'next-shared' }\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport type {\n PrerenderResumeDataCache,\n ResumeDataCache,\n} from '../resume-data-cache/resume-data-cache'\nimport type { Params } from '../request/params'\nimport type { ImplicitTags } from '../lib/implicit-tags'\nimport type { WorkStore } from './work-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport type { StagedRenderingController } from './staged-rendering'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nexport type WorkUnitPhase = 'action' | 'render' | 'after'\n\nexport interface CommonWorkUnitStore {\n /** NOTE: Will be mutated as phases change */\n phase: WorkUnitPhase\n readonly implicitTags: ImplicitTags\n}\n\nexport interface RequestStore extends CommonWorkUnitStore {\n readonly type: 'request'\n\n /**\n * The URL of the request. This only specifies the pathname and the search\n * part of the URL.\n */\n readonly url: {\n /**\n * The pathname of the requested URL.\n */\n readonly pathname: string\n\n /**\n * The search part of the requested URL. If the request did not provide a\n * search part, this will be an empty string.\n */\n readonly search: string\n }\n\n readonly headers: ReadonlyHeaders\n // This is mutable because we need to reassign it when transitioning from the action phase to the render phase.\n // The cookie object itself is deliberately read only and thus can't be updated.\n cookies: ReadonlyRequestCookies\n readonly mutableCookies: ResponseCookies\n readonly userspaceMutableCookies: ResponseCookies\n readonly draftMode: DraftModeProvider\n readonly isHmrRefresh?: boolean\n readonly serverComponentsHmrCache?: ServerComponentsHmrCache\n readonly hmrRefreshHash?: string\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this request. Either a mutable\n * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or\n * an immutable `RenderResumeDataCache` (e.g. when resuming from a postponed\n * state). Narrow via `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n stale?: number\n\n stagedRendering?: StagedRenderingController | null\n asyncApiPromises?: AsyncApiPromises\n needsSessionShell?: boolean // DEV-only\n cacheSignal?: CacheSignal | null\n fallbackParams?: OpaqueFallbackRouteParams | null\n varyParamsAccumulator?: ResponseVaryParamsAccumulator | null\n\n // Only in build-time instant-validation or when rendering\n // a secondary stream for static shell validation\n // We mirror the controller/renderSignal from prerender stores to allow aborting the render\n controller?: AbortController\n renderSignal?: AbortSignal\n\n // Only in build-time instant-validation\n validationSamples?: InstantValidationSamples\n validationSampleTracking?: InstantValidationSampleTracking | null\n\n // DEV-only\n usedDynamic?: boolean\n}\n\nexport type InstantValidationSamples = {\n params: Params | undefined\n searchParams: Record<string, string | string[] | null> | undefined\n}\n\nexport type AsyncApiPromises = {\n cookies: Promise<ReadonlyRequestCookies>\n mutableCookies: Promise<ReadonlyRequestCookies>\n headers: Promise<ReadonlyHeaders>\n sharedParamsParent: Promise<string>\n sharedSearchParamsParent: Promise<string>\n connection: Promise<undefined>\n io: Promise<undefined>\n}\n\n/**\n * The Prerender store is for tracking information related to prerenders.\n *\n * It can be used for both RSC and SSR prerendering and should be scoped as close\n * to the individual `renderTo...` API call as possible. To keep the type simple\n * we don't distinguish between RSC and SSR prerendering explicitly but instead\n * use conditional object properties to infer which mode we are in. For instance cache tracking\n * only needs to happen during the RSC prerender when we are prospectively prerendering\n * to fill all caches.\n */\nexport type PrerenderStoreModern =\n | PrerenderStoreModernClient\n | PrerenderStoreModernServer\n | PrerenderStoreModernRuntime\n | ValidationStoreClient\n\n/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStoreModern = Exclude<\n PrerenderStoreModern,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface PrerenderStoreModernClient\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender-client'\n}\n\nexport interface ValidationStoreClient extends PrerenderStoreModernCommon {\n readonly type: 'validation-client'\n readonly boundaryState: ValidationBoundaryTracking | null\n validationSamples: InstantValidationSamples | null\n validationSampleTracking: InstantValidationSampleTracking | null\n fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStoreModernServer\n extends PrerenderStoreModernCommon,\n StaticPrerenderStoreCommon {\n readonly type: 'prerender'\n\n readonly stagedRendering: StagedRenderingController | null\n\n /**\n * When not null, records whether the render has accessed a data source\n * that hangs during a static prerender but would resolve during a runtime\n * prerender — cookies, headers, fallback params, searchParams, and cache\n * entries excluded only from static prerenders. Call sites go through\n * `trackRuntimeDataAccessed`, which resolves the promise `true` on the\n * first access; it's resolved `false` when the prerender completes without\n * one. Promise resolution is idempotent, so the flag is monotonic with no\n * extra state.\n *\n * The promise is embedded in the RSC payload (`InitialRSCPayload['u']`)\n * so the fulfillment row's stream position records the stage the access\n * happened in; the per-segment prefetch encoding (`collectSegmentData`)\n * extracts it from the page data to tell the client whether a runtime\n * prefetch request could be skipped. Tracking is page-global: an access\n * anywhere in the page poisons all segments (per-segment granularity is\n * recovered downstream for segments whose content is provably complete).\n * Shared between the payload prerender store and the render store because\n * request-data props are created during payload construction, before the\n * render store exists. Null for warmup, route-handler, and error prerender\n * stores.\n */\n readonly runtimeDataAccessed: PromiseWithResolvers<boolean> | null\n\n /**\n * Mutable single-boolean companion to `runtimeDataAccessed`, holding this\n * prerender's `PrefetchHint.ShouldAttemptStaticPrefetch` measurement\n * directly — the value that becomes the route's build-constant hint:\n * starts `true`, and a disqualifying runtime-data access flips it to\n * `false`. Not every access that resolves the promise disqualifies —\n * fallback-param accesses on a fallback-upgradeable route are transient\n * and leave the hint intact (see `trackRuntimeDataAccessed`, which applies\n * the rule at access time using `isFallbackUpgradeable` below). A plain\n * boolean suffices because the hint needs no stream positioning: unlike\n * `runtimeDataAccessed`, whose fulfillment position encodes which stage\n * the access happened in, this is read once after the prerender settles.\n * Held in a cell so it can be shared. Same sharing and null rules as\n * `runtimeDataAccessed`.\n */\n readonly shouldAttemptStaticPrefetch: { current: boolean } | null\n\n /**\n * Whether a fallback shell produced by this prerender could later be\n * upgraded to a concrete prerender (`renderOpts.isFallbackUpgradeable`:\n * at least one fallback param is a `generateStaticParams` candidate).\n * Consulted by `trackRuntimeDataAccessed` to decide whether a\n * fallback-param access disqualifies the static-prefetch hint.\n */\n readonly isFallbackUpgradeable: boolean\n}\n\nexport interface PrerenderStoreModernRuntime\n extends PrerenderStoreModernCommon {\n readonly type: 'prerender-runtime'\n\n /**\n * The staged rendering controller for this prerender. Models stage\n * transitions (Before → Static → Runtime → Dynamic). Null for prospective\n * renders where all stages run without sequencing.\n */\n readonly stagedRendering: StagedRenderingController | null\n readonly isSessionShell: boolean\n\n readonly headers: RequestStore['headers']\n readonly cookies: RequestStore['cookies']\n readonly draftMode: RequestStore['draftMode']\n}\n\nexport interface RevalidateStore {\n // Collected revalidate times and tags for this document during the prerender.\n revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.\n expire: number // server expiration time\n stale: number // client expiration time\n tags: null | string[]\n}\n\ninterface PrerenderStoreModernCommon\n extends CommonWorkUnitStore,\n RevalidateStore {\n /**\n * The render signal is aborted after React's `prerender` function is aborted\n * (using a separate signal), which happens in two cases:\n *\n * 1. When all caches are filled during the prospective prerender.\n * 2. When the final prerender is aborted immediately after the prerender was\n * started.\n *\n * It can be used to reject any pending I/O, including hanging promises. This\n * allows React to properly track the async I/O in dev mode, which yields\n * better owner stacks for dynamic validation errors.\n */\n readonly renderSignal: AbortSignal\n\n /**\n * This is the AbortController which represents the boundary between Prerender\n * and dynamic. In some renders it is the same as the controller for React,\n * but in others it is a separate controller. It should be aborted whenever we\n * are no longer in the prerender phase of rendering. Typically this is after\n * one task, or when you call a sync API which requires the prerender to end\n * immediately.\n */\n readonly controller: AbortController\n\n /**\n * When not null, this signal is used to track cache reads during prerendering\n * and to await all cache reads completing, before aborting the prerender.\n */\n readonly cacheSignal: null | CacheSignal\n\n /**\n * During some prerenders we want to track dynamic access.\n */\n readonly dynamicTracking: null | DynamicTrackingState\n\n readonly rootParams: Params\n\n /**\n * The resume data cache for this prerender. Either a mutable\n * `PrerenderResumeDataCache` that fills as this prerender runs, or an\n * immutable `RenderResumeDataCache` provided by an earlier phase when the\n * prerender is supposed to read from prefilled caches only (e.g. when\n * prerendering an optional fallback shell). Narrow via\n * `resumeDataCache.mutable` to tell them apart.\n */\n resumeDataCache: ResumeDataCache | null\n\n /**\n * The HMR refresh hash is only provided in dev mode. It is needed for the dev\n * warmup render to ensure that the cache keys will be identical for the\n * subsequent dynamic render.\n */\n readonly hmrRefreshHash: string | undefined\n\n /**\n * A mutable accumulator for per-segment vary params during prerender. Tracks\n * which route params each segment actually accesses, allowing the client\n * cache to re-key entries for better sharing across different param values.\n */\n readonly varyParamsAccumulator: ResponseVaryParamsAccumulator | null\n}\n\ninterface StaticPrerenderStoreCommon {\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n}\n\nexport interface PrerenderStorePPR\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-ppr'\n readonly rootParams: Params\n readonly dynamicTracking: null | DynamicTrackingState\n\n /**\n * The set of unknown route parameters. Accessing these will be tracked as\n * a dynamic access.\n */\n readonly fallbackRouteParams: OpaqueFallbackRouteParams | null\n\n /**\n * The resume data cache for this prerender. Always mutable in PPR mode.\n */\n resumeDataCache: PrerenderResumeDataCache\n}\n\nexport interface PrerenderStoreLegacy\n extends CommonWorkUnitStore,\n RevalidateStore {\n readonly type: 'prerender-legacy'\n readonly rootParams: Params\n}\n\nexport type PrerenderStore =\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModern\n\n// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */\nexport type StaticPrerenderStore = Exclude<\n PrerenderStore,\n PrerenderStoreModernRuntime | ValidationStoreClient\n>\n\nexport interface CommonCacheStore\n extends Omit<CommonWorkUnitStore, 'implicitTags'> {\n /**\n * A cache work unit store might not always have an outer work unit store,\n * from which implicit tags could be inherited.\n */\n readonly implicitTags: ImplicitTags | undefined\n /**\n * Draft mode is only available if the outer work unit store is a request\n * store and draft mode is enabled.\n */\n readonly draftMode: DraftModeProvider | undefined\n}\n\nexport interface CommonUseCacheStore extends CommonCacheStore, RevalidateStore {\n explicitRevalidate: undefined | number // explicit revalidate time from cacheLife() calls\n explicitExpire: undefined | number // server expiration time\n explicitStale: undefined | number // client expiration time\n readonly hmrRefreshHash: string | undefined\n readonly isHmrRefresh: boolean\n readonly serverComponentsHmrCache: ServerComponentsHmrCache | undefined\n readonly forceRevalidate: boolean\n readonly outerOwnerStack: string | undefined\n}\n\nexport interface PublicUseCacheStore extends CommonUseCacheStore {\n readonly type: 'cache'\n\n /**\n * The root params for the current route. `undefined` when nested inside\n * `unstable_cache`, which doesn't carry root params. Currently, `\"use cache\"`\n * inside `unstable_cache` is allowed, so this case must be handled. The error\n * message in `getRootParam` assumes this is the only scenario where\n * `rootParams` is `undefined`.\n */\n readonly rootParams: Params | undefined\n /**\n * Tracks which root param names were read during this cache invocation.\n */\n readonly readRootParamNames: Set<string>\n /**\n * The first nested public `'use cache'` invocation with a dynamic cache life\n * (`revalidate === 0` or `expire < MIN_PRERENDERABLE_EXPIRE`) that propagated\n * up to this store. Used as `cause` for the nested-dynamic cache error so the\n * redbox can point at the inner invocation site, not just the outer one.\n */\n dynamicNestedCacheError: Error | undefined\n}\n\nexport interface PrivateUseCacheStore extends CommonUseCacheStore {\n readonly type: 'private-cache'\n\n readonly headers: ReadonlyHeaders\n readonly cookies: ReadonlyRequestCookies\n\n readonly rootParams: Params\n\n /**\n * DEV-only: Tracks which root param names were read during this cache\n * invocation. In development, private caches are persisted (keyed by the\n * request's cookies and headers), so reads of different root param values\n * must produce different entries.\n */\n readonly readRootParamNames: Set<string> | undefined\n}\n\nexport type UseCacheStore = PublicUseCacheStore | PrivateUseCacheStore\n\nexport interface UnstableCacheStore extends CommonCacheStore {\n readonly type: 'unstable-cache'\n /**\n * Always `undefined` for `unstable_cache` — root params are not available in\n * this context. If a `\"use cache\"` function nested inside `unstable_cache`\n * tries to access root params, it will encounter `undefined` here and throw.\n */\n readonly rootParams: undefined\n}\n\n/**\n * The Cache store is for tracking information inside a \"use cache\" or\n * unstable_cache context. A cache store shadows an outer request store (if\n * present) as a work unit, so that we never accidentally expose any request or\n * page specific information to cache functions, unless it's explicitly desired.\n * For those exceptions, the data is copied over from the request store to the\n * cache store, instead of generally making the request store available to cache\n * functions.\n */\nexport type CacheStore = UseCacheStore | UnstableCacheStore\n\nexport interface GenerateStaticParamsStore extends CommonWorkUnitStore {\n readonly type: 'generate-static-params'\n readonly rootParams: Params\n}\n\nexport type WorkUnitStore =\n | RequestStore\n | CacheStore\n | PrerenderStore\n | GenerateStaticParamsStore\n\nexport type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>\n\nexport { workUnitAsyncStorageInstance as workUnitAsyncStorage }\n\nexport function throwForMissingRequestStore(callingExpression: string): never {\n throw new Error(\n `\\`${callingExpression}\\` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n}\n\nexport function throwInvariantForMissingStore(): never {\n throw new InvariantError('Expected workUnitAsyncStorage to have a store.')\n}\n\n/**\n * Returns the resume data cache for the given work unit store, regardless of\n * whether it is mutable (`PrerenderResumeDataCache`) or read-only\n * (`RenderResumeDataCache`). Use `resumeDataCache.mutable` to narrow.\n */\nexport function getResumeDataCache(\n workUnitStore: WorkUnitStore\n): ResumeDataCache | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n return workUnitStore.resumeDataCache\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-legacy':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getHmrRefreshHash(\n workUnitStore: WorkUnitStore\n): string | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'prerender':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.hmrRefreshHash\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.isHmrRefresh ?? false\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return false\n}\n\nexport function getServerComponentsHmrCache(\n workUnitStore: WorkUnitStore\n): ServerComponentsHmrCache | undefined {\n if (process.env.__NEXT_DEV_SERVER) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'request':\n return workUnitStore.serverComponentsHmrCache\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'unstable-cache':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\n/**\n * Returns a draft mode provider only if draft mode is enabled.\n */\nexport function getDraftModeProviderForCacheScope(\n workStore: WorkStore,\n workUnitStore: WorkUnitStore\n): DraftModeProvider | undefined {\n if (workStore.isDraftMode) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'request':\n return workUnitStore.draftMode\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n return undefined\n}\n\nexport function getStagedRenderingController(\n workUnitStore: WorkUnitStore\n): StagedRenderingController | null {\n switch (workUnitStore.type) {\n case 'request':\n case 'prerender-runtime':\n case 'prerender':\n return workUnitStore.stagedRendering ?? null\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getCacheSignal(\n workUnitStore: WorkUnitStore\n): CacheSignal | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-runtime':\n return workUnitStore.cacheSignal\n case 'request': {\n // In dev, we might fill caches even during a dynamic request.\n if (workUnitStore.cacheSignal) {\n return workUnitStore.cacheSignal\n }\n // fallthrough\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n return workUnitStore satisfies never\n }\n}\n\nexport function getVaryParamsAccumulator(\n workUnitStore: WorkUnitStore\n): ResponseVaryParamsAccumulator | null {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n case 'request': {\n return workUnitStore.varyParamsAccumulator ?? null\n }\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'cache':\n case 'private-cache':\n case 'prerender-client':\n case 'validation-client':\n case 'unstable-cache':\n case 'generate-static-params':\n return null\n default:\n workUnitStore satisfies never\n return null\n }\n}\n"],"names":["getCacheSignal","getDraftModeProviderForCacheScope","getHmrRefreshHash","getResumeDataCache","getServerComponentsHmrCache","getStagedRenderingController","getVaryParamsAccumulator","isHmrRefresh","throwForMissingRequestStore","throwInvariantForMissingStore","workUnitAsyncStorage","workUnitAsyncStorageInstance","callingExpression","Error","InvariantError","workUnitStore","type","resumeDataCache","process","env","__NEXT_DEV_SERVER","hmrRefreshHash","undefined","serverComponentsHmrCache","workStore","isDraftMode","draftMode","stagedRendering","cacheSignal","varyParamsAccumulator"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;IAkmBgBA,cAAc;eAAdA;;IAjDAC,iCAAiC;eAAjCA;;IA/EAC,iBAAiB;eAAjBA;;IAtBAC,kBAAkB;eAAlBA;;IAwEAC,2BAA2B;eAA3BA;;IAwDAC,4BAA4B;eAA5BA;;IAkDAC,wBAAwB;eAAxBA;;IAlIAC,YAAY;eAAZA;;IA/DAC,2BAA2B;eAA3BA;;IAMAC,6BAA6B;eAA7BA;;IARyBC,oBAAoB;eAApDC,0DAA4B;;;8CAhbQ;gCASd;AAyaxB,SAASH,4BAA4BI,iBAAyB;IACnE,MAAM,qBAEL,CAFK,IAAIC,MACR,CAAC,EAAE,EAAED,kBAAkB,iHAAiH,CAAC,GADrI,qBAAA;eAAA;oBAAA;sBAAA;IAEN;AACF;AAEO,SAASH;IACd,MAAM,qBAAoE,CAApE,IAAIK,8BAAc,CAAC,mDAAnB,qBAAA;eAAA;oBAAA;sBA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B,OAAQV,cAAcC,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOD,cAAcW,SAAS;YAChC,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH;YACF;gBACEX;QACJ;IACF;IAEA,OAAOO;AACT;AAEO,SAASjB,6BACdU,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAcY,eAAe,IAAI;QAC1C,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOZ;IACX;AACF;AAEO,SAASf,eACde,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAOD,cAAca,WAAW;QAClC,KAAK;YAAW;gBACd,8DAA8D;gBAC9D,IAAIb,cAAca,WAAW,EAAE;oBAC7B,OAAOb,cAAca,WAAW;gBAClC;YACA,cAAc;YAChB;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACE,OAAOb;IACX;AACF;AAEO,SAAST,yBACdS,aAA4B;IAE5B,OAAQA,cAAcC,IAAI;QACxB,KAAK;QACL,KAAK;QACL,KAAK;YAAW;gBACd,OAAOD,cAAcc,qBAAqB,IAAI;YAChD;QACA,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO;QACT;YACEd;YACA,OAAO;IACX;AACF","ignoreList":[0]} |
@@ -154,6 +154,6 @@ "use strict"; | ||
| this.staticPathsCache = new _lrucache.LRUCache(// 5MB | ||
| 5 * 1024 * 1024, function length(value) { | ||
| 5 * 1024 * 1024, function length(value, cacheKey) { | ||
| var _JSON_stringify; | ||
| // Ensure minimum size of 1 for LRU eviction to work correctly | ||
| return ((_JSON_stringify = JSON.stringify(value.staticPaths)) == null ? void 0 : _JSON_stringify.length) || 1; | ||
| return cacheKey.length + (((_JSON_stringify = JSON.stringify(value.staticPaths)) == null ? void 0 : _JSON_stringify.length) || 1); | ||
| }); | ||
@@ -167,4 +167,4 @@ const { pagesDir, appDir } = (0, _findpagesdir.findPagesDir)(this.dir); | ||
| const hmrCacheSize = Math.max(this.nextConfig.cacheMaxMemorySize, _configshared.defaultConfig.cacheMaxMemorySize); | ||
| this.serverComponentsHmrCache = new _lrucache.LRUCache(hmrCacheSize, function length(value) { | ||
| return JSON.stringify(value).length; | ||
| this.serverComponentsHmrCache = new _lrucache.LRUCache(hmrCacheSize, function length(value, cacheKey) { | ||
| return cacheKey.length + JSON.stringify(value).length; | ||
| }); | ||
@@ -171,0 +171,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return JSON.stringify(value.staticPaths)?.length || 1\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value) {\n return JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["DevServer","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","React","createElement","Server","getStaticPathsWorker","worker","Worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getFormattedNodeOptionsWithoutInspect","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","DetachedPromise","conf","bundlerService","startServerSpan","trace","renderOpts","ErrorDebug","staticPathsCache","LRUCache","length","value","JSON","stringify","staticPaths","pagesDir","appDir","findPagesDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","defaultConfig","installUseCacheProbe","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","installDevValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","DevRouteMatcherManager","extensions","pageExtensions","extensionsExpression","RegExp","join","fileReader","BatchedFileReader","DefaultFileReader","pathnameFilter","test","push","DevPagesRouteMatcherProvider","localeNormalizer","DevPagesAPIRouteMatcherProvider","ignorePartFilter","part","startsWith","isTurbopack","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","getBuildId","prepareImpl","setGlobal","PHASE_DEVELOPMENT_SERVER","existingTelemetry","traceGlobals","get","telemetry","Telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","isPostpone","logErrorWithOriginalStack","err","hasPage","normalizedPath","normalizePagePath","console","error","isMiddlewareFile","findPageFile","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","DecodeError","MiddlewareNotFoundError","getProperError","decorateServerError","COMPILER_NAMES","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","getRequestMeta","requestStart","hrtime","bigint","addRequestMeta","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","logRequests","devRequestTimingInternalsEnd","manualTraceChild","hrtimeToEpochNanoseconds","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","pathHasPrefix","removePathPrefix","fs","existsSync","pathJoin","publicDir","PUBLIC_DIR_MIDDLEWARE_CONFLICT","formatServerError","sent","__NEXT_PAGE","isError","internalErr","body","send","type","getPagesManifest","NodeManifestLoader","serverDistDir","PAGES_MANIFEST","getAppPathsManifest","enabledDirectories","app","APP_PATHS_MANIFEST","rewrites","generateInterceptionRoutesRewrites","Object","keys","appPathRoutes","map","route","buildCustomRoute","regex","output","Log","exit","getMiddleware","middleware","getMiddlewareRouteMatcher","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","getInstrumentationModule","message","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","withCoalescedInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","FallbackMode","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","PRERENDER_MANIFEST","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackModeToFallbackField","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","getRouteRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","HMR_MESSAGE_SENT_TO_BROWSER","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","WrappedBuildError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","loadDefaultErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":";;;;+BA8HA;;;eAAqBA;;;6BA9Gd;+DAQgB;2DACR;4BACQ;mCACc;yCACM;sBACV;2BACc;8BAClB;4BAOtB;oEACmC;mCACR;+BACJ;kCACG;yBACP;uBAMnB;wBACsB;8BACA;uBACyB;mCAClB;4CAI7B;wBAC8C;6DAChC;iEACmB;8BACe;wBACtB;mCACC;wCACK;8CACM;iDACG;gDACD;iDACC;oCACb;mCACD;mCACA;0BACT;wCACiB;iCACV;4BACL;oDACwB;kCAClB;6BACG;6BAGR;0BAC8B;gDAKnD;4BAEuB;kCAEc;mCACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE1CC,IAAAA,4CAAyB;AAEzB,wCAAwC;AACxC,IAAIC;AACJ,MAAMC,kBAA6C,CAACC;IAClD,IAAIF,8BAA8BG,WAAW;QAC3CH,4BAA4B,AAC1BI,QAAQ,+DACRC,qBAAqB;IACzB;IACA,OAAOC,OAAMC,aAAa,CAACP,2BAA2BE;AACxD;AAqBe,MAAMJ,kBAAkBU,mBAAM;IA4BnCC,uBAEN;QACA,MAAMC,SAAS,IAAIC,kBAAM,CAACP,QAAQQ,OAAO,CAAC,0BAA0B;YAClEC,YAAY;YACZ,2GAA2G;YAC3G,uCAAuC;YACvCC,YAAY;YACZC,qBAAqB,IAAI,CAACC,UAAU,CAACC,YAAY,CAACC,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,CAACC,YAAY,EAAE;YACnD,MAAM,IAAI,CAAC9P,UAAU,CAAC;gBACpBE;gBACAkK;gBACAjK,YAAY;gBACZF,YAAYvE;gBACZ0E;YACF;QACF;QAEA,IAAI,CAAC2P,gBAAgB,GAAG,KAAK,CAACvG;QAE9B,OAAO,MAAM,KAAK,CAAC8F,mBAAmB;YACpCpP;YACAsP;YACAhM;YACA+L;YACA7E;YACA+E;YACArP;QACF;IACF;IAEA,MAAgB4P,2BACd5P,GAAY,EAC2C;QACvD,MAAM,IAAI,CAACxC,cAAc,CAACoS,0BAA0B,CAAC5P;QACrD,OAAO,MAAM6P,IAAAA,sDAA0B,EAAC,IAAI,CAAC9Q,OAAO;IACtD;IAEA,MAAMwQ,oBAAoBzP,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACtC,cAAc,CAAC+R,mBAAmB,CAACzP;IACvD;IAEA,MAAgBgQ,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACxN,SAASyN,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAAC1N,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/dev/next-dev-server.ts"],"sourcesContent":["import type { FindComponentsResult, NodeRequestHandler } from '../next-server'\nimport type { LoadComponentsReturnType } from '../load-components'\nimport type { Options as ServerOptions } from '../next-server'\nimport type { Params } from '../request/params'\nimport type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { UrlWithParsedQuery } from 'url'\nimport type { MiddlewareRoutingItem } from '../base-server'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'\n\nimport {\n addRequestMeta,\n getRequestMeta,\n type NextParsedUrlQuery,\n type NextUrlWithParsedQuery,\n} from '../request-meta'\nimport type { DevBundlerService } from '../lib/dev-bundler-service'\nimport type { IncrementalCache } from '../lib/incremental-cache'\nimport type { UnwrapPromise } from '../../lib/coalesced-function'\nimport type { NodeNextResponse, NodeNextRequest } from '../base-http/node'\nimport type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager'\nimport type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'\n\nimport * as React from 'react'\nimport fs from 'fs'\nimport { Worker } from 'next/dist/compiled/jest-worker'\nimport { installUseCacheProbe } from './use-cache-probe-pool'\nimport { installDevValidationWorker } from './dev-validation-worker-pool'\nimport { join as pathJoin } from 'path'\nimport { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants'\nimport { findPagesDir } from '../../lib/find-pages-dir'\nimport {\n PHASE_DEVELOPMENT_SERVER,\n PAGES_MANIFEST,\n APP_PATHS_MANIFEST,\n COMPILER_NAMES,\n PRERENDER_MANIFEST,\n} from '../../shared/lib/constants'\nimport Server, { WrappedBuildError } from '../next-server'\nimport { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path'\nimport { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix'\nimport { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix'\nimport { Telemetry } from '../../telemetry/storage'\nimport {\n type Span,\n hrtimeToEpochNanoseconds,\n setGlobal,\n trace,\n} from '../../trace'\nimport { traceGlobals } from '../../trace/shared'\nimport { findPageFile } from '../lib/find-page-file'\nimport { getFormattedNodeOptionsWithoutInspect } from '../lib/utils'\nimport { withCoalescedInvoke } from '../../lib/coalesced-function'\nimport {\n loadDefaultErrorComponents,\n type ErrorModule,\n} from '../load-default-error-components'\nimport { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils'\nimport * as Log from '../../build/output/log'\nimport isError, { getProperError } from '../../lib/is-error'\nimport { defaultConfig, type NextConfigComplete } from '../config-shared'\nimport { isMiddlewareFile } from '../../build/utils'\nimport { formatServerError } from '../../lib/format-server-error'\nimport { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager'\nimport { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider'\nimport { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider'\nimport { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider'\nimport { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider'\nimport { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader'\nimport { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader'\nimport { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader'\nimport { LRUCache } from '../lib/lru-cache'\nimport { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher'\nimport { DetachedPromise } from '../../lib/detached-promise'\nimport { isPostpone } from '../lib/router-utils/is-postpone'\nimport { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites'\nimport { buildCustomRoute } from '../../lib/build-custom-route'\nimport { decorateServerError } from '../../shared/lib/error-source'\nimport type { ServerOnInstrumentationRequestError } from '../app-render/types'\nimport type { ServerComponentsHmrCache } from '../response-cache'\nimport { logRequests } from './log-requests'\nimport { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback'\nimport type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup'\nimport {\n ensureInstrumentationRegistered,\n getInstrumentationModule,\n} from '../lib/router-utils/instrumentation-globals.external'\nimport type { PrerenderManifest } from '../../build'\nimport { getRouteRegex } from '../../shared/lib/router/utils/route-regex'\nimport type { PrerenderedRoute } from '../../build/static-paths/types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport { registerLocalSpanRecorder } from '../lib/trace/local-span-recorder'\n\nregisterLocalSpanRecorder()\n\n// Load ReactDevOverlay only when needed\nlet PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType\nconst ReactDevOverlay: PagesDevOverlayBridgeType = (props) => {\n if (PagesDevOverlayBridgeImpl === undefined) {\n PagesDevOverlayBridgeImpl = (\n require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup')\n ).PagesDevOverlayBridge\n }\n return React.createElement(PagesDevOverlayBridgeImpl, props)\n}\n\nexport interface Options extends ServerOptions {\n // Override type to make the full config available instead of only NextConfigRuntime\n conf: NextConfigComplete\n /**\n * Tells of Next.js is running from the `next dev` command\n */\n isNextDevCommand?: boolean\n\n /**\n * Interface to the development bundler.\n */\n bundlerService: DevBundlerService\n\n /**\n * Trace span for server startup.\n */\n startServerSpan: Span\n}\n\nexport default class DevServer extends Server {\n // Override type to make the full config available instead of only NextConfigRuntime\n protected readonly nextConfig: NextConfigComplete\n\n /**\n * The promise that resolves when the server is ready. When this is unset\n * the server is ready.\n */\n private ready? = new DetachedPromise<void>()\n protected sortedRoutes?: string[]\n private pagesDir?: string\n private appDir?: string\n private actualMiddlewareFile?: string\n private actualInstrumentationHookFile?: string\n private middleware?: MiddlewareRoutingItem\n private readonly bundlerService: DevBundlerService\n private staticPathsCache: LRUCache<\n UnwrapPromise<ReturnType<DevServer['getStaticPaths']>>\n >\n private startServerSpan: Span\n private readonly serverComponentsHmrCache:\n | ServerComponentsHmrCache\n | undefined\n\n protected staticPathsWorker?: { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n private getStaticPathsWorker(): { [key: string]: any } & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n } {\n const worker = new Worker(require.resolve('./static-paths-worker'), {\n maxRetries: 1,\n // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test.\n // This helps reusing the memory a lot.\n numWorkers: 1,\n enableWorkerThreads: this.nextConfig.experimental.workerThreads,\n forkOptions: {\n env: {\n ...process.env,\n // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers\n // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to\n // the number of workers Next.js tries to launch. The only worker users are interested in debugging\n // is the main Next.js one\n NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(),\n },\n },\n }) as Worker & {\n loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths\n }\n\n worker.getStdout().pipe(process.stdout)\n worker.getStderr().pipe(process.stderr)\n\n return worker\n }\n\n constructor(options: Options) {\n try {\n // Increase the number of stack frames on the server\n Error.stackTraceLimit = 50\n } catch {}\n super({ ...options, dev: true })\n this.nextConfig = options.conf\n this.bundlerService = options.bundlerService\n this.startServerSpan =\n options.startServerSpan ?? trace('start-next-dev-server')\n this.renderOpts.ErrorDebug = ReactDevOverlay\n this.staticPathsCache = new LRUCache(\n // 5MB\n 5 * 1024 * 1024,\n function length(value, cacheKey) {\n // Ensure minimum size of 1 for LRU eviction to work correctly\n return (\n cacheKey.length + (JSON.stringify(value.staticPaths)?.length || 1)\n )\n }\n )\n\n const { pagesDir, appDir } = findPagesDir(this.dir)\n this.pagesDir = pagesDir\n this.appDir = appDir\n\n if (this.nextConfig.experimental.serverComponentsHmrCache) {\n // Ensure HMR cache has a minimum size equal to the default cacheMaxMemorySize,\n // but allow it to grow if the user has configured a larger value.\n const hmrCacheSize = Math.max(\n this.nextConfig.cacheMaxMemorySize,\n defaultConfig.cacheMaxMemorySize\n )\n this.serverComponentsHmrCache = new LRUCache(\n hmrCacheSize,\n function length(value, cacheKey) {\n return cacheKey.length + JSON.stringify(value).length\n }\n )\n }\n\n installUseCacheProbe({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n\n // Runs Cache Components dev validation on a worker thread, off the main\n // thread, so validation renders don't block the event loop during rapid\n // navigation. Gated by `experimental.devValidationWorker`. The worker is\n // spawned lazily on the first navigation that validates, so this install is\n // free when a project doesn't use Cache Components.\n //\n // Turbopack only, because the worker's thread has source maps just for the\n // chunks it loaded itself, and resolves the rest by reading the `.map`\n // Turbopack writes next to each chunk. Webpack keeps its dev source maps in\n // the compiler, which the worker's thread cannot reach, so validation\n // errors would be reported without a source location. Running validation on\n // the main thread costs dev performance but keeps those frames intact.\n if (\n process.env.TURBOPACK &&\n this.nextConfig.experimental.devValidationWorker !== false\n ) {\n installDevValidationWorker({\n distDir: this.distDir,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n nextConfig: this.nextConfig,\n })\n }\n }\n\n protected override getServerComponentsHmrCache() {\n return this.serverComponentsHmrCache\n }\n\n protected override getServerComponentsHmrRefreshHash(): string | undefined {\n return this.bundlerService.getServerComponentsHmrRefreshHash()\n }\n\n protected getRouteMatchers(): RouteMatcherManager {\n const { pagesDir, appDir } = findPagesDir(this.dir)\n\n const ensurer: RouteEnsurer = {\n ensure: async (match, pathname) => {\n await this.ensurePage({\n definition: match.definition,\n page: match.definition.page,\n clientOnly: false,\n url: pathname,\n })\n },\n }\n\n const matchers = new DevRouteMatcherManager(\n super.getRouteMatchers(),\n ensurer,\n this.dir\n )\n const extensions = this.nextConfig.pageExtensions\n const extensionsExpression = new RegExp(`\\\\.(?:${extensions.join('|')})$`)\n\n // If the pages directory is available, then configure those matchers.\n if (pagesDir) {\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Only allow files that have the correct extensions.\n pathnameFilter: (pathname) => extensionsExpression.test(pathname),\n })\n )\n\n matchers.push(\n new DevPagesRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n matchers.push(\n new DevPagesAPIRouteMatcherProvider(\n pagesDir,\n extensions,\n fileReader,\n this.localeNormalizer\n )\n )\n }\n\n if (appDir) {\n // We create a new file reader for the app directory because we don't want\n // to include any folders or files starting with an underscore. This will\n // prevent the reader from wasting time reading files that we know we\n // don't care about.\n const fileReader = new BatchedFileReader(\n new DefaultFileReader({\n // Ignore any directory prefixed with an underscore.\n ignorePartFilter: (part) => part.startsWith('_'),\n })\n )\n\n // TODO: Improve passing of \"is running with Turbopack\"\n const isTurbopack = !!process.env.TURBOPACK\n matchers.push(\n new DevAppPageRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n matchers.push(\n new DevAppRouteRouteMatcherProvider(\n appDir,\n extensions,\n fileReader,\n isTurbopack\n )\n )\n }\n\n return matchers\n }\n\n protected getBuildId(): string {\n return 'development'\n }\n\n protected async prepareImpl(): Promise<void> {\n setGlobal('distDir', this.distDir)\n setGlobal('phase', PHASE_DEVELOPMENT_SERVER)\n\n // Use existing telemetry instance from traceGlobals instead of creating a new one.\n // Creating a new instance would overwrite the existing one, causing any telemetry\n // events recorded to the original instance to be lost during cleanup/flush.\n const existingTelemetry = traceGlobals.get('telemetry')\n const telemetry =\n existingTelemetry || new Telemetry({ distDir: this.distDir })\n\n await super.prepareImpl()\n await this.matchers.reload()\n\n this.ready?.resolve()\n this.ready = undefined\n\n // In dev, this needs to be called after prepare because the build entries won't be known in the constructor\n this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()\n\n // This is required by the tracing subsystem.\n setGlobal('appDir', this.appDir)\n setGlobal('pagesDir', this.pagesDir)\n // Only set telemetry if it wasn't already set\n if (!existingTelemetry) {\n setGlobal('telemetry', telemetry)\n }\n\n process.on('unhandledRejection', (reason) => {\n if (isPostpone(reason)) {\n // React postpones that are unhandled might end up logged here but they're\n // not really errors. They're just part of rendering.\n return\n }\n this.logErrorWithOriginalStack(reason, 'unhandledRejection')\n })\n process.on('uncaughtException', (err) => {\n this.logErrorWithOriginalStack(err, 'uncaughtException')\n })\n }\n\n protected async hasPage(pathname: string): Promise<boolean> {\n let normalizedPath: string\n try {\n normalizedPath = normalizePagePath(pathname)\n } catch (err) {\n console.error(err)\n // if normalizing the page fails it means it isn't valid\n // so it doesn't exist so don't throw and return false\n // to ensure we return 404 instead of 500\n return false\n }\n\n if (isMiddlewareFile(normalizedPath)) {\n return findPageFile(\n this.dir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n ).then(Boolean)\n }\n\n let appFile: string | null = null\n let pagesFile: string | null = null\n\n if (this.appDir) {\n appFile = await findPageFile(\n this.appDir,\n normalizedPath + '/page',\n this.nextConfig.pageExtensions,\n true\n )\n }\n\n if (this.pagesDir) {\n pagesFile = await findPageFile(\n this.pagesDir,\n normalizedPath,\n this.nextConfig.pageExtensions,\n false\n )\n }\n if (appFile && pagesFile) {\n return false\n }\n\n return Boolean(appFile || pagesFile)\n }\n\n async runMiddleware(params: {\n request: NodeNextRequest\n response: NodeNextResponse\n parsedUrl: ParsedUrl\n parsed: UrlWithParsedQuery\n middlewareList: MiddlewareRoutingItem[]\n }) {\n try {\n const result = await super.runMiddleware({\n ...params,\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n\n if ('finished' in result) {\n return result\n }\n\n result.waitUntil.catch((error) => {\n this.logErrorWithOriginalStack(error, 'unhandledRejection')\n })\n return result\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n\n /**\n * We only log the error when it is not a MiddlewareNotFound error as\n * in that case we should be already displaying a compilation error\n * which is what makes the module not found.\n */\n if (!(error instanceof MiddlewareNotFoundError)) {\n this.logErrorWithOriginalStack(error)\n }\n\n const err = getProperError(error)\n decorateServerError(err, COMPILER_NAMES.edgeServer)\n const { request, response, parsedUrl } = params\n\n /**\n * When there is a failure for an internal Next.js request from\n * middleware we bypass the error without finishing the request\n * so we can serve the required chunks to render the error.\n */\n if (\n request.url.includes('/_next/static') ||\n request.url.includes('/__nextjs_attach-nodejs-inspector') ||\n request.url.includes('/__nextjs_original-stack-frame') ||\n request.url.includes('/__nextjs_source-map') ||\n request.url.includes('/__nextjs_error_feedback')\n ) {\n return { finished: false }\n }\n\n response.statusCode = 500\n await this.renderError(err, request, response, parsedUrl.pathname)\n return { finished: true }\n }\n }\n\n async runEdgeFunction(params: {\n req: NodeNextRequest\n res: NodeNextResponse\n query: ParsedUrlQuery\n params: Params | undefined\n page: string\n appPaths: string[] | null\n isAppPath: boolean\n }) {\n try {\n return super.runEdgeFunction({\n ...params,\n onError: (err) => this.logErrorWithOriginalStack(err, 'app-dir'),\n onWarning: (warn) => {\n this.logErrorWithOriginalStack(warn, 'warning')\n },\n })\n } catch (error) {\n if (error instanceof DecodeError) {\n throw error\n }\n this.logErrorWithOriginalStack(error, 'warning')\n const err = getProperError(error)\n const { req, res, page } = params\n\n res.statusCode = 500\n await this.renderError(err, req, res, page)\n return null\n }\n }\n\n public getRequestHandler(): NodeRequestHandler {\n const handler = super.getRequestHandler()\n\n return (req, res, parsedUrl) => {\n const request = this.normalizeReq(req)\n const response = this.normalizeRes(res)\n const loggingConfig = this.nextConfig.logging\n\n if (loggingConfig !== false) {\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n if (!getRequestMeta(req, 'devRequestTimingStart')) {\n const requestStart = process.hrtime.bigint()\n addRequestMeta(req, 'devRequestTimingStart', requestStart)\n }\n const isMiddlewareRequest =\n getRequestMeta(req, 'middlewareInvoke') ?? false\n\n if (!isMiddlewareRequest) {\n response.originalResponse.once('close', () => {\n // NOTE: The route match is only attached to the request's meta data\n // after the request handler is created, so we need to check it in the\n // close handler and not before.\n const routeMatch = getRequestMeta(req).match\n\n if (!routeMatch) {\n return\n }\n\n // The closure variable is not used here because the request handler may be invoked twice for one request when middleware is added in the application.\n // By setting the start time we can ensure that the middleware timing is correctly included.\n const requestStart = getRequestMeta(req, 'devRequestTimingStart')\n if (!requestStart) {\n return\n }\n const requestEnd = process.hrtime.bigint()\n logRequests(\n request,\n response,\n loggingConfig,\n requestStart,\n requestEnd,\n getRequestMeta(req, 'devRequestTimingMiddlewareStart'),\n getRequestMeta(req, 'devRequestTimingMiddlewareEnd'),\n getRequestMeta(req, 'devRequestTimingInternalsEnd'),\n getRequestMeta(req, 'devGenerateStaticParamsDuration')\n )\n\n // Create trace span for render phase\n const devRequestTimingInternalsEnd = getRequestMeta(\n req,\n 'devRequestTimingInternalsEnd'\n )\n if (devRequestTimingInternalsEnd) {\n this.startServerSpan.manualTraceChild(\n 'render-path',\n hrtimeToEpochNanoseconds(devRequestTimingInternalsEnd),\n hrtimeToEpochNanoseconds(requestEnd),\n { path: req.url || '' }\n )\n }\n })\n }\n }\n\n return handler(request, response, parsedUrl)\n }\n }\n\n public async handleRequest(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl?: NextUrlWithParsedQuery\n ): Promise<void> {\n const span = trace('handle-request', undefined, { url: req.url })\n const result = await span.traceAsyncFn(async () => {\n await this.ready?.promise\n addRequestMeta(req, 'PagesErrorDebug', this.renderOpts.ErrorDebug)\n return await super.handleRequest(req, res, parsedUrl)\n })\n const memoryUsage = process.memoryUsage()\n span\n .traceChild('memory-usage', {\n url: req.url,\n 'memory.rss': String(memoryUsage.rss),\n 'memory.heapUsed': String(memoryUsage.heapUsed),\n 'memory.heapTotal': String(memoryUsage.heapTotal),\n })\n .stop()\n return result\n }\n\n async run(\n req: NodeNextRequest,\n res: NodeNextResponse,\n parsedUrl: UrlWithParsedQuery\n ): Promise<void> {\n await this.ready?.promise\n\n const { basePath } = this.nextConfig\n let originalPathname: string | null = null\n\n // TODO: see if we can remove this in the future\n if (basePath && pathHasPrefix(parsedUrl.pathname || '/', basePath)) {\n // strip basePath before handling dev bundles\n // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`\n originalPathname = parsedUrl.pathname\n parsedUrl.pathname = removePathPrefix(parsedUrl.pathname || '/', basePath)\n }\n\n const { pathname } = parsedUrl\n\n if (pathname!.startsWith('/_next')) {\n if (fs.existsSync(pathJoin(this.publicDir, '_next'))) {\n throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)\n }\n }\n\n if (originalPathname) {\n // restore the path before continuing so that custom-routes can accurately determine\n // if they should match against the basePath or not\n parsedUrl.pathname = originalPathname\n }\n try {\n return await super.run(req, res, parsedUrl)\n } catch (error) {\n const err = getProperError(error)\n formatServerError(err)\n this.logErrorWithOriginalStack(err)\n if (!res.sent) {\n res.statusCode = 500\n try {\n return await this.renderError(err, req, res, pathname!, {\n __NEXT_PAGE: (isError(err) && err.page) || pathname || '',\n })\n } catch (internalErr) {\n console.error(internalErr)\n res.body('Internal Server Error').send()\n }\n }\n }\n }\n\n protected logErrorWithOriginalStack(\n err?: unknown,\n type?: 'unhandledRejection' | 'uncaughtException' | 'warning' | 'app-dir'\n ): void {\n this.bundlerService.logErrorWithOriginalStack(err, type)\n }\n\n protected getPagesManifest(): PagesManifest | undefined {\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, PAGES_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getAppPathsManifest(): PagesManifest | undefined {\n if (!this.enabledDirectories.app) return undefined\n\n return (\n NodeManifestLoader.require(\n pathJoin(this.serverDistDir, APP_PATHS_MANIFEST)\n ) ?? undefined\n )\n }\n\n protected getinterceptionRoutePatterns(): RegExp[] {\n const rewrites = generateInterceptionRoutesRewrites(\n Object.keys(this.appPathRoutes ?? {}),\n this.nextConfig.basePath\n ).map((route) => new RegExp(buildCustomRoute('rewrite', route).regex))\n\n if (this.nextConfig.output === 'export' && rewrites.length > 0) {\n Log.error(\n 'Intercepting routes are not supported with static export.\\nRead more: https://nextjs.org/docs/app/building-your-application/deploying/static-exports#unsupported-features'\n )\n\n process.exit(1)\n }\n\n return rewrites ?? []\n }\n\n protected async getMiddleware() {\n // We need to populate the match\n // field as it isn't serializable\n if (this.middleware?.match === null) {\n this.middleware.match = getMiddlewareRouteMatcher(\n this.middleware.matchers || []\n )\n }\n return this.middleware\n }\n\n protected getNextFontManifest() {\n return undefined\n }\n\n protected async hasMiddleware(): Promise<boolean> {\n return this.hasPage(this.actualMiddlewareFile!)\n }\n\n protected async ensureMiddleware(url: string) {\n return this.ensurePage({\n page: this.actualMiddlewareFile!,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n protected async loadInstrumentationModule(): Promise<any> {\n let instrumentationModule: any\n if (\n this.actualInstrumentationHookFile &&\n (await this.ensurePage({\n page: this.actualInstrumentationHookFile!,\n clientOnly: false,\n definition: undefined,\n })\n .then(() => true)\n .catch(() => false))\n ) {\n try {\n instrumentationModule = await getInstrumentationModule(\n this.dir,\n this.nextConfig.distDir\n )\n } catch (err: any) {\n err.message = `An error occurred while loading instrumentation hook: ${err.message}`\n throw err\n }\n }\n return instrumentationModule\n }\n\n protected async runInstrumentationHookIfAvailable() {\n await ensureInstrumentationRegistered(this.dir, this.nextConfig.distDir)\n }\n\n protected async ensureEdgeFunction({\n page,\n appPaths,\n url,\n }: {\n page: string\n appPaths: string[] | null\n url: string\n }) {\n return this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n generateRoutes(_dev?: boolean) {\n // In development we expose all compiled files for react-error-overlay's line show feature\n // We use unshift so that we're sure the routes is defined before Next's default routes\n // routes.unshift({\n // match: getPathMatch('/_next/development/:path*'),\n // type: 'route',\n // name: '_next/development catchall',\n // fn: async (req, res, params) => {\n // const p = pathJoin(this.distDir, ...(params.path || []))\n // await this.serveStatic(req, res, p)\n // return {\n // finished: true,\n // }\n // },\n // })\n }\n\n protected async getStaticPaths({\n pathname,\n urlPathname,\n requestHeaders,\n page,\n isAppPath,\n }: {\n pathname: string\n urlPathname: string\n requestHeaders: IncrementalCache['requestHeaders']\n page: string\n isAppPath: boolean\n }): Promise<{\n prerenderedRoutes?: PrerenderedRoute[]\n staticPaths?: string[]\n fallbackMode?: FallbackMode\n }> {\n // we lazy load the staticPaths to prevent the user\n // from waiting on them for the page to load in dev mode\n\n const __getStaticPaths = async () => {\n const { configFileName, httpAgentOptions } = this.nextConfig\n const { locales, defaultLocale } = this.nextConfig.i18n || {}\n const staticPathsWorker = this.getStaticPathsWorker()\n\n try {\n const pathsResult = await staticPathsWorker.loadStaticPaths({\n dir: this.dir,\n distDir: this.distDir,\n pathname,\n config: {\n pprConfig: this.nextConfig.experimental.ppr,\n configFileName,\n cacheComponents: Boolean(this.nextConfig.cacheComponents),\n },\n httpAgentOptions,\n locales,\n defaultLocale,\n page,\n isAppPath,\n requestHeaders,\n cacheHandler: this.nextConfig.cacheHandler,\n cacheHandlers: this.nextConfig.cacheHandlers,\n cacheLifeProfiles: this.nextConfig.cacheLife,\n fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,\n isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,\n cacheMaxMemorySize: this.nextConfig.cacheMaxMemorySize,\n nextConfigOutput: this.nextConfig.output,\n buildId: this.buildId,\n deploymentId: this.deploymentId,\n authInterrupts: Boolean(this.nextConfig.experimental.authInterrupts),\n useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,\n staticPageGenerationTimeout:\n this.nextConfig.staticPageGenerationTimeout,\n sriEnabled: Boolean(this.nextConfig.experimental.sri?.algorithm),\n })\n return pathsResult\n } finally {\n // we don't re-use workers so destroy the used one\n staticPathsWorker.end()\n }\n }\n const result = this.staticPathsCache.get(pathname)\n\n const nextInvoke = withCoalescedInvoke(__getStaticPaths)(\n `staticPaths-${pathname}`,\n []\n )\n .then(async (res) => {\n const { prerenderedRoutes, fallbackMode: fallback } = res.value\n\n if (isAppPath) {\n if (this.nextConfig.output === 'export') {\n if (!prerenderedRoutes) {\n throw new Error(\n `Page \"${page}\" is missing exported function \"generateStaticParams()\", which is required with \"output: export\" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`\n )\n }\n\n if (\n !prerenderedRoutes.some((item) => item.pathname === urlPathname)\n ) {\n throw new Error(\n `Page \"${page}\" is missing param \"${pathname}\" in \"generateStaticParams()\", which is required with \"output: export\" config.`\n )\n }\n }\n }\n\n if (!isAppPath && this.nextConfig.output === 'export') {\n if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: blocking\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n } else if (fallback === FallbackMode.PRERENDER) {\n throw new Error(\n 'getStaticPaths with \"fallback: true\" cannot be used with \"output: export\". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'\n )\n }\n }\n\n const value: {\n staticPaths: string[] | undefined\n prerenderedRoutes: PrerenderedRoute[] | undefined\n fallbackMode: FallbackMode | undefined\n } = {\n staticPaths: prerenderedRoutes?.map((route) => route.pathname),\n prerenderedRoutes,\n fallbackMode: fallback,\n }\n\n if (\n res.value?.fallbackMode !== undefined &&\n // This matches the hasGenerateStaticParams logic we do during build.\n (!isAppPath || (prerenderedRoutes && prerenderedRoutes.length > 0))\n ) {\n // we write the static paths to partial manifest for\n // fallback handling inside of entry handler's\n const rawExistingManifest = await fs.promises.readFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n 'utf8'\n )\n const existingManifest: PrerenderManifest =\n JSON.parse(rawExistingManifest)\n for (const staticPath of value.staticPaths || []) {\n existingManifest.routes[staticPath] = {} as any\n }\n\n // Find the fallback route from the prerendered routes. This is\n // the route whose pathname matches the page pattern (e.g.\n // /dynamic-params/[slug]) and has fallback route params describing\n // which params are unknown at build time.\n const fallbackPrerenderedRoute = prerenderedRoutes?.find(\n (route) => route.pathname === pathname\n )\n\n existingManifest.dynamicRoutes[pathname] = {\n dataRoute: null,\n dataRouteRegex: null,\n fallback: fallbackModeToFallbackField(res.value.fallbackMode, page),\n fallbackRevalidate: false,\n fallbackExpire: undefined,\n fallbackHeaders: undefined,\n fallbackStatus: undefined,\n fallbackRootParams: fallbackPrerenderedRoute?.fallbackRootParams,\n fallbackRouteParams: fallbackPrerenderedRoute?.fallbackRouteParams,\n fallbackSourceRoute: pathname,\n prefetchDataRoute: undefined,\n prefetchDataRouteRegex: undefined,\n routeRegex: getRouteRegex(pathname).re.source,\n experimentalPPR: undefined,\n renderingMode: undefined,\n allowHeader: [],\n }\n\n const updatedManifest = JSON.stringify(existingManifest)\n\n if (updatedManifest !== rawExistingManifest) {\n await fs.promises.writeFile(\n pathJoin(this.distDir, PRERENDER_MANIFEST),\n updatedManifest\n )\n }\n }\n this.staticPathsCache.set(pathname, value)\n\n // Since generateStaticParams runs in the background, the fallbackParams\n // accessed during a render are derived from the previous result served\n // by the static paths cache. Now that the cache holds the new result,\n // trigger a refresh so the next render picks up the new fallbackParams\n // (e.g. so blocking-route validation reflects params that just became\n // statically known).\n if (\n isAppPath &&\n this.nextConfig.cacheComponents &&\n // Ensure this is not the first invocation.\n result &&\n // Comparing lengths rather than the whole objects, which is too\n // expensive.\n result.prerenderedRoutes?.length !== prerenderedRoutes?.length\n ) {\n this.bundlerService.sendHmrMessage({\n type: HMR_MESSAGE_SENT_TO_BROWSER.STATIC_PARAMS_CHANGED,\n })\n }\n\n return value\n })\n .catch((err) => {\n this.staticPathsCache.remove(pathname)\n if (!result) throw err\n Log.error(`Failed to generate static paths for ${pathname}:`)\n console.error(err)\n })\n\n if (result) {\n return result\n }\n return nextInvoke as NonNullable<typeof result>\n }\n\n protected async ensurePage(opts: {\n page: string\n clientOnly: boolean\n appPaths?: ReadonlyArray<string> | null\n definition: RouteDefinition | undefined\n url?: string\n }): Promise<void> {\n await this.bundlerService.ensurePage(opts)\n }\n\n protected async findPageComponents({\n locale,\n page,\n query,\n params,\n isAppPath,\n appPaths = null,\n shouldEnsure,\n url,\n }: {\n locale: string | undefined\n page: string\n query: NextParsedUrlQuery\n params: Params\n isAppPath: boolean\n sriEnabled?: boolean\n appPaths?: ReadonlyArray<string> | null\n shouldEnsure: boolean\n url?: string\n }): Promise<FindComponentsResult | null> {\n await this.ready?.promise\n\n const compilationErr = await this.getCompilationError(page)\n if (compilationErr) {\n // Wrap build errors so that they don't get logged again\n throw new WrappedBuildError(compilationErr)\n }\n if (shouldEnsure || this.serverOptions.customServer) {\n await this.ensurePage({\n page,\n appPaths,\n clientOnly: false,\n definition: undefined,\n url,\n })\n }\n\n this.nextFontManifest = super.getNextFontManifest()\n\n return await super.findPageComponents({\n page,\n query,\n params,\n locale,\n isAppPath,\n shouldEnsure,\n url,\n })\n }\n\n protected async getFallbackErrorComponents(\n url?: string\n ): Promise<LoadComponentsReturnType<ErrorModule> | null> {\n await this.bundlerService.getFallbackErrorComponents(url)\n return await loadDefaultErrorComponents(this.distDir)\n }\n\n async getCompilationError(page: string): Promise<any> {\n return await this.bundlerService.getCompilationError(page)\n }\n\n protected async instrumentationOnRequestError(\n ...args: Parameters<ServerOnInstrumentationRequestError>\n ) {\n await super.instrumentationOnRequestError(...args)\n\n const [err, , , silenceLog] = args\n if (!silenceLog) {\n this.logErrorWithOriginalStack(err, 'app-dir')\n }\n }\n}\n"],"names":["DevServer","registerLocalSpanRecorder","PagesDevOverlayBridgeImpl","ReactDevOverlay","props","undefined","require","PagesDevOverlayBridge","React","createElement","Server","getStaticPathsWorker","worker","Worker","resolve","maxRetries","numWorkers","enableWorkerThreads","nextConfig","experimental","workerThreads","forkOptions","env","process","NODE_OPTIONS","getFormattedNodeOptionsWithoutInspect","getStdout","pipe","stdout","getStderr","stderr","constructor","options","Error","stackTraceLimit","dev","ready","DetachedPromise","conf","bundlerService","startServerSpan","trace","renderOpts","ErrorDebug","staticPathsCache","LRUCache","length","value","cacheKey","JSON","stringify","staticPaths","pagesDir","appDir","findPagesDir","dir","serverComponentsHmrCache","hmrCacheSize","Math","max","cacheMaxMemorySize","defaultConfig","installUseCacheProbe","distDir","buildId","deploymentId","TURBOPACK","devValidationWorker","installDevValidationWorker","getServerComponentsHmrCache","getServerComponentsHmrRefreshHash","getRouteMatchers","ensurer","ensure","match","pathname","ensurePage","definition","page","clientOnly","url","matchers","DevRouteMatcherManager","extensions","pageExtensions","extensionsExpression","RegExp","join","fileReader","BatchedFileReader","DefaultFileReader","pathnameFilter","test","push","DevPagesRouteMatcherProvider","localeNormalizer","DevPagesAPIRouteMatcherProvider","ignorePartFilter","part","startsWith","isTurbopack","DevAppPageRouteMatcherProvider","DevAppRouteRouteMatcherProvider","getBuildId","prepareImpl","setGlobal","PHASE_DEVELOPMENT_SERVER","existingTelemetry","traceGlobals","get","telemetry","Telemetry","reload","interceptionRoutePatterns","getinterceptionRoutePatterns","on","reason","isPostpone","logErrorWithOriginalStack","err","hasPage","normalizedPath","normalizePagePath","console","error","isMiddlewareFile","findPageFile","then","Boolean","appFile","pagesFile","runMiddleware","params","result","onWarning","warn","waitUntil","catch","DecodeError","MiddlewareNotFoundError","getProperError","decorateServerError","COMPILER_NAMES","edgeServer","request","response","parsedUrl","includes","finished","statusCode","renderError","runEdgeFunction","onError","req","res","getRequestHandler","handler","normalizeReq","normalizeRes","loggingConfig","logging","getRequestMeta","requestStart","hrtime","bigint","addRequestMeta","isMiddlewareRequest","originalResponse","once","routeMatch","requestEnd","logRequests","devRequestTimingInternalsEnd","manualTraceChild","hrtimeToEpochNanoseconds","path","handleRequest","span","traceAsyncFn","promise","memoryUsage","traceChild","String","rss","heapUsed","heapTotal","stop","run","basePath","originalPathname","pathHasPrefix","removePathPrefix","fs","existsSync","pathJoin","publicDir","PUBLIC_DIR_MIDDLEWARE_CONFLICT","formatServerError","sent","__NEXT_PAGE","isError","internalErr","body","send","type","getPagesManifest","NodeManifestLoader","serverDistDir","PAGES_MANIFEST","getAppPathsManifest","enabledDirectories","app","APP_PATHS_MANIFEST","rewrites","generateInterceptionRoutesRewrites","Object","keys","appPathRoutes","map","route","buildCustomRoute","regex","output","Log","exit","getMiddleware","middleware","getMiddlewareRouteMatcher","getNextFontManifest","hasMiddleware","actualMiddlewareFile","ensureMiddleware","loadInstrumentationModule","instrumentationModule","actualInstrumentationHookFile","getInstrumentationModule","message","runInstrumentationHookIfAvailable","ensureInstrumentationRegistered","ensureEdgeFunction","appPaths","generateRoutes","_dev","getStaticPaths","urlPathname","requestHeaders","isAppPath","__getStaticPaths","configFileName","httpAgentOptions","locales","defaultLocale","i18n","staticPathsWorker","pathsResult","loadStaticPaths","config","pprConfig","ppr","cacheComponents","cacheHandler","cacheHandlers","cacheLifeProfiles","cacheLife","fetchCacheKeyPrefix","isrFlushToDisk","nextConfigOutput","authInterrupts","useCacheTimeout","staticPageGenerationTimeout","sriEnabled","sri","algorithm","end","nextInvoke","withCoalescedInvoke","prerenderedRoutes","fallbackMode","fallback","some","item","FallbackMode","BLOCKING_STATIC_RENDER","PRERENDER","rawExistingManifest","promises","readFile","PRERENDER_MANIFEST","existingManifest","parse","staticPath","routes","fallbackPrerenderedRoute","find","dynamicRoutes","dataRoute","dataRouteRegex","fallbackModeToFallbackField","fallbackRevalidate","fallbackExpire","fallbackHeaders","fallbackStatus","fallbackRootParams","fallbackRouteParams","fallbackSourceRoute","prefetchDataRoute","prefetchDataRouteRegex","routeRegex","getRouteRegex","re","source","experimentalPPR","renderingMode","allowHeader","updatedManifest","writeFile","set","sendHmrMessage","HMR_MESSAGE_SENT_TO_BROWSER","STATIC_PARAMS_CHANGED","remove","opts","findPageComponents","locale","query","shouldEnsure","compilationErr","getCompilationError","WrappedBuildError","serverOptions","customServer","nextFontManifest","getFallbackErrorComponents","loadDefaultErrorComponents","instrumentationOnRequestError","args","silenceLog"],"mappings":";;;;+BA8HA;;;eAAqBA;;;6BA9Gd;+DAQgB;2DACR;4BACQ;mCACc;yCACM;sBACV;2BACc;8BAClB;4BAOtB;oEACmC;mCACR;+BACJ;kCACG;yBACP;uBAMnB;wBACsB;8BACA;uBACyB;mCAClB;4CAI7B;wBAC8C;6DAChC;iEACmB;8BACe;wBACtB;mCACC;wCACK;8CACM;iDACG;gDACD;iDACC;oCACb;mCACD;mCACA;0BACT;wCACiB;iCACV;4BACL;oDACwB;kCAClB;6BACG;6BAGR;0BAC8B;gDAKnD;4BAEuB;kCAEc;mCACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE1CC,IAAAA,4CAAyB;AAEzB,wCAAwC;AACxC,IAAIC;AACJ,MAAMC,kBAA6C,CAACC;IAClD,IAAIF,8BAA8BG,WAAW;QAC3CH,4BAA4B,AAC1BI,QAAQ,+DACRC,qBAAqB;IACzB;IACA,OAAOC,OAAMC,aAAa,CAACP,2BAA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,MAAM,EACNkH,SAAS,EACTN,WAAW,IAAI,EACfqF,YAAY,EACZrP,GAAG,EAWJ,EAAwC;YACjC;QAAN,QAAM,cAAA,IAAI,CAAC5C,KAAK,qBAAV,YAAY+I,OAAO;QAEzB,MAAMmJ,iBAAiB,MAAM,IAAI,CAACC,mBAAmB,CAACzP;QACtD,IAAIwP,gBAAgB;YAClB,wDAAwD;YACxD,MAAM,IAAIE,6BAAiB,CAACF;QAC9B;QACA,IAAID,gBAAgB,IAAI,CAACI,aAAa,CAACC,YAAY,EAAE;YACnD,MAAM,IAAI,CAAC9P,UAAU,CAAC;gBACpBE;gBACAkK;gBACAjK,YAAY;gBACZF,YAAYxE;gBACZ2E;YACF;QACF;QAEA,IAAI,CAAC2P,gBAAgB,GAAG,KAAK,CAACvG;QAE9B,OAAO,MAAM,KAAK,CAAC8F,mBAAmB;YACpCpP;YACAsP;YACAhM;YACA+L;YACA7E;YACA+E;YACArP;QACF;IACF;IAEA,MAAgB4P,2BACd5P,GAAY,EAC2C;QACvD,MAAM,IAAI,CAACzC,cAAc,CAACqS,0BAA0B,CAAC5P;QACrD,OAAO,MAAM6P,IAAAA,sDAA0B,EAAC,IAAI,CAAC9Q,OAAO;IACtD;IAEA,MAAMwQ,oBAAoBzP,IAAY,EAAgB;QACpD,OAAO,MAAM,IAAI,CAACvC,cAAc,CAACgS,mBAAmB,CAACzP;IACvD;IAEA,MAAgBgQ,8BACd,GAAGC,IAAqD,EACxD;QACA,MAAM,KAAK,CAACD,iCAAiCC;QAE7C,MAAM,CAACxN,SAASyN,WAAW,GAAGD;QAC9B,IAAI,CAACC,YAAY;YACf,IAAI,CAAC1N,yBAAyB,CAACC,KAAK;QACtC;IACF;AACF","ignoreList":[0]} |
| import { RenderStage, type AdvanceableRenderStage } from './app-render/staged-rendering'; | ||
| import type { RequestStore } from './app-render/work-unit-async-storage.external'; | ||
| import type { RequestStore, WorkUnitStore } from './app-render/work-unit-async-storage.external'; | ||
| export declare function isHangingPromiseRejectionError(err: unknown): err is HangingPromiseRejectionError; | ||
@@ -15,2 +15,27 @@ declare class HangingPromiseRejectionError extends Error { | ||
| export declare function isClientHookDynamicError(err: unknown): err is ClientHookDynamicError; | ||
| /** | ||
| * Records on a static prerender store that the render accessed a data source | ||
| * which would have resolved during a runtime prerender. No-op for all other | ||
| * store types. | ||
| * | ||
| * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this | ||
| * automatically; call it directly only where the access is observed | ||
| * separately from the promise's creation (see the null `workUnitStore` case | ||
| * of `makeRuntimeHangingPromise`), or where the prerender is aborted | ||
| * synchronously instead of hanging. | ||
| * | ||
| * For fallback-param data, use `trackFallbackParamsAccessed` instead. When | ||
| * unsure, this is the conservative choice: it unconditionally clears the | ||
| * static-prefetch hint. | ||
| */ | ||
| export declare function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void; | ||
| /** | ||
| * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of | ||
| * fallback route params and values derived solely from them. It records the | ||
| * response-level flag all the same, but only clears the build-time | ||
| * static-prefetch hint when the route is not fallback-upgradeable — on an | ||
| * upgradeable route the access is transient, since ISR later produces a | ||
| * concrete prerender that resolves it. | ||
| */ | ||
| export declare function trackFallbackParamsAccessed(workUnitStore: WorkUnitStore): void; | ||
| export declare function makeClientHookHangingPromise<T>(signal: AbortSignal, error: ClientHookDynamicError): Promise<T>; | ||
@@ -17,0 +42,0 @@ /** |
@@ -13,4 +13,9 @@ "use strict"; | ||
| makeDevtoolsIOAwarePromise: null, | ||
| makeHangingPromise: null, | ||
| makePromiseFromTrigger: null | ||
| makeDynamicHangingPromise: null, | ||
| makeFallbackParamsHangingPromise: null, | ||
| makePromiseFromTrigger: null, | ||
| makeRuntimeHangingPromise: null, | ||
| makeStageHangingPromise: null, | ||
| trackFallbackParamsAccessed: null, | ||
| trackRuntimeDataAccessed: null | ||
| }); | ||
@@ -45,7 +50,22 @@ function _export(target, all) { | ||
| }, | ||
| makeHangingPromise: function() { | ||
| return makeHangingPromise; | ||
| makeDynamicHangingPromise: function() { | ||
| return makeDynamicHangingPromise; | ||
| }, | ||
| makeFallbackParamsHangingPromise: function() { | ||
| return makeFallbackParamsHangingPromise; | ||
| }, | ||
| makePromiseFromTrigger: function() { | ||
| return makePromiseFromTrigger; | ||
| }, | ||
| makeRuntimeHangingPromise: function() { | ||
| return makeRuntimeHangingPromise; | ||
| }, | ||
| makeStageHangingPromise: function() { | ||
| return makeStageHangingPromise; | ||
| }, | ||
| trackFallbackParamsAccessed: function() { | ||
| return trackFallbackParamsAccessed; | ||
| }, | ||
| trackRuntimeDataAccessed: function() { | ||
| return trackRuntimeDataAccessed; | ||
| } | ||
@@ -86,5 +106,69 @@ }); | ||
| const abortListenersBySignal = new WeakMap(); | ||
| function makeHangingPromise(signal, route, expression) { | ||
| function makeDynamicHangingPromise(signal, route, expression) { | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| function makeRuntimeHangingPromise(signal, route, expression, workUnitStore) { | ||
| if (workUnitStore !== null) { | ||
| trackRuntimeDataAccessed(workUnitStore); | ||
| } | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| function makeFallbackParamsHangingPromise(signal, route, expression, workUnitStore) { | ||
| if (workUnitStore !== null) { | ||
| trackFallbackParamsAccessed(workUnitStore); | ||
| } | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| function makeStageHangingPromise(signal, route, expression, workUnitStore) { | ||
| trackRuntimeDataAccessed(workUnitStore); | ||
| return makeHangingPromiseWithError(signal, new HangingPromiseRejectionError(route, expression)); | ||
| } | ||
| function trackRuntimeDataAccessed(workUnitStore) { | ||
| trackRuntimeDataAccessedImpl(workUnitStore, false); | ||
| } | ||
| function trackFallbackParamsAccessed(workUnitStore) { | ||
| trackRuntimeDataAccessedImpl(workUnitStore, true); | ||
| } | ||
| function trackRuntimeDataAccessedImpl(workUnitStore, isFallbackParamAccess) { | ||
| switch(workUnitStore.type){ | ||
| case 'prerender': | ||
| { | ||
| var // Response-level flag (the payload's `u`, forwarded to segment | ||
| // responses as `needsRuntimeRequest`): resolved for every kind of | ||
| // access — a pre-upgrade fallback response must keep reporting that | ||
| // a runtime request would return more. The fulfillment row lands at | ||
| // the current position in the Flight stream, which is what makes the | ||
| // value rewindable per stage. Promise resolution is idempotent, so | ||
| // repeated accesses are free. | ||
| _workUnitStore_runtimeDataAccessed; | ||
| (_workUnitStore_runtimeDataAccessed = workUnitStore.runtimeDataAccessed) == null ? void 0 : _workUnitStore_runtimeDataAccessed.resolve(true); | ||
| // Hint cell (holds the build-constant | ||
| // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a | ||
| // fallback-param access is transient when the route is | ||
| // fallback-upgradeable — ISR later produces the concrete prerender a | ||
| // static prefetch attempt would hit — so it leaves the hint intact. | ||
| // (Until that upgrade, the response-level flag above keeps directing | ||
| // the client to a runtime fallback; the hint only costs a wasted | ||
| // static attempt in the interim.) Every other access clears it. | ||
| const hintCell = workUnitStore.shouldAttemptStaticPrefetch; | ||
| if (hintCell !== null && (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)) { | ||
| hintCell.current = false; | ||
| } | ||
| break; | ||
| } | ||
| case 'prerender-client': | ||
| case 'prerender-ppr': | ||
| case 'prerender-legacy': | ||
| case 'prerender-runtime': | ||
| case 'validation-client': | ||
| case 'request': | ||
| case 'cache': | ||
| case 'private-cache': | ||
| case 'unstable-cache': | ||
| case 'generate-static-params': | ||
| break; | ||
| default: | ||
| workUnitStore; | ||
| } | ||
| } | ||
| function makeClientHookHangingPromise(signal, error) { | ||
@@ -91,0 +175,0 @@ return makeHangingPromiseWithError(signal, error); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type { RequestStore } from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * This function constructs a promise that will never resolve. This is primarily\n * useful for cacheComponents where we use promise resolution timing to determine which\n * parts of a render can be included in a prerender.\n *\n * @internal\n */\nexport function makeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["ClientHookDynamicError","RENDER_STAGES_BY_DATA_KIND","applyOwnerStack","isClientHookDynamicError","isHangingPromiseRejectionError","makeClientHookHangingPromise","makeDevtoolsIOAwarePromise","makeHangingPromise","makePromiseFromTrigger","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","abortListenersBySignal","WeakMap","signal","makeHangingPromiseWithError","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","trigger","value","promise","then","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","resolve","setTimeout","sessionData","RenderStage","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","process","env","NODE_ENV","getClientReact","getServerReact","ownerStack","workUnitStore","workUnitAsyncStorage","getStore","innerOwnerStack","captureOwnerStack","type","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":";;;;;;;;;;;;;;;;;;;;;;IAmCaA,sBAAsB;eAAtBA;;IA+HAC,0BAA0B;eAA1BA;;IAMGC,eAAe;eAAfA;;IAtHAC,wBAAwB;eAAxBA;;IA1CAC,8BAA8B;eAA9BA;;IAyEAC,4BAA4B;eAA5BA;;IA0DAC,0BAA0B;eAA1BA;;IArEAC,kBAAkB;eAAlBA;;IA4DAC,sBAAsB;eAAtBA;;;iCA/HT;8CAE8B;uCACU;AAExC,SAASJ,+BACdK,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,KAAK,CACH,CAAC,qBAAqB,EAAEA,WAAW,qGAAqG,EAAEA,WAAW,8KAA8K,EAAED,MAAM,EAAE,CAAC,QAJhUA,QAAAA,YACAC,aAAAA,iBAJFN,SAASC;IASzB;AACF;AAEA,MAAMM,sBAAsB;AAErB,MAAMjB,+BAA+Ba;IAG1CC,YAAYC,KAAa,EAAEC,UAAkB,CAAE;QAC7C,KAAK,CACH,CAAC,OAAO,EA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AAI,EAAC,KAC7DtB;gBACF;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAKA;gBACHe,aAAaI;gBACb;YACF;gBACEH;QACJ;QAEA,IAAID,YAAY;YACd,IAAIQ,QAAQR;YAEZ,IAAI3C,MAAMmD,KAAK,EAAE;gBACf,MAAMC,SAAmB,EAAE;gBAE3B,KAAK,MAAMC,SAASrD,MAAMmD,KAAK,CAACG,KAAK,CAAC,MAAMC,KAAK,CAAC,GAAI;oBACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAO1C,IAAI,CAAC2C;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEAnD,MAAMmD,KAAK,GAAGnD,MAAM0D,IAAI,GAAG,OAAO1D,MAAM2D,OAAO,GAAGR;QACpD;IACF;IAEA,OAAOnD;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../src/server/dynamic-rendering-utils.ts"],"sourcesContent":["import {\n RenderStage,\n type AdvanceableRenderStage,\n} from './app-render/staged-rendering'\nimport type {\n RequestStore,\n WorkUnitStore,\n} from './app-render/work-unit-async-storage.external'\nimport { workUnitAsyncStorage } from './app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from './runtime-reacts.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\nconst CLIENT_HOOK_DYNAMIC = 'CLIENT_HOOK_DYNAMIC'\n\nexport class ClientHookDynamicError extends Error {\n public readonly digest = CLIENT_HOOK_DYNAMIC\n\n constructor(route: string, expression: string) {\n super(\n `Route \"${route}\": Next.js encountered URL data \\`${expression}\\` in a Client Component outside of \\`<Suspense>\\`.\\n\\n` +\n `This blocks prerendering because the value is only available at runtime.\\n\\n` +\n `Ways to fix this:\\n` +\n ` - [stream] Wrap the component in \\`<Suspense fallback={...}>\\` so the hook value streams in after prerendering\\n` +\n ` - [block] Set \\`export const instant = false\\` to allow a blocking route\\n\\n` +\n `Learn more: https://nextjs.org/docs/messages/blocking-prerender-client-hook`\n )\n }\n}\n\nexport function isClientHookDynamicError(\n err: unknown\n): err is ClientHookDynamicError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === CLIENT_HOOK_DYNAMIC\n}\n\ntype AbortListeners = Array<() => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * Constructs a promise that never resolves, standing in for *dynamic* data:\n * data that is only available during a real dynamic request and hangs in\n * every kind of prerender — `io()`, `connection()`, uncached `fetch()`.\n *\n * This is primarily useful for cacheComponents where we use promise\n * resolution timing to determine which parts of a render can be included in a\n * prerender.\n *\n * Records nothing on the prerender store: the promise's holes are only ever\n * filled by a real dynamic request, so a runtime prefetch response would have\n * the same holes as the static one. If the data source would resolve during a\n * runtime prerender, use `makeRuntimeHangingPromise` instead.\n *\n * @internal\n */\nexport function makeDynamicHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for *runtime* data:\n * data that hangs during a static prerender but is available during a runtime\n * prerender (the kind that backs a runtime prefetch request: request data\n * like cookies and headers is available, but the render is still not a real\n * dynamic request). Examples: cookies, headers, fallback params,\n * searchParams, and cache entries that are excluded only from static\n * prerenders.\n *\n * Creating one of these during a static prerender records on the prerender\n * store that a runtime prefetch would produce more content than the static\n * response (`runtimeDataAccessed`), which the segment prefetch encoding uses\n * to tell the client whether a runtime prefetch request could be skipped.\n *\n * When unsure whether data is dynamic or runtime, prefer this method — the\n * cost of over-recording is a redundant runtime prefetch request; the cost of\n * under-recording is a permanently missing one.\n *\n * `workUnitStore` may be null ONLY when the caller tracks the access itself\n * at observation time instead of creation time. This is for promises the\n * framework creates eagerly whether or not anything reads them (e.g. the\n * `searchParams` prop constructed for every page): recording at creation\n * would mark every render. Such a caller MUST call `trackRuntimeDataAccessed`\n * from every path that observes the promise (e.g. the proxy traps for\n * `then`/`status`), against the work unit store active at access time.\n *\n * For fallback-param data — data a concrete (ISR-upgraded) prerender would\n * resolve — use `makeFallbackParamsHangingPromise` instead, so the access\n * is recorded with the right effect on the static-prefetch hint.\n *\n * @internal\n */\nexport function makeRuntimeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackRuntimeDataAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Variant of `makeRuntimeHangingPromise` for *fallback-param* data: fallback\n * route params and values derived solely from them (`params`, `rootParams`,\n * `pathname` during a fallback prerender). Like every runtime data access it\n * records the access on the prerender store's response-level flag, but its\n * effect on the build-time static-prefetch hint differs — on a\n * fallback-upgradeable route the access is transient (a concrete prerender\n * resolves it), so it leaves the hint intact. See\n * `trackFallbackParamsAccessed`.\n *\n * As with `makeRuntimeHangingPromise`, `workUnitStore` may be null ONLY when\n * the caller tracks the access itself at observation time instead of creation\n * time, by calling `trackFallbackParamsAccessed` from every path that\n * observes the promise.\n *\n * @internal\n */\nexport function makeFallbackParamsHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore | null\n): Promise<T> {\n if (workUnitStore !== null) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Constructs a promise that never resolves, standing in for data that is only\n * accessible in a later *stage* of rendering than this render reaches — e.g.\n * a prefetchable short-stale cache entry that's excluded from shells when the\n * render ends at the shell stage, or params during a runtime-prefetch render\n * that stops before the stage where params resolve.\n *\n * A render that runs through the later stage would include the data; in\n * particular a runtime prefetch renders through its later stages, so on a\n * static prerender store this records `runtimeDataAccessed`, same as\n * `makeRuntimeHangingPromise`.\n *\n * @internal\n */\nexport function makeStageHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string,\n workUnitStore: WorkUnitStore\n): Promise<T> {\n trackRuntimeDataAccessed(workUnitStore)\n return makeHangingPromiseWithError(\n signal,\n new HangingPromiseRejectionError(route, expression)\n )\n}\n\n/**\n * Records on a static prerender store that the render accessed a data source\n * which would have resolved during a runtime prerender. No-op for all other\n * store types.\n *\n * `makeRuntimeHangingPromise` and `makeStageHangingPromise` call this\n * automatically; call it directly only where the access is observed\n * separately from the promise's creation (see the null `workUnitStore` case\n * of `makeRuntimeHangingPromise`), or where the prerender is aborted\n * synchronously instead of hanging.\n *\n * For fallback-param data, use `trackFallbackParamsAccessed` instead. When\n * unsure, this is the conservative choice: it unconditionally clears the\n * static-prefetch hint.\n */\nexport function trackRuntimeDataAccessed(workUnitStore: WorkUnitStore): void {\n trackRuntimeDataAccessedImpl(workUnitStore, false)\n}\n\n/**\n * Fallback-param variant of `trackRuntimeDataAccessed`, for accesses of\n * fallback route params and values derived solely from them. It records the\n * response-level flag all the same, but only clears the build-time\n * static-prefetch hint when the route is not fallback-upgradeable — on an\n * upgradeable route the access is transient, since ISR later produces a\n * concrete prerender that resolves it.\n */\nexport function trackFallbackParamsAccessed(\n workUnitStore: WorkUnitStore\n): void {\n trackRuntimeDataAccessedImpl(workUnitStore, true)\n}\n\nfunction trackRuntimeDataAccessedImpl(\n workUnitStore: WorkUnitStore,\n isFallbackParamAccess: boolean\n): void {\n switch (workUnitStore.type) {\n case 'prerender': {\n // Response-level flag (the payload's `u`, forwarded to segment\n // responses as `needsRuntimeRequest`): resolved for every kind of\n // access — a pre-upgrade fallback response must keep reporting that\n // a runtime request would return more. The fulfillment row lands at\n // the current position in the Flight stream, which is what makes the\n // value rewindable per stage. Promise resolution is idempotent, so\n // repeated accesses are free.\n workUnitStore.runtimeDataAccessed?.resolve(true)\n\n // Hint cell (holds the build-constant\n // PrefetchHint.ShouldAttemptStaticPrefetch value directly): a\n // fallback-param access is transient when the route is\n // fallback-upgradeable — ISR later produces the concrete prerender a\n // static prefetch attempt would hit — so it leaves the hint intact.\n // (Until that upgrade, the response-level flag above keeps directing\n // the client to a runtime fallback; the hint only costs a wasted\n // static attempt in the interim.) Every other access clears it.\n const hintCell = workUnitStore.shouldAttemptStaticPrefetch\n if (\n hintCell !== null &&\n (!isFallbackParamAccess || !workUnitStore.isFallbackUpgradeable)\n ) {\n hintCell.current = false\n }\n break\n }\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'validation-client':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n // Only the modern server prerender tracks this; see the field docs on\n // PrerenderStoreModernServer.\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function makeClientHookHangingPromise<T>(\n signal: AbortSignal,\n error: ClientHookDynamicError\n): Promise<T> {\n return makeHangingPromiseWithError(signal, error)\n}\n\nfunction makeHangingPromiseWithError<T>(\n signal: AbortSignal,\n error: Error\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(error)\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(null, error)\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\n/**\n * Creates a promise that will be triggered when another promise resolves.\n * It will not emit unhandled rejections, which is important if the trigger\n * is a promise that might itself get rejected (e.g. when a prerender/render\n * are aborted due to sync IO)\n */\nexport function makePromiseFromTrigger<T>(\n trigger: Promise<any>,\n value: T\n): Promise<T> {\n const promise = trigger.then(() => value)\n promise.catch(ignoreReject)\n return promise\n}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\nexport const RENDER_STAGES_BY_DATA_KIND = {\n sessionData: RenderStage.ShellRuntime as const,\n staticLinkData: RenderStage.Static as const,\n runtimeLinkData: RenderStage.Runtime as const,\n}\n\nexport function applyOwnerStack(error: Error): Error {\n if (process.env.NODE_ENV !== 'production') {\n let ownerStack: string | undefined | null\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n // captureOwnerStack() returns the owner stack for the current React\n // rendering context. Inside a cache scope this only includes the inner\n // component tree. The outer owner stack (captured before entering the\n // cache boundary in use-cache-wrapper.ts) is stored on the cache store.\n // We concatenate both to get the full component tree.\n const innerOwnerStack =\n getClientReact()?.captureOwnerStack?.() ??\n getServerReact()?.captureOwnerStack?.()\n\n switch (workUnitStore?.type) {\n case 'cache':\n case 'private-cache':\n ownerStack =\n (innerOwnerStack || '') + (workUnitStore.outerOwnerStack || '') ||\n undefined\n break\n case 'unstable-cache':\n case 'request':\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n case undefined:\n ownerStack = innerOwnerStack\n break\n default:\n workUnitStore satisfies never\n }\n\n if (ownerStack) {\n let stack = ownerStack\n\n if (error.stack) {\n const frames: string[] = []\n\n for (const frame of error.stack.split('\\n').slice(1)) {\n if (frame.includes('react_stack_bottom_frame')) {\n break\n }\n\n frames.push(frame)\n }\n\n stack = '\\n' + frames.join('\\n') + stack\n }\n\n error.stack = error.name + ': ' + error.message + stack\n }\n }\n\n return error\n}\n"],"names":["ClientHookDynamicError","RENDER_STAGES_BY_DATA_KIND","applyOwnerStack","isClientHookDynamicError","isHangingPromiseRejectionError","makeClientHookHangingPromise","makeDevtoolsIOAwarePromise","makeDynamicHangingPromise","makeFallbackParamsHangingPromise","makePromiseFromTrigger","makeRuntimeHangingPromise","makeStageHangingPromise","trackFallbackParamsAccessed","trackRuntimeDataAccessed","err","digest","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","Error","constructor","route","expression","CLIENT_HOOK_DYNAMIC","abortListenersBySignal","WeakMap","signal","makeHangingPromiseWithError","workUnitStore","trackRuntimeDataAccessedImpl","isFallbackParamAccess","type","runtimeDataAccessed","resolve","hintCell","shouldAttemptStaticPrefetch","isFallbackUpgradeable","current","error","aborted","Promise","reject","hangingPromise","_","boundRejection","bind","currentListeners","get","push","listeners","set","addEventListener","i","length","once","catch","ignoreReject","trigger","value","promise","then","underlying","requestStore","stage","stagedRendering","delayUntilStage","undefined","setTimeout","sessionData","RenderStage","ShellRuntime","staticLinkData","Static","runtimeLinkData","Runtime","process","env","NODE_ENV","getClientReact","getServerReact","ownerStack","workUnitAsyncStorage","getStore","innerOwnerStack","captureOwnerStack","outerOwnerStack","stack","frames","frame","split","slice","includes","join","name","message"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;IAsCaA,sBAAsB;eAAtBA;;IAqUAC,0BAA0B;eAA1BA;;IAMGC,eAAe;eAAfA;;IA5TAC,wBAAwB;eAAxBA;;IA1CAC,8BAA8B;eAA9BA;;IA+QAC,4BAA4B;eAA5BA;;IA0DAC,0BAA0B;eAA1BA;;IAlQAC,yBAAyB;eAAzBA;;IA2EAC,gCAAgC;eAAhCA;;IA8KAC,sBAAsB;eAAtBA;;IA9MAC,yBAAyB;eAAzBA;;IA6DAC,uBAAuB;eAAvBA;;IAwCAC,2BAA2B;eAA3BA;;IAZAC,wBAAwB;eAAxBA;;;iCAnNT;8CAK8B;uCACU;AAExC,SAAST,+BACdU,GAAY;IAEZ,IAAI,OAAOA,QAAQ,YAAYA,QAAQ,QAAQ,CAAE,CAAA,YAAYA,GAAE,GAAI;QACjE,OAAO;IACT;IAEA,OAAOA,IAAIC,MAAM,KAAKC;AACxB;AAEA,MAAMA,4BAA4B;AAElC,MAAMC,qCAAqCC;IAGzCC,YACE,AAAgBC,KAAa,EAC7B,AAAgBC,UAAkB,CAClC;QACA,KAAK,CACH,CAAC,qBAAqB,EAAEA,WAAW,qGAAqG,EAAEA,WAAW,8KAA8K,EAAED,MAAM,EAAE,CAAC,QAJhUA,QAAAA,YACAC,aAAAA,iBAJFN,SAASC;IASzB;AACF;AAEA,MAAMM,sBAAsB;AAErB,MAAMtB,+BAA+BkB;IAG1CC,YAAYC,KAAa,EAAEC,UAAkB,CAAE;QAC7C,KAAK,CACH,CAAC,OAAO,EAAED,MAAM,kCAAkC,EAAEC,WAAW,uDAAuD,CAAC,GACrH,CAAC,4EAA4E,CAAC,GAC9E,CAAC,mBAAmB,CAAC,GACrB,CAAC,kHA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e,IAAI,EAAC,KAC7DnB;gBACF;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAKA;gBACHc,aAAaG;gBACb;YACF;gBACEvD;QACJ;QAEA,IAAIoD,YAAY;YACd,IAAIM,QAAQN;YAEZ,IAAI1C,MAAMgD,KAAK,EAAE;gBACf,MAAMC,SAAmB,EAAE;gBAE3B,KAAK,MAAMC,SAASlD,MAAMgD,KAAK,CAACG,KAAK,CAAC,MAAMC,KAAK,CAAC,GAAI;oBACpD,IAAIF,MAAMG,QAAQ,CAAC,6BAA6B;wBAC9C;oBACF;oBAEAJ,OAAOvC,IAAI,CAACwC;gBACd;gBAEAF,QAAQ,OAAOC,OAAOK,IAAI,CAAC,QAAQN;YACrC;YAEAhD,MAAMgD,KAAK,GAAGhD,MAAMuD,IAAI,GAAG,OAAOvD,MAAMwD,OAAO,GAAGR;QACpD;IACF;IAEA,OAAOhD;AACT","ignoreList":[0]} |
@@ -82,3 +82,3 @@ "use strict"; | ||
| const versionSuffix = logBundler ? ` (${(0, _bundler.bundlerName)((0, _bundler.getBundlerFromEnv)())})` : ''; | ||
| _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.0-canary.97"}`))}${versionSuffix}`); | ||
| _log.bootstrap(`${(0, _picocolors.bold)((0, _picocolors.purple)(`${_log.prefixes.ready} Next.js ${"16.3.0-canary.99"}`))}${versionSuffix}`); | ||
| if (appUrl) { | ||
@@ -85,0 +85,0 @@ _log.bootstrap(`- Local: ${appUrl}`); |
@@ -39,3 +39,3 @@ /** | ||
| } | ||
| const memoryCache = new _lrucache.LRUCache(maxSize, (entry)=>entry.size); | ||
| const memoryCache = new _lrucache.LRUCache(maxSize, (entry, cacheKey)=>entry.size + cacheKey.length); | ||
| const pendingSets = new Map(); | ||
@@ -42,0 +42,0 @@ const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE ? console.debug.bind(console, 'DefaultCacheHandler:') : undefined; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/cache-handlers/default.ts"],"sourcesContent":["/**\n * This is the default \"use cache\" handler it defaults to an in-memory store.\n * 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, we also\n * don't want to reuse a stale entry for too long so stale entries should be\n * considered expired/missing in such cache handlers.\n *\n * The dev server (`next dev`) is the exception: to keep reloads fast it serves\n * stale entries until they expire, relying on the wrapper's\n * stale-while-revalidate path to warm a fresh entry in the background. See\n * `get` for where this branches.\n */\n\nimport { LRUCache } from '../lru-cache'\nimport type { CacheEntry, CacheHandler } from './types'\nimport {\n areTagsExpired,\n areTagsStale,\n tagsManifest,\n type TagManifestEntry,\n} from '../incremental-cache/tags-manifest.external'\nimport { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'\n\ntype PrivateCacheEntry = {\n entry: CacheEntry\n\n // For the default cache we store errored cache\n // entries and allow them to be used up to 3 times\n // after that we want to dispose it and try for fresh\n\n // If an entry is errored we return no entry\n // three times so that we retry hitting origin (MISS)\n // and then if it still fails to set after the third we\n // return the errored content and use expiration of\n // Math.min(30, entry.expiration)\n isErrored: boolean\n errorRetryCount: number\n\n // compute size on set since we need to read size\n // of the ReadableStream for LRU evicting\n size: number\n}\n\nexport function createDefaultCacheHandler(maxSize: number): CacheHandler {\n // If the max size is 0, return a cache handler that doesn't cache anything,\n // this avoids an unnecessary LRUCache instance and potential memory\n // allocation.\n if (maxSize === 0) {\n return {\n get: () => Promise.resolve(undefined),\n set: () => Promise.resolve(),\n refreshTags: () => Promise.resolve(),\n getExpiration: () => Promise.resolve(0),\n updateTags: () => Promise.resolve(),\n }\n }\n\n const memoryCache = new LRUCache<PrivateCacheEntry>(\n maxSize,\n (entry) => entry.size\n )\n const pendingSets = new Map<string, Promise<void>>()\n\n const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? console.debug.bind(console, 'DefaultCacheHandler:')\n : undefined\n\n return {\n async get(cacheKey) {\n const pendingPromise = pendingSets.get(cacheKey)\n\n if (pendingPromise) {\n debug?.('get', cacheKey, 'pending')\n await pendingPromise\n }\n\n const privateEntry = memoryCache.get(cacheKey)\n\n if (!privateEntry) {\n debug?.('get', cacheKey, 'not found')\n return undefined\n }\n\n const entry = privateEntry.entry\n\n // A negative `expire` is an eviction sentinel: the tiered cache handler\n // (dev-only) marks a front entry for deletion by overwriting it with a\n // negative `expire`, since the cache-handler interface has no per-key\n // delete. Treat it as missing here, independently of the minimum\n // retention below (which would otherwise keep it alive). This is distinct\n // from `revalidate = -1` below, which keeps serving the entry but forces\n // a revalidation.\n if (entry.expire < 0) {\n debug?.('get', cacheKey, 'evicted')\n return undefined\n }\n\n // The dev server serves stale entries until they expire (see the file\n // overview); production drops them once past the revalidate time. In dev,\n // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that\n // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`\n // client-only cache) still linger long enough that a reload hits the\n // cache. That minimum is the same threshold below which the \"use cache\"\n // wrapper treats an entry as dynamic, so it only extends the retention of\n // entries that are dynamic anyway. It affects retention only; the\n // returned entry keeps its real `expire`, so staging decisions are\n // unchanged.\n const maxAgeSeconds = process.env.__NEXT_DEV_SERVER\n ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)\n : entry.revalidate\n\n if (\n performance.timeOrigin + performance.now() >\n entry.timestamp + maxAgeSeconds * 1000\n ) {\n debug?.('get', cacheKey, 'expired')\n\n return undefined\n }\n\n let revalidate = entry.revalidate\n\n if (areTagsExpired(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had expired tag')\n return undefined\n }\n\n if (areTagsStale(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had stale tag')\n revalidate = -1\n }\n\n const [returnStream, newSaved] = entry.value.tee()\n entry.value = newSaved\n\n debug?.('get', cacheKey, 'found', {\n tags: entry.tags,\n timestamp: entry.timestamp,\n expire: entry.expire,\n revalidate,\n })\n\n return {\n ...entry,\n revalidate,\n value: returnStream,\n }\n },\n\n async set(cacheKey, pendingEntry) {\n debug?.('set', cacheKey, 'start')\n\n let resolvePending: () => void = () => {}\n const pendingPromise = new Promise<void>((resolve) => {\n resolvePending = resolve\n })\n pendingSets.set(cacheKey, pendingPromise)\n\n const entry = await pendingEntry\n\n let size = 0\n\n try {\n // In production an `expire: 0` entry is dynamic: the \"use cache\"\n // wrapper regenerates it on every read instead of serving the stored\n // copy, so persisting it would be a wasted write of a value that is\n // never served back. Skip storing it so the next read is a plain miss.\n // The dev server keeps it, because its minimum retention serves the\n // previously cached value across reloads. The `finally` below still\n // resolves the pending set.\n if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {\n debug?.('set', cacheKey, 'skipped dynamic entry')\n return\n }\n\n const [value, clonedValue] = entry.value.tee()\n entry.value = value\n const reader = clonedValue.getReader()\n\n for (let chunk; !(chunk = await reader.read()).done; ) {\n size += Buffer.from(chunk.value).byteLength\n }\n\n memoryCache.set(cacheKey, {\n entry,\n isErrored: false,\n errorRetryCount: 0,\n size,\n })\n\n debug?.('set', cacheKey, 'done')\n } catch (err) {\n // TODO: store partial buffer with error after we retry 3 times\n debug?.('set', cacheKey, 'failed', err)\n } finally {\n resolvePending()\n pendingSets.delete(cacheKey)\n }\n },\n\n async refreshTags() {\n // Nothing to do for an in-memory cache handler.\n },\n\n async getExpiration(tags) {\n const expirations = tags.map((tag) => {\n const entry = tagsManifest.get(tag)\n if (!entry) return 0\n // Return the most recent timestamp (either expired or stale)\n return entry.expired || 0\n })\n\n const expiration = Math.max(...expirations, 0)\n\n debug?.('getExpiration', { tags, expiration })\n\n return expiration\n },\n\n async updateTags(tags, durations) {\n const now = Math.round(performance.timeOrigin + performance.now())\n debug?.('updateTags', { tags, timestamp: now })\n\n for (const tag of tags) {\n // TODO: update file-system-cache?\n const existingEntry = tagsManifest.get(tag) || {}\n\n if (durations) {\n // Use provided durations directly\n const updates: TagManifestEntry = { ...existingEntry }\n\n // mark as stale immediately\n updates.stale = now\n\n if (durations.expire !== undefined) {\n updates.expired = now + durations.expire * 1000 // Convert seconds to ms\n }\n\n tagsManifest.set(tag, updates)\n } else {\n // Update expired field for immediate expiration (default behavior when no durations provided)\n tagsManifest.set(tag, { ...existingEntry, expired: now })\n }\n }\n },\n }\n}\n"],"names":["createDefaultCacheHandler","maxSize","get","Promise","resolve","undefined","set","refreshTags","getExpiration","updateTags","memoryCache","LRUCache","entry","size","pendingSets","Map","debug","process","env","NEXT_PRIVATE_DEBUG_CACHE","console","bind","cacheKey","pendingPromise","privateEntry","expire","maxAgeSeconds","__NEXT_DEV_SERVER","Math","max","MIN_PRERENDERABLE_EXPIRE","revalidate","performance","timeOrigin","now","timestamp","areTagsExpired","tags","areTagsStale","returnStream","newSaved","value","tee","pendingEntry","resolvePending","clonedValue","reader","getReader","chunk","read","done","Buffer","from","byteLength","isErrored","errorRetryCount","err","delete","expirations","map","tag","tagsManifest","expired","expiration","durations","round","existingEntry","updates","stale"],"mappings":"AAAA;;;;;;;;;;;;CAYC;;;;+BAgCeA;;;eAAAA;;;0BA9BS;sCAOlB;2BACkC;AAsBlC,SAASA,0BAA0BC,OAAe;IACvD,4EAA4E;IAC5E,oEAAoE;IACpE,cAAc;IACd,IAAIA,YAAY,GAAG;QACjB,OAAO;YACLC,KAAK,IAAMC,QAAQC,OAAO,CAACC;YAC3BC,KAAK,IAAMH,QAAQC,OAAO;YAC1BG,aAAa,IAAMJ,QAAQC,OAAO;YAClCI,eAAe,IAAML,QAAQC,OAAO,CAAC;YACrCK,YAAY,IAAMN,QAAQC,OAAO;QACnC;IACF;IAEA,MAAMM,cAAc,IAAIC,kBAAQ,CAC9BV,SACA,CAACW,QAAUA,MAAMC,IAAI;IAEvB,MAAMC,cAAc,IAAIC;IAExB,MAAMC,QAAQC,QAAQC,GAAG,CAACC,wBAAwB,GA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oBAEAoC,kCAAY,CAACvD,GAAG,CAACsD,KAAKO;gBACxB,OAAO;oBACL,8FAA8F;oBAC9FN,kCAAY,CAACvD,GAAG,CAACsD,KAAK;wBAAE,GAAGM,aAAa;wBAAEJ,SAAS5B;oBAAI;gBACzD;YACF;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/cache-handlers/default.ts"],"sourcesContent":["/**\n * This is the default \"use cache\" handler it defaults to an in-memory store.\n * 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, we also\n * don't want to reuse a stale entry for too long so stale entries should be\n * considered expired/missing in such cache handlers.\n *\n * The dev server (`next dev`) is the exception: to keep reloads fast it serves\n * stale entries until they expire, relying on the wrapper's\n * stale-while-revalidate path to warm a fresh entry in the background. See\n * `get` for where this branches.\n */\n\nimport { LRUCache } from '../lru-cache'\nimport type { CacheEntry, CacheHandler } from './types'\nimport {\n areTagsExpired,\n areTagsStale,\n tagsManifest,\n type TagManifestEntry,\n} from '../incremental-cache/tags-manifest.external'\nimport { MIN_PRERENDERABLE_EXPIRE } from '../../use-cache/constants'\n\ntype PrivateCacheEntry = {\n entry: CacheEntry\n\n // For the default cache we store errored cache\n // entries and allow them to be used up to 3 times\n // after that we want to dispose it and try for fresh\n\n // If an entry is errored we return no entry\n // three times so that we retry hitting origin (MISS)\n // and then if it still fails to set after the third we\n // return the errored content and use expiration of\n // Math.min(30, entry.expiration)\n isErrored: boolean\n errorRetryCount: number\n\n // compute size on set since we need to read size\n // of the ReadableStream for LRU evicting\n size: number\n}\n\nexport function createDefaultCacheHandler(maxSize: number): CacheHandler {\n // If the max size is 0, return a cache handler that doesn't cache anything,\n // this avoids an unnecessary LRUCache instance and potential memory\n // allocation.\n if (maxSize === 0) {\n return {\n get: () => Promise.resolve(undefined),\n set: () => Promise.resolve(),\n refreshTags: () => Promise.resolve(),\n getExpiration: () => Promise.resolve(0),\n updateTags: () => Promise.resolve(),\n }\n }\n\n const memoryCache = new LRUCache<PrivateCacheEntry>(\n maxSize,\n (entry, cacheKey) => entry.size + cacheKey.length\n )\n const pendingSets = new Map<string, Promise<void>>()\n\n const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE\n ? console.debug.bind(console, 'DefaultCacheHandler:')\n : undefined\n\n return {\n async get(cacheKey) {\n const pendingPromise = pendingSets.get(cacheKey)\n\n if (pendingPromise) {\n debug?.('get', cacheKey, 'pending')\n await pendingPromise\n }\n\n const privateEntry = memoryCache.get(cacheKey)\n\n if (!privateEntry) {\n debug?.('get', cacheKey, 'not found')\n return undefined\n }\n\n const entry = privateEntry.entry\n\n // A negative `expire` is an eviction sentinel: the tiered cache handler\n // (dev-only) marks a front entry for deletion by overwriting it with a\n // negative `expire`, since the cache-handler interface has no per-key\n // delete. Treat it as missing here, independently of the minimum\n // retention below (which would otherwise keep it alive). This is distinct\n // from `revalidate = -1` below, which keeps serving the entry but forces\n // a revalidation.\n if (entry.expire < 0) {\n debug?.('get', cacheKey, 'evicted')\n return undefined\n }\n\n // The dev server serves stale entries until they expire (see the file\n // overview); production drops them once past the revalidate time. In dev,\n // an entry is retained for at least `MIN_PRERENDERABLE_EXPIRE` so that\n // entries with a short `expire` (for example a `cacheLife({ expire: 0 })`\n // client-only cache) still linger long enough that a reload hits the\n // cache. That minimum is the same threshold below which the \"use cache\"\n // wrapper treats an entry as dynamic, so it only extends the retention of\n // entries that are dynamic anyway. It affects retention only; the\n // returned entry keeps its real `expire`, so staging decisions are\n // unchanged.\n const maxAgeSeconds = process.env.__NEXT_DEV_SERVER\n ? Math.max(entry.expire, MIN_PRERENDERABLE_EXPIRE)\n : entry.revalidate\n\n if (\n performance.timeOrigin + performance.now() >\n entry.timestamp + maxAgeSeconds * 1000\n ) {\n debug?.('get', cacheKey, 'expired')\n\n return undefined\n }\n\n let revalidate = entry.revalidate\n\n if (areTagsExpired(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had expired tag')\n return undefined\n }\n\n if (areTagsStale(entry.tags, entry.timestamp)) {\n debug?.('get', cacheKey, 'had stale tag')\n revalidate = -1\n }\n\n const [returnStream, newSaved] = entry.value.tee()\n entry.value = newSaved\n\n debug?.('get', cacheKey, 'found', {\n tags: entry.tags,\n timestamp: entry.timestamp,\n expire: entry.expire,\n revalidate,\n })\n\n return {\n ...entry,\n revalidate,\n value: returnStream,\n }\n },\n\n async set(cacheKey, pendingEntry) {\n debug?.('set', cacheKey, 'start')\n\n let resolvePending: () => void = () => {}\n const pendingPromise = new Promise<void>((resolve) => {\n resolvePending = resolve\n })\n pendingSets.set(cacheKey, pendingPromise)\n\n const entry = await pendingEntry\n\n let size = 0\n\n try {\n // In production an `expire: 0` entry is dynamic: the \"use cache\"\n // wrapper regenerates it on every read instead of serving the stored\n // copy, so persisting it would be a wasted write of a value that is\n // never served back. Skip storing it so the next read is a plain miss.\n // The dev server keeps it, because its minimum retention serves the\n // previously cached value across reloads. The `finally` below still\n // resolves the pending set.\n if (!process.env.__NEXT_DEV_SERVER && entry.expire === 0) {\n debug?.('set', cacheKey, 'skipped dynamic entry')\n return\n }\n\n const [value, clonedValue] = entry.value.tee()\n entry.value = value\n const reader = clonedValue.getReader()\n\n for (let chunk; !(chunk = await reader.read()).done; ) {\n size += Buffer.from(chunk.value).byteLength\n }\n\n memoryCache.set(cacheKey, {\n entry,\n isErrored: false,\n errorRetryCount: 0,\n size,\n })\n\n debug?.('set', cacheKey, 'done')\n } catch (err) {\n // TODO: store partial buffer with error after we retry 3 times\n debug?.('set', cacheKey, 'failed', err)\n } finally {\n resolvePending()\n pendingSets.delete(cacheKey)\n }\n },\n\n async refreshTags() {\n // Nothing to do for an in-memory cache handler.\n },\n\n async getExpiration(tags) {\n const expirations = tags.map((tag) => {\n const entry = tagsManifest.get(tag)\n if (!entry) return 0\n // Return the most recent timestamp (either expired or stale)\n return entry.expired || 0\n })\n\n const expiration = Math.max(...expirations, 0)\n\n debug?.('getExpiration', { tags, expiration })\n\n return expiration\n },\n\n async updateTags(tags, durations) {\n const now = Math.round(performance.timeOrigin + performance.now())\n debug?.('updateTags', { tags, timestamp: now })\n\n for (const tag of tags) {\n // TODO: update file-system-cache?\n const existingEntry = tagsManifest.get(tag) || {}\n\n if (durations) {\n // Use provided durations directly\n const updates: TagManifestEntry = { ...existingEntry }\n\n // mark as stale immediately\n updates.stale = now\n\n if (durations.expire !== undefined) {\n updates.expired = now + durations.expire * 1000 // Convert seconds to ms\n }\n\n tagsManifest.set(tag, updates)\n } else {\n // Update expired field for immediate expiration (default behavior when no durations provided)\n tagsManifest.set(tag, { ...existingEntry, expired: now })\n }\n }\n },\n }\n}\n"],"names":["createDefaultCacheHandler","maxSize","get","Promise","resolve","undefined","set","refreshTags","getExpiration","updateTags","memoryCache","LRUCache","entry","cacheKey","size","length","pendingSets","Map","debug","process","env","NEXT_PRIVATE_DEBUG_CACHE","console","bind","pendingPromise","privateEntry","expire","maxAgeSeconds","__NEXT_DEV_SERVER","Math","max","MIN_PRERENDERABLE_EXPIRE","revalidate","performance","timeOrigin","now","timestamp","areTagsExpired","tags","areTagsStale","returnStream","newSaved","value","tee","pendingEntry","resolvePending","clonedValue","reader","getReader","chunk","read","done","Buffer","from","byteLength","isErrored","errorRetryCount","err","delete","expirations","map","tag","tagsManifest","expired","expiration","durations","round","existingEntry","updates","stale"],"mappings":"AAAA;;;;;;;;;;;;CAYC;;;;+BAgCeA;;;eAAAA;;;0BA9BS;sCAOlB;2BACkC;AAsBlC,SAASA,0BAA0BC,OAAe;IACvD,4EAA4E;IAC5E,oEAAoE;IACpE,cAAc;IACd,IAAIA,YAAY,GAAG;QACjB,OAAO;YACLC,KAAK,IAAMC,QAAQC,OAAO,CAACC;YAC3BC,KAAK,IAAMH,QAAQC,OAAO;YAC1BG,aAAa,IAAMJ,QAAQC,OAAO;YAClCI,eAAe,IAAML,QAAQC,OAAO,CAAC;YACrCK,YAAY,IAAMN,QAAQC,OAAO;QACnC;IACF;IAEA,MAA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;oBAC5BC,QAAQC,KAAK,GAAGlC;oBAEhB,IAAI8B,UAAUvC,MAAM,KAAKrB,WAAW;wBAClC+D,QAAQL,OAAO,GAAG5B,MAAM8B,UAAUvC,MAAM,GAAG,KAAK,wBAAwB;;oBAC1E;oBAEAoC,kCAAY,CAACxD,GAAG,CAACuD,KAAKO;gBACxB,OAAO;oBACL,8FAA8F;oBAC9FN,kCAAY,CAACxD,GAAG,CAACuD,KAAK;wBAAE,GAAGM,aAAa;wBAAEJ,SAAS5B;oBAAI;gBACzD;YACF;QACF;IACF;AACF","ignoreList":[0]} |
@@ -29,8 +29,8 @@ "use strict"; | ||
| if (!memoryCache) { | ||
| memoryCache = new _lrucache.LRUCache(maxMemoryCacheSize, function length({ value }) { | ||
| var _JSON_stringify; | ||
| memoryCache = new _lrucache.LRUCache(maxMemoryCacheSize, function length({ value }, cacheKey) { | ||
| let valueSize; | ||
| if (!value) { | ||
| return 25; | ||
| valueSize = 25; | ||
| } else if (value.kind === _types.CachedRouteKind.REDIRECT) { | ||
| return JSON.stringify(value.props).length; | ||
| valueSize = JSON.stringify(value.props).length; | ||
| } else if (value.kind === _types.CachedRouteKind.IMAGE) { | ||
@@ -43,12 +43,14 @@ throw Object.defineProperty(new Error('invariant image should not be incremental-cache'), "__NEXT_ERROR_CODE", { | ||
| } else if (value.kind === _types.CachedRouteKind.FETCH) { | ||
| return JSON.stringify(value.data || '').length; | ||
| valueSize = JSON.stringify(value.data || '').length; | ||
| } else if (value.kind === _types.CachedRouteKind.APP_ROUTE) { | ||
| return value.body.length; | ||
| } | ||
| // rough estimate of size of cache value | ||
| if (value.kind === _types.CachedRouteKind.APP_PAGE) { | ||
| valueSize = value.body.length; | ||
| } else if (value.kind === _types.CachedRouteKind.APP_PAGE) { | ||
| var _value_postponed; | ||
| return Math.max(1, value.html.length + getBufferSize(value.rscData) + (((_value_postponed = value.postponed) == null ? void 0 : _value_postponed.length) || 0) + getSegmentDataSize(value.segmentData)); | ||
| // rough estimate of size of cache value | ||
| valueSize = Math.max(1, value.html.length + getBufferSize(value.rscData) + (((_value_postponed = value.postponed) == null ? void 0 : _value_postponed.length) || 0) + getSegmentDataSize(value.segmentData)); | ||
| } else { | ||
| var _JSON_stringify; | ||
| valueSize = value.html.length + (((_JSON_stringify = JSON.stringify(value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0); | ||
| } | ||
| return value.html.length + (((_JSON_stringify = JSON.stringify(value.pageData)) == null ? void 0 : _JSON_stringify.length) || 0); | ||
| return cacheKey.length + valueSize; | ||
| }); | ||
@@ -55,0 +57,0 @@ } |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/incremental-cache/memory-cache.external.ts"],"sourcesContent":["import type { CacheHandlerValue } from '.'\nimport { CachedRouteKind } from '../../response-cache/types'\nimport { LRUCache } from '../lru-cache'\n\nlet memoryCache: LRUCache<CacheHandlerValue> | undefined\n\nfunction getBufferSize(buffer: Buffer | undefined) {\n return buffer?.length || 0\n}\n\nfunction getSegmentDataSize(segmentData: Map<string, Buffer> | undefined) {\n if (!segmentData) {\n return 0\n }\n\n let size = 0\n\n for (const [segmentPath, buffer] of segmentData) {\n size += segmentPath.length + getBufferSize(buffer)\n }\n\n return size\n}\n\nexport function getMemoryCache(maxMemoryCacheSize: number) {\n if (!memoryCache) {\n memoryCache = new LRUCache(maxMemoryCacheSize, function length({ value }) {\n if (!value) {\n return 25\n } else if (value.kind === CachedRouteKind.REDIRECT) {\n return JSON.stringify(value.props).length\n } else if (value.kind === CachedRouteKind.IMAGE) {\n throw new Error('invariant image should not be incremental-cache')\n } else if (value.kind === CachedRouteKind.FETCH) {\n return JSON.stringify(value.data || '').length\n } else if (value.kind === CachedRouteKind.APP_ROUTE) {\n return value.body.length\n }\n // rough estimate of size of cache value\n if (value.kind === CachedRouteKind.APP_PAGE) {\n return Math.max(\n 1,\n value.html.length +\n getBufferSize(value.rscData) +\n (value.postponed?.length || 0) +\n getSegmentDataSize(value.segmentData)\n )\n }\n\n return value.html.length + (JSON.stringify(value.pageData)?.length || 0)\n })\n }\n\n return memoryCache\n}\n"],"names":["getMemoryCache","memoryCache","getBufferSize","buffer","length","getSegmentDataSize","segmentData","size","segmentPath","maxMemoryCacheSize","LRUCache","value","JSON","kind","CachedRouteKind","REDIRECT","stringify","props","IMAGE","Error","FETCH","data","APP_ROUTE","body","APP_PAGE","Math","max","html","rscData","postponed","pageData"],"mappings":";;;;+BAwBgBA;;;eAAAA;;;uBAvBgB;0BACP;AAEzB,IAAIC;AAEJ,SAASC,cAAcC,MAA0B;IAC/C,OAAOA,CAAAA,0BAAAA,OAAQC,MAAM,KAAI;AAC3B;AAEA,SAASC,mBAAmBC,WAA4C;IACtE,IAAI,CAACA,aAAa;QAChB,OAAO;IACT;IAEA,IAAIC,OAAO;IAEX,KAAK,MAAM,CAACC,aAAaL,OAAO,IAAIG,YAAa;QAC/CC,QAAQC,YAAYJ,MAAM,GAAGF,cAAcC;IAC7C;IAEA,OAAOI;AACT;AAEO,SAASP,eAAeS,kBAA0B;IACvD,IAAI,CAACR,aAAa;QAChBA,cAAc,IAAIS,kBAAQ,CAACD,oBAAoB,SAASL,OAAO,EAAEO,KAAK,EAAE;gBAuB1CC;YAtB5B,IAAI,CAACD,OAAO;gBACV,OAAO;YACT,OAAO,IAAIA,MAAME,IAAI,KAAKC,sBAAe,CAACC,QAAQ,EAAE;gBAClD,OAAOH,KAAKI,SAAS,CAACL,MAAMM,KAAK,EAAEb,MAAM;YAC3C,OAAO,IAAIO,MAAME,IAAI,KAAKC,sBAAe,CAACI,KAAK,EAAE;gBAC/C,MAAM,qBAA4D,CAA5D,IAAIC,MAAM,oDAAV,qBAAA;2BAAA;gCAAA;kCAAA;gBAA2D;YACnE,OAAO,IAAIR,MAAME,IAAI,KAAKC,sBAAe,CAACM,KAAK,EAAE;gBAC/C,OAAOR,KAAKI,SAAS,CAACL,MAAMU,IAAI,IAAI,IAAIjB,MAAM;YAChD,OAAO,IAAIO,MAAME,IAAI,KAAKC,sBAAe,CAACQ,SAAS,EAAE;gBACnD,OAAOX,MAAMY,IAAI,CAACnB,MAAM;YAC1B;YACA,wCAAwC;YACxC,IAAIO,MAAME,IAAI,KAAKC,sBAAe,CAACU,QAAQ,EAAE;oBAKtCb;gBAJL,OAAOc,KAAKC,GAAG,CACb,GACAf,MAAMgB,IAAI,CAACvB,MAAM,GACfF,cAAcS,MAAMiB,OAAO,IAC1BjB,CAAAA,EAAAA,mBAAAA,MAAMkB,SAAS,qBAAflB,iBAAiBP,MAAM,KAAI,CAAA,IAC5BC,mBAAmBM,MAAML,WAAW;YAE1C;YAEA,OAAOK,MAAMgB,IAAI,CAACvB,MAAM,GAAIQ,CAAAA,EAAAA,kBAAAA,KAAKI,SAAS,CAACL,MAAMmB,QAAQ,sBAA7BlB,gBAAgCR,MAAM,KAAI,CAAA;QACxE;IACF;IAEA,OAAOH;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/incremental-cache/memory-cache.external.ts"],"sourcesContent":["import type { CacheHandlerValue } from '.'\nimport { CachedRouteKind } from '../../response-cache/types'\nimport { LRUCache } from '../lru-cache'\n\nlet memoryCache: LRUCache<CacheHandlerValue> | undefined\n\nfunction getBufferSize(buffer: Buffer | undefined) {\n return buffer?.length || 0\n}\n\nfunction getSegmentDataSize(segmentData: Map<string, Buffer> | undefined) {\n if (!segmentData) {\n return 0\n }\n\n let size = 0\n\n for (const [segmentPath, buffer] of segmentData) {\n size += segmentPath.length + getBufferSize(buffer)\n }\n\n return size\n}\n\nexport function getMemoryCache(maxMemoryCacheSize: number) {\n if (!memoryCache) {\n memoryCache = new LRUCache(maxMemoryCacheSize, function length(\n { value },\n cacheKey\n ) {\n let valueSize: number\n\n if (!value) {\n valueSize = 25\n } else if (value.kind === CachedRouteKind.REDIRECT) {\n valueSize = JSON.stringify(value.props).length\n } else if (value.kind === CachedRouteKind.IMAGE) {\n throw new Error('invariant image should not be incremental-cache')\n } else if (value.kind === CachedRouteKind.FETCH) {\n valueSize = JSON.stringify(value.data || '').length\n } else if (value.kind === CachedRouteKind.APP_ROUTE) {\n valueSize = value.body.length\n } else if (value.kind === CachedRouteKind.APP_PAGE) {\n // rough estimate of size of cache value\n valueSize = Math.max(\n 1,\n value.html.length +\n getBufferSize(value.rscData) +\n (value.postponed?.length || 0) +\n getSegmentDataSize(value.segmentData)\n )\n } else {\n valueSize =\n value.html.length + (JSON.stringify(value.pageData)?.length || 0)\n }\n\n return cacheKey.length + valueSize\n })\n }\n\n return memoryCache\n}\n"],"names":["getMemoryCache","memoryCache","getBufferSize","buffer","length","getSegmentDataSize","segmentData","size","segmentPath","maxMemoryCacheSize","LRUCache","value","cacheKey","valueSize","kind","CachedRouteKind","REDIRECT","JSON","stringify","props","IMAGE","Error","FETCH","data","APP_ROUTE","body","APP_PAGE","Math","max","html","rscData","postponed","pageData"],"mappings":";;;;+BAwBgBA;;;eAAAA;;;uBAvBgB;0BACP;AAEzB,IAAIC;AAEJ,SAASC,cAAcC,MAA0B;IAC/C,OAAOA,CAAAA,0BAAAA,OAAQC,MAAM,KAAI;AAC3B;AAEA,SAASC,mBAAmBC,WAA4C;IACtE,IAAI,CAACA,aAAa;QAChB,OAAO;IACT;IAEA,IAAIC,OAAO;IAEX,KAAK,MAAM,CAACC,aAAaL,OAAO,IAAIG,YAAa;QAC/CC,QAAQC,YAAYJ,MAAM,GAAGF,cAAcC;IAC7C;IAEA,OAAOI;AACT;AAEO,SAASP,eAAeS,kBAA0B;IACvD,IAAI,CAACR,aAAa;QAChBA,cAAc,IAAIS,kBAAQ,CAACD,oBAAoB,SAASL,OACtD,EAAEO,KAAK,EAAE,EACTC,QAAQ;YAER,IAAIC;YAEJ,IAAI,CAACF,OAAO;gBACVE,YAAY;YACd,OAAO,IAAIF,MAAMG,IAAI,KAAKC,sBAAe,CAACC,QAAQ,EAAE;gBAClDH,YAAYI,KAAKC,SAAS,CAACP,MAAMQ,KAAK,EAAEf,MAAM;YAChD,OAAO,IAAIO,MAAMG,IAAI,KAAKC,sBAAe,CAACK,KAAK,EAAE;gBAC/C,MAAM,qBAA4D,CAA5D,IAAIC,MAAM,oDAAV,qBAAA;2BAAA;gCAAA;kCAAA;gBAA2D;YACnE,OAAO,IAAIV,MAAMG,IAAI,KAAKC,sBAAe,CAACO,KAAK,EAAE;gBAC/CT,YAAYI,KAAKC,SAAS,CAACP,MAAMY,IAAI,IAAI,IAAInB,MAAM;YACrD,OAAO,IAAIO,MAAMG,IAAI,KAAKC,sBAAe,CAACS,SAAS,EAAE;gBACnDX,YAAYF,MAAMc,IAAI,CAACrB,MAAM;YAC/B,OAAO,IAAIO,MAAMG,IAAI,KAAKC,sBAAe,CAACW,QAAQ,EAAE;oBAM7Cf;gBALL,wCAAwC;gBACxCE,YAAYc,KAAKC,GAAG,CAClB,GACAjB,MAAMkB,IAAI,CAACzB,MAAM,GACfF,cAAcS,MAAMmB,OAAO,IAC1BnB,CAAAA,EAAAA,mBAAAA,MAAMoB,SAAS,qBAAfpB,iBAAiBP,MAAM,KAAI,CAAA,IAC5BC,mBAAmBM,MAAML,WAAW;YAE1C,OAAO;oBAEkBW;gBADvBJ,YACEF,MAAMkB,IAAI,CAACzB,MAAM,GAAIa,CAAAA,EAAAA,kBAAAA,KAAKC,SAAS,CAACP,MAAMqB,QAAQ,sBAA7Bf,gBAAgCb,MAAM,KAAI,CAAA;YACnE;YAEA,OAAOQ,SAASR,MAAM,GAAGS;QAC3B;IACF;IAEA,OAAOZ;AACT","ignoreList":[0]} |
@@ -27,3 +27,3 @@ /** | ||
| private readonly onEvict; | ||
| constructor(maxSize: number, calculateSize?: (value: T) => number, onEvict?: (key: string, value: T) => void); | ||
| constructor(maxSize: number, calculateSize?: (value: T, key: string) => number, onEvict?: (key: string, value: T) => void); | ||
| /** | ||
@@ -30,0 +30,0 @@ * Adds a node immediately after the head (marks as most recently used). |
@@ -92,3 +92,3 @@ /** | ||
| */ set(key, value) { | ||
| const size = (this.calculateSize == null ? void 0 : this.calculateSize.call(this, value)) ?? 1; | ||
| const size = (this.calculateSize == null ? void 0 : this.calculateSize.call(this, value, key)) ?? 1; | ||
| if (size <= 0) { | ||
@@ -95,0 +95,0 @@ throw Object.defineProperty(new Error(`LRUCache: calculateSize returned ${size}, but size must be > 0. ` + `Items with size 0 would never be evicted, causing unbounded cache growth.`), "__NEXT_ERROR_CODE", { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/lru-cache.ts"],"sourcesContent":["/**\n * Node in the doubly-linked list used for LRU tracking.\n * Each node represents a cache entry with bidirectional pointers.\n */\nclass LRUNode<T> {\n public readonly key: string\n public data: T\n public size: number\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n\n constructor(key: string, data: T, size: number) {\n this.key = key\n this.data = data\n this.size = size\n }\n}\n\n/**\n * Sentinel node used for head/tail boundaries.\n * These nodes don't contain actual cache data but simplify list operations.\n */\nclass SentinelNode<T> {\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n}\n\n/**\n * LRU (Least Recently Used) Cache implementation using a doubly-linked list\n * and hash map for O(1) operations.\n *\n * Algorithm:\n * - Uses a doubly-linked list to maintain access order (most recent at head)\n * - Hash map provides O(1) key-to-node lookup\n * - Sentinel head/tail nodes simplify edge case handling\n * - Size-based eviction supports custom size calculation functions\n *\n * Data Structure Layout:\n * HEAD <-> [most recent] <-> ... <-> [least recent] <-> TAIL\n *\n * Operations:\n * - get(): Move accessed node to head (mark as most recent)\n * - set(): Add new node at head, evict from tail if over capacity\n * - Eviction: Remove least recent node (tail.prev) when size exceeds limit\n */\nexport class LRUCache<T> {\n private readonly cache: Map<string, LRUNode<T>> = new Map()\n private readonly head: SentinelNode<T>\n private readonly tail: SentinelNode<T>\n private totalSize: number = 0\n private readonly maxSize: number\n private readonly calculateSize: ((value: T) => number) | undefined\n private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n constructor(\n maxSize: number,\n calculateSize?: (value: T) => number,\n onEvict?: (key: string, value: T) => void\n ) {\n this.maxSize = maxSize\n this.calculateSize = calculateSize\n this.onEvict = onEvict\n\n // Create sentinel nodes to simplify doubly-linked list operations\n // HEAD <-> TAIL (empty list)\n this.head = new SentinelNode<T>()\n this.tail = new SentinelNode<T>()\n this.head.next = this.tail\n this.tail.prev = this.head\n }\n\n /**\n * Adds a node immediately after the head (marks as most recently used).\n * Used when inserting new items or when an item is accessed.\n * PRECONDITION: node must be disconnected (prev/next should be null)\n */\n private addToHead(node: LRUNode<T>): void {\n node.prev = this.head\n node.next = this.head.next\n // head.next is always non-null (points to tail or another node)\n this.head.next!.prev = node\n this.head.next = node\n }\n\n /**\n * Removes a node from its current position in the doubly-linked list.\n * Updates the prev/next pointers of adjacent nodes to maintain list integrity.\n * PRECONDITION: node must be connected (prev/next are non-null)\n */\n private removeNode(node: LRUNode<T>): void {\n // Connected nodes always have non-null prev/next\n node.prev!.next = node.next\n node.next!.prev = node.prev\n }\n\n /**\n * Moves an existing node to the head position (marks as most recently used).\n * This is the core LRU operation - accessed items become most recent.\n */\n private moveToHead(node: LRUNode<T>): void {\n this.removeNode(node)\n this.addToHead(node)\n }\n\n /**\n * Removes and returns the least recently used node (the one before tail).\n * This is called during eviction when the cache exceeds capacity.\n * PRECONDITION: cache is not empty (ensured by caller)\n */\n private removeTail(): LRUNode<T> {\n const lastNode = this.tail.prev as LRUNode<T>\n // tail.prev is always non-null and always LRUNode when cache is not empty\n this.removeNode(lastNode)\n return lastNode\n }\n\n /**\n * Sets a key-value pair in the cache.\n * If the key exists, updates the value and moves to head.\n * If new, adds at head and evicts from tail if necessary.\n *\n * Time Complexity:\n * - O(1) for uniform item sizes\n * - O(k) where k is the number of items evicted (can be O(N) for variable sizes)\n */\n public set(key: string, value: T): boolean {\n const size = this.calculateSize?.(value) ?? 1\n if (size <= 0) {\n throw new Error(\n `LRUCache: calculateSize returned ${size}, but size must be > 0. ` +\n `Items with size 0 would never be evicted, causing unbounded cache growth.`\n )\n }\n if (size > this.maxSize) {\n console.warn('Single item size exceeds maxSize')\n return false\n }\n\n const existing = this.cache.get(key)\n if (existing) {\n // Update existing node: adjust size and move to head (most recent)\n existing.data = value\n this.totalSize = this.totalSize - existing.size + size\n existing.size = size\n this.moveToHead(existing)\n } else {\n // Add new node at head (most recent position)\n const newNode = new LRUNode(key, value, size)\n this.cache.set(key, newNode)\n this.addToHead(newNode)\n this.totalSize += size\n }\n\n // Evict least recently used items until under capacity\n while (this.totalSize > this.maxSize && this.cache.size > 0) {\n const tail = this.removeTail()\n this.cache.delete(tail.key)\n this.totalSize -= tail.size\n this.onEvict?.(tail.key, tail.data)\n }\n\n return true\n }\n\n /**\n * Checks if a key exists in the cache.\n * This is a pure query operation - does NOT update LRU order.\n *\n * Time Complexity: O(1)\n */\n public has(key: string): boolean {\n return this.cache.has(key)\n }\n\n /**\n * Retrieves a value by key and marks it as most recently used.\n * Moving to head maintains the LRU property for future evictions.\n *\n * Time Complexity: O(1)\n */\n public get(key: string): T | undefined {\n const node = this.cache.get(key)\n if (!node) return undefined\n\n // Mark as most recently used by moving to head\n this.moveToHead(node)\n\n return node.data\n }\n\n /**\n * Returns an iterator over the cache entries. The order is outputted in the\n * order of most recently used to least recently used.\n */\n public *[Symbol.iterator](): IterableIterator<[string, T]> {\n let current = this.head.next\n while (current && current !== this.tail) {\n // Between head and tail, current is always LRUNode\n const node = current as LRUNode<T>\n yield [node.key, node.data]\n current = current.next\n }\n }\n\n /**\n * Removes a specific key from the cache.\n * Updates both the hash map and doubly-linked list.\n *\n * Note: This is an explicit removal and does NOT trigger the `onEvict`\n * callback. Use this for intentional deletions where eviction tracking\n * is not needed.\n *\n * Time Complexity: O(1)\n */\n public remove(key: string): void {\n const node = this.cache.get(key)\n if (!node) return\n\n this.removeNode(node)\n this.cache.delete(key)\n this.totalSize -= node.size\n }\n\n /**\n * Returns the number of items in the cache.\n */\n public get size(): number {\n return this.cache.size\n }\n\n /**\n * Returns the current total size of all cached items.\n * This uses the custom size calculation if provided.\n */\n public get currentSize(): number {\n return this.totalSize\n }\n}\n"],"names":["LRUCache","LRUNode","constructor","key","data","size","prev","next","SentinelNode","maxSize","calculateSize","onEvict","cache","Map","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","set","value","Error","console","warn","existing","get","newNode","delete","has","undefined","Symbol","iterator","current","remove","currentSize"],"mappings":"AAAA;;;CAGC;;;;+BA0CYA;;;eAAAA;;;AAzCb,MAAMC;IAOJC,YAAYC,GAAW,EAAEC,IAAO,EAAEC,IAAY,CAAE;aAHzCC,OAA4C;aAC5CC,OAA4C;QAGjD,IAAI,CAACJ,GAAG,GAAGA;QACX,IAAI,CAACC,IAAI,GAAGA;QACZ,IAAI,CAACC,IAAI,GAAGA;IACd;AACF;AAEA;;;CAGC,GACD,MAAMG;;aACGF,OAA4C;aAC5CC,OAA4C;;AACrD;AAoBO,MAAMP;IASXE,YACEO,OAAe,EACfC,aAAoC,EACpCC,OAAyC,CACzC;aAZeC,QAAiC,IAAIC;aAG9CC,YAAoB;QAU1B,IAAI,CAACL,OAAO,GAAGA;QACf,IAAI,CAACC,aAAa,GAAGA;QACrB,IAAI,CAACC,OAAO,GAAGA;QAEf,kEAAkE;QAClE,6BAA6B;QAC7B,IAAI,CAACI,IAAI,GAAG,IAAIP;QAChB,IAAI,CAACQ,IAAI,GAAG,IAAIR;QAChB,IAAI,CAACO,IAAI,CAACR,IAAI,GAAG,IAAI,CAACS,IAAI;QAC1B,IAAI,CAACA,IAAI,CAACV,IAAI,GAAG,IAAI,CAACS,IAAI;IAC5B;IAEA;;;;GAIC,GACD,AAAQE,UAAUC,IAAgB,EAAQ;QACxCA,KAAKZ,IAAI,GAAG,IAAI,CAACS,IAAI;QACrBG,KAAKX,IAAI,GAAG,IAAI,CAACQ,IAAI,CAACR,IAAI;QAC1B,gEAAgE;QAChE,IAAI,CAACQ,IAAI,CAACR,IAAI,CAAED,IAAI,GAAGY;QACvB,IAAI,CAACH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,OAAO,IAAI,CAACN,KAAK,CAACiB,GAAG,CAAC1B;QAC5B,IAAI,CAACe,MAAM;QAEX,IAAI,CAACC,UAAU,CAACD;QAChB,IAAI,CAACN,KAAK,CAACmB,MAAM,CAAC5B;QAClB,IAAI,CAACW,SAAS,IAAII,KAAKb,IAAI;IAC7B;IAEA;;GAEC,GACD,IAAWA,OAAe;QACxB,OAAO,IAAI,CAACO,KAAK,CAACP,IAAI;IACxB;IAEA;;;GAGC,GACD,IAAWiC,cAAsB;QAC/B,OAAO,IAAI,CAACxB,SAAS;IACvB;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/lru-cache.ts"],"sourcesContent":["/**\n * Node in the doubly-linked list used for LRU tracking.\n * Each node represents a cache entry with bidirectional pointers.\n */\nclass LRUNode<T> {\n public readonly key: string\n public data: T\n public size: number\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n\n constructor(key: string, data: T, size: number) {\n this.key = key\n this.data = data\n this.size = size\n }\n}\n\n/**\n * Sentinel node used for head/tail boundaries.\n * These nodes don't contain actual cache data but simplify list operations.\n */\nclass SentinelNode<T> {\n public prev: LRUNode<T> | SentinelNode<T> | null = null\n public next: LRUNode<T> | SentinelNode<T> | null = null\n}\n\n/**\n * LRU (Least Recently Used) Cache implementation using a doubly-linked list\n * and hash map for O(1) operations.\n *\n * Algorithm:\n * - Uses a doubly-linked list to maintain access order (most recent at head)\n * - Hash map provides O(1) key-to-node lookup\n * - Sentinel head/tail nodes simplify edge case handling\n * - Size-based eviction supports custom size calculation functions\n *\n * Data Structure Layout:\n * HEAD <-> [most recent] <-> ... <-> [least recent] <-> TAIL\n *\n * Operations:\n * - get(): Move accessed node to head (mark as most recent)\n * - set(): Add new node at head, evict from tail if over capacity\n * - Eviction: Remove least recent node (tail.prev) when size exceeds limit\n */\nexport class LRUCache<T> {\n private readonly cache: Map<string, LRUNode<T>> = new Map()\n private readonly head: SentinelNode<T>\n private readonly tail: SentinelNode<T>\n private totalSize: number = 0\n private readonly maxSize: number\n private readonly calculateSize:\n | ((value: T, key: string) => number)\n | undefined\n private readonly onEvict: ((key: string, value: T) => void) | undefined\n\n constructor(\n maxSize: number,\n calculateSize?: (value: T, key: string) => number,\n onEvict?: (key: string, value: T) => void\n ) {\n this.maxSize = maxSize\n this.calculateSize = calculateSize\n this.onEvict = onEvict\n\n // Create sentinel nodes to simplify doubly-linked list operations\n // HEAD <-> TAIL (empty list)\n this.head = new SentinelNode<T>()\n this.tail = new SentinelNode<T>()\n this.head.next = this.tail\n this.tail.prev = this.head\n }\n\n /**\n * Adds a node immediately after the head (marks as most recently used).\n * Used when inserting new items or when an item is accessed.\n * PRECONDITION: node must be disconnected (prev/next should be null)\n */\n private addToHead(node: LRUNode<T>): void {\n node.prev = this.head\n node.next = this.head.next\n // head.next is always non-null (points to tail or another node)\n this.head.next!.prev = node\n this.head.next = node\n }\n\n /**\n * Removes a node from its current position in the doubly-linked list.\n * Updates the prev/next pointers of adjacent nodes to maintain list integrity.\n * PRECONDITION: node must be connected (prev/next are non-null)\n */\n private removeNode(node: LRUNode<T>): void {\n // Connected nodes always have non-null prev/next\n node.prev!.next = node.next\n node.next!.prev = node.prev\n }\n\n /**\n * Moves an existing node to the head position (marks as most recently used).\n * This is the core LRU operation - accessed items become most recent.\n */\n private moveToHead(node: LRUNode<T>): void {\n this.removeNode(node)\n this.addToHead(node)\n }\n\n /**\n * Removes and returns the least recently used node (the one before tail).\n * This is called during eviction when the cache exceeds capacity.\n * PRECONDITION: cache is not empty (ensured by caller)\n */\n private removeTail(): LRUNode<T> {\n const lastNode = this.tail.prev as LRUNode<T>\n // tail.prev is always non-null and always LRUNode when cache is not empty\n this.removeNode(lastNode)\n return lastNode\n }\n\n /**\n * Sets a key-value pair in the cache.\n * If the key exists, updates the value and moves to head.\n * If new, adds at head and evicts from tail if necessary.\n *\n * Time Complexity:\n * - O(1) for uniform item sizes\n * - O(k) where k is the number of items evicted (can be O(N) for variable sizes)\n */\n public set(key: string, value: T): boolean {\n const size = this.calculateSize?.(value, key) ?? 1\n if (size <= 0) {\n throw new Error(\n `LRUCache: calculateSize returned ${size}, but size must be > 0. ` +\n `Items with size 0 would never be evicted, causing unbounded cache growth.`\n )\n }\n if (size > this.maxSize) {\n console.warn('Single item size exceeds maxSize')\n return false\n }\n\n const existing = this.cache.get(key)\n if (existing) {\n // Update existing node: adjust size and move to head (most recent)\n existing.data = value\n this.totalSize = this.totalSize - existing.size + size\n existing.size = size\n this.moveToHead(existing)\n } else {\n // Add new node at head (most recent position)\n const newNode = new LRUNode(key, value, size)\n this.cache.set(key, newNode)\n this.addToHead(newNode)\n this.totalSize += size\n }\n\n // Evict least recently used items until under capacity\n while (this.totalSize > this.maxSize && this.cache.size > 0) {\n const tail = this.removeTail()\n this.cache.delete(tail.key)\n this.totalSize -= tail.size\n this.onEvict?.(tail.key, tail.data)\n }\n\n return true\n }\n\n /**\n * Checks if a key exists in the cache.\n * This is a pure query operation - does NOT update LRU order.\n *\n * Time Complexity: O(1)\n */\n public has(key: string): boolean {\n return this.cache.has(key)\n }\n\n /**\n * Retrieves a value by key and marks it as most recently used.\n * Moving to head maintains the LRU property for future evictions.\n *\n * Time Complexity: O(1)\n */\n public get(key: string): T | undefined {\n const node = this.cache.get(key)\n if (!node) return undefined\n\n // Mark as most recently used by moving to head\n this.moveToHead(node)\n\n return node.data\n }\n\n /**\n * Returns an iterator over the cache entries. The order is outputted in the\n * order of most recently used to least recently used.\n */\n public *[Symbol.iterator](): IterableIterator<[string, T]> {\n let current = this.head.next\n while (current && current !== this.tail) {\n // Between head and tail, current is always LRUNode\n const node = current as LRUNode<T>\n yield [node.key, node.data]\n current = current.next\n }\n }\n\n /**\n * Removes a specific key from the cache.\n * Updates both the hash map and doubly-linked list.\n *\n * Note: This is an explicit removal and does NOT trigger the `onEvict`\n * callback. Use this for intentional deletions where eviction tracking\n * is not needed.\n *\n * Time Complexity: O(1)\n */\n public remove(key: string): void {\n const node = this.cache.get(key)\n if (!node) return\n\n this.removeNode(node)\n this.cache.delete(key)\n this.totalSize -= node.size\n }\n\n /**\n * Returns the number of items in the cache.\n */\n public get size(): number {\n return this.cache.size\n }\n\n /**\n * Returns the current total size of all cached items.\n * This uses the custom size calculation if provided.\n */\n public get currentSize(): number {\n return this.totalSize\n }\n}\n"],"names":["LRUCache","LRUNode","constructor","key","data","size","prev","next","SentinelNode","maxSize","calculateSize","onEvict","cache","Map","totalSize","head","tail","addToHead","node","removeNode","moveToHead","removeTail","lastNode","set","value","Error","console","warn","existing","get","newNode","delete","has","undefined","Symbol","iterator","current","remove","currentSize"],"mappings":"AAAA;;;CAGC;;;;+BA0CYA;;;eAAAA;;;AAzCb,MAAMC;IAOJC,YAAYC,GAAW,EAAEC,IAAO,EAAEC,IAAY,CAAE;aAHzCC,OAA4C;aAC5CC,OAA4C;QAGjD,IAAI,CAACJ,GAAG,GAAGA;QACX,IAAI,CAACC,IAAI,GAAGA;QACZ,IAAI,CAACC,IAAI,GAAGA;IACd;AACF;AAEA;;;CAGC,GACD,MAAMG;;aACGF,OAA4C;aAC5CC,OAA4C;;AACrD;AAoBO,MAAMP;IAWXE,YACEO,OAAe,EACfC,aAAiD,EACjDC,OAAyC,CACzC;aAdeC,QAAiC,IAAIC;aAG9CC,YAAoB;QAY1B,IAAI,CAACL,OAAO,GAAGA;QACf,IAAI,CAACC,aAAa,GAAGA;QACrB,IAAI,CAACC,OAAO,GAAGA;QAEf,kEAAkE;QAClE,6BAA6B;QAC7B,IAAI,CAACI,IAAI,GAAG,IAAIP;QAChB,IAAI,CAACQ,IAAI,GAAG,IAAIR;QAChB,IAAI,CAACO,IAAI,CAACR,IAAI,GAAG,IAAI,CAACS,IAAI;QAC1B,IAAI,CAACA,IAAI,CAACV,IAAI,GAAG,IAAI,CAACS,IAAI;IAC5B;IAEA;;;;GAIC,GACD,AAAQE,UAAUC,IAAgB,EAAQ;QACxCA,KAAKZ,IAAI,GAAG,IAAI,CAACS,I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BAAClB,KAAKf,GAAG;gBAAEe,KAAKd,IAAI;aAAC;YAC3BgC,UAAUA,QAAQ7B,IAAI;QACxB;IACF;IAEA;;;;;;;;;GASC,GACD,AAAO8B,OAAOlC,GAAW,EAAQ;QAC/B,MAAMe,OAAO,IAAI,CAACN,KAAK,CAACiB,GAAG,CAAC1B;QAC5B,IAAI,CAACe,MAAM;QAEX,IAAI,CAACC,UAAU,CAACD;QAChB,IAAI,CAACN,KAAK,CAACmB,MAAM,CAAC5B;QAClB,IAAI,CAACW,SAAS,IAAII,KAAKb,IAAI;IAC7B;IAEA;;GAEC,GACD,IAAWA,OAAe;QACxB,OAAO,IAAI,CAACO,KAAK,CAACP,IAAI;IACxB;IAEA;;;GAGC,GACD,IAAWiC,cAAsB;QAC/B,OAAO,IAAI,CAACxB,SAAS;IACvB;AACF","ignoreList":[0]} |
@@ -37,2 +37,3 @@ "use strict"; | ||
| const _requestinsights = require("./trace/request-insights"); | ||
| const _requestinsightsidentity = require("./trace/request-insights-identity"); | ||
| const _tracer = require("./trace/tracer"); | ||
@@ -124,17 +125,22 @@ const _constants1 = require("../../lib/constants"); | ||
| }); | ||
| if ((0, _requestinsights.isRequestInsightsEnabled)() && workStore.requestId) { | ||
| (0, _requestinsights.recordRequestInsightFetch)({ | ||
| requestId: workStore.requestId, | ||
| htmlRequestId: workStore.htmlRequestId, | ||
| route: workStore.route | ||
| }, { | ||
| url: metric.url, | ||
| method: metric.method, | ||
| statusCode: metric.status, | ||
| startTime: metric.start, | ||
| durationMs: metric.end - metric.start, | ||
| cacheStatus: metric.cacheStatus, | ||
| cacheReason: metric.cacheReason, | ||
| index: metric.idx | ||
| }); | ||
| if ((0, _requestinsights.isRequestInsightsEnabled)()) { | ||
| const requestInsightsIdentity = (0, _requestinsightsidentity.getRequestInsightsIdentity)(); | ||
| const requestInsightsRequestId = (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId) ?? workStore.requestId; | ||
| if (requestInsightsRequestId) { | ||
| (0, _requestinsights.recordRequestInsightFetch)({ | ||
| requestId: requestInsightsRequestId, | ||
| kind: requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.kind, | ||
| htmlRequestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId) ?? workStore.htmlRequestId, | ||
| route: workStore.route | ||
| }, { | ||
| url: metric.url, | ||
| method: metric.method, | ||
| statusCode: metric.status, | ||
| startTime: metric.start, | ||
| durationMs: metric.end - metric.start, | ||
| cacheStatus: metric.cacheStatus, | ||
| cacheReason: metric.cacheReason, | ||
| index: metric.idx | ||
| }); | ||
| } | ||
| } | ||
@@ -454,3 +460,3 @@ if (!workStore.shouldTrackFetchMetrics) { | ||
| } | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'validation-client': | ||
@@ -569,3 +575,3 @@ break; | ||
| } | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'request': | ||
@@ -863,3 +869,3 @@ if (process.env.NODE_ENV === 'development' && workUnitStore.stagedRendering) { | ||
| } | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'request': | ||
@@ -898,3 +904,3 @@ if (process.env.NODE_ENV === 'development' && workUnitStore.stagedRendering) { | ||
| case 'validation-client': | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, 'fetch()'); | ||
| case 'request': | ||
@@ -901,0 +907,0 @@ if (process.env.NODE_ENV === 'development' && workUnitStore.stagedRendering) { |
@@ -120,9 +120,28 @@ "use strict"; | ||
| }; | ||
| // Measured retained cost of a cache entry beyond its strings (LRUNode, | ||
| // Map slot, string header): ~120 bytes. Counting it keeps the entry count | ||
| // bounded even when keys are short, so the budget approximates retained | ||
| // bytes. | ||
| const FS_LRU_ENTRY_OVERHEAD = 128; | ||
| const FS_LRU_MAX_SIZE = 8 * 1024 * 1024; | ||
| // The pathname passed to getItem is usually a V8 slice of the full request | ||
| // URL, and a sliced string retains its parent — including the query string — | ||
| // for as long as the cache holds the key. Store a flat copy instead. | ||
| // The JSON round-trip returns an equal string for every input (unlike a | ||
| // Buffer round-trip, which replaces lone surrogates), so distinct keys can | ||
| // never collide on the stored copy. | ||
| function flatKeyCopy(key) { | ||
| return JSON.parse(JSON.stringify(key)); | ||
| } | ||
| // Cached result for paths that resolve to nothing. Not null, so that a | ||
| // cached miss can't be conflated with an uncached key (undefined). | ||
| const notFound = Symbol('not-found'); | ||
| async function setupFsCheck(opts) { | ||
| const getItemsLru = !opts.dev ? new _lrucache.LRUCache(1024 * 1024, function length(value) { | ||
| if (!value) { | ||
| // Null entries (negative cache) still need a non-zero size for LRU eviction | ||
| return 1; | ||
| const getItemsLru = !opts.dev ? new _lrucache.LRUCache(FS_LRU_MAX_SIZE, function length(value, key) { | ||
| const size = FS_LRU_ENTRY_OVERHEAD + key.length; | ||
| if (value === notFound) { | ||
| // Negative cache entries only retain their key. | ||
| return size; | ||
| } | ||
| return (value.fsPath || '').length + value.itemPath.length + value.type.length; | ||
| return size + (value.fsPath || '').length + value.itemPath.length + value.type.length; | ||
| }) : undefined; | ||
@@ -351,4 +370,4 @@ // routes that have _next/data endpoints (SSG/SSP) | ||
| const lruResult = getItemsLru == null ? void 0 : getItemsLru.get(itemKey); | ||
| if (lruResult) { | ||
| return lruResult; | ||
| if (lruResult !== undefined) { | ||
| return lruResult === notFound ? null : lruResult; | ||
| } | ||
@@ -574,9 +593,11 @@ const { basePath } = opts.config; | ||
| itemsRoot, | ||
| itemPath: curItemPath | ||
| // itemPath is usually a slice of the request URL too; keep a | ||
| // flat copy so the cached value doesn't retain the full URL. | ||
| itemPath: flatKeyCopy(curItemPath) | ||
| }; | ||
| getItemsLru == null ? void 0 : getItemsLru.set(itemKey, itemResult); | ||
| getItemsLru == null ? void 0 : getItemsLru.set(flatKeyCopy(itemKey), itemResult); | ||
| return itemResult; | ||
| } | ||
| } | ||
| getItemsLru == null ? void 0 : getItemsLru.set(itemKey, null); | ||
| getItemsLru == null ? void 0 : getItemsLru.set(flatKeyCopy(itemKey), notFound); | ||
| return null; | ||
@@ -583,0 +604,0 @@ }, |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/router-utils/filesystem.ts"],"sourcesContent":["import type {\n FunctionsConfigManifest,\n ManifestRoute,\n PrerenderManifest,\n RoutesManifest,\n} from '../../../build'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'\nimport type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport type { __ApiPreviewProps } from '../../api-utils'\n\nimport path from 'path'\nimport fs from 'fs/promises'\nimport * as Log from '../../../build/output/log'\nimport setupDebug from 'next/dist/compiled/debug'\nimport { LRUCache } from '../lru-cache'\nimport loadCustomRoutes, { type Rewrite } from '../../../lib/load-custom-routes'\nimport { modifyRouteRegex } from '../../../lib/redirect-status'\nimport { FileType, fileExists } from '../../../lib/file-exists'\nimport { recursiveReadDir } from '../../../lib/recursive-readdir'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\nimport { getPathMatch } from '../../../shared/lib/router/utils/path-match'\nimport {\n getNamedRouteRegex,\n getRouteRegex,\n} from '../../../shared/lib/router/utils/route-regex'\nimport { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'\nimport { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'\nimport { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'\nimport { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'\nimport { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport {\n APP_PATH_ROUTES_MANIFEST,\n BUILD_ID_FILE,\n FUNCTIONS_CONFIG_MANIFEST,\n MIDDLEWARE_MANIFEST,\n PAGES_MANIFEST,\n PRERENDER_MANIFEST,\n ROUTES_MANIFEST,\n} from '../../../shared/lib/constants'\nimport { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'\nimport { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { encodeURIPath } from '../../../shared/lib/encode-uri-path'\nimport { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'\n\nexport type FsOutput = {\n type:\n | 'appFile'\n | 'pageFile'\n | 'nextImage'\n | 'publicFolder'\n | 'nextStaticFolder'\n | 'legacyStaticFolder'\n | 'devVirtualFsItem'\n\n itemPath: string\n fsPath?: string\n itemsRoot?: string\n locale?: string\n}\n\nconst debug = setupDebug('next:router-server:filesystem')\n\nexport type FilesystemDynamicRoute = ManifestRoute & {\n /**\n * The path matcher that can be used to match paths against this route.\n */\n match: PatchMatcher\n}\n\nexport const buildCustomRoute = <T>(\n type: 'redirect' | 'header' | 'rewrite' | 'before_files_rewrite',\n item: T & { source: string },\n basePath?: string,\n caseSensitive?: boolean\n): T & { match: PatchMatcher; check?: boolean; regex: string } => {\n const restrictedRedirectPaths = ['/_next'].map((p) =>\n basePath ? `${basePath}${p}` : p\n )\n let builtRegex = ''\n const match = getPathMatch(item.source, {\n strict: true,\n removeUnnamedParams: true,\n regexModifier: (regex: string) => {\n if (!(item as any).internal) {\n regex = modifyRouteRegex(\n regex,\n type === 'redirect' ? restrictedRedirectPaths : undefined\n )\n }\n builtRegex = regex\n return builtRegex\n },\n sensitive: caseSensitive,\n })\n\n return {\n ...item,\n regex: builtRegex,\n ...(type === 'rewrite' ? { check: true } : {}),\n match,\n }\n}\n\nexport async function setupFsCheck(opts: {\n dir: string\n dev: boolean\n minimalMode?: boolean\n config: NextConfigRuntime\n}) {\n const getItemsLru = !opts.dev\n ? new LRUCache<FsOutput | null>(1024 * 1024, function length(value) {\n if (!value) {\n // Null entries (negative cache) still need a non-zero size for LRU eviction\n return 1\n }\n return (\n (value.fsPath || '').length +\n value.itemPath.length +\n value.type.length\n )\n })\n : undefined\n\n // routes that have _next/data endpoints (SSG/SSP)\n const nextDataRoutes = new Set<string>()\n const publicFolderItems = new Set<string>()\n const nextStaticFolderItems = new Set<string>()\n const legacyStaticFolderItems = new Set<string>()\n\n const appFiles = new Set<string>()\n const pageFiles = new Set<string>()\n // Map normalized path to the file path. This is essential\n // for parallel and group routes as their original path\n // cannot be restored from the request path.\n // Example:\n // [normalized-path] -> [file-path]\n // /icon-<hash>.png -> .../app/@parallel/icon.png\n // /icon-<hash>.png -> .../app/(group)/icon.png\n // /icon.png -> .../app/icon.png\n const staticMetadataFiles = new Map<string, string>()\n let dynamicRoutes: FilesystemDynamicRoute[] = []\n\n let middlewareMatcher:\n | ReturnType<typeof getMiddlewareRouteMatcher>\n | undefined = () => false\n\n const distDir = path.join(opts.dir, opts.config.distDir)\n const publicFolderPath = path.join(opts.dir, 'public')\n const nextStaticFolderPath = path.join(distDir, 'static')\n const legacyStaticFolderPath = path.join(opts.dir, 'static')\n let customRoutes: UnwrapPromise<ReturnType<typeof loadCustomRoutes>> = {\n redirects: [],\n rewrites: {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n onMatchHeaders: [],\n headers: [],\n }\n let buildId = 'development'\n let previewProps: __ApiPreviewProps\n\n if (!opts.dev) {\n const buildIdPath = path.join(opts.dir, opts.config.distDir, BUILD_ID_FILE)\n try {\n buildId = await fs.readFile(buildIdPath, 'utf8')\n } catch (err: any) {\n if (err.code !== 'ENOENT') throw err\n throw new Error(\n `Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n )\n }\n\n try {\n for (const file of await recursiveReadDir(publicFolderPath)) {\n // Ensure filename is encoded and normalized.\n publicFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(legacyStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n legacyStaticFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n Log.warn(\n `The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`\n )\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(nextStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n nextStaticFolderItems.add(\n path.posix.join(\n '/_next/static',\n encodeURIPath(normalizePathSep(file))\n )\n )\n }\n } catch (err) {\n if (opts.config.output !== 'standalone') throw err\n }\n\n const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)\n const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST)\n const middlewareManifestPath = path.join(\n distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n const functionsConfigManifestPath = path.join(\n distDir,\n 'server',\n FUNCTIONS_CONFIG_MANIFEST\n )\n const pagesManifestPath = path.join(distDir, 'server', PAGES_MANIFEST)\n const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)\n\n const routesManifest = JSON.parse(\n await fs.readFile(routesManifestPath, 'utf8')\n ) as RoutesManifest\n\n previewProps = (\n JSON.parse(\n await fs.readFile(prerenderManifestPath, 'utf8')\n ) as PrerenderManifest\n ).preview\n\n const middlewareManifest = JSON.parse(\n await fs.readFile(middlewareManifestPath, 'utf8').catch(() => '{}')\n ) as MiddlewareManifest\n\n const functionsConfigManifest = JSON.parse(\n await fs.readFile(functionsConfigManifestPath, 'utf8').catch(() => '{}')\n ) as FunctionsConfigManifest\n\n const pagesManifest = JSON.parse(\n await fs.readFile(pagesManifestPath, 'utf8')\n )\n const appRoutesManifest = JSON.parse(\n await fs.readFile(appRoutesManifestPath, 'utf8').catch(() => '{}')\n )\n\n for (const key of Object.keys(pagesManifest)) {\n // ensure the non-locale version is in the set\n if (opts.config.i18n) {\n pageFiles.add(\n normalizeLocalePath(key, opts.config.i18n.locales).pathname\n )\n } else {\n pageFiles.add(key)\n }\n }\n for (const key of Object.keys(appRoutesManifest)) {\n appFiles.add(appRoutesManifest[key])\n }\n\n const escapedBuildId = escapeStringRegexp(buildId)\n\n for (const route of routesManifest.dataRoutes) {\n if (isDynamicRoute(route.page)) {\n const routeRegex = getNamedRouteRegex(route.page, {\n prefixRouteKeys: true,\n })\n dynamicRoutes.push({\n ...route,\n regex: routeRegex.re.toString(),\n namedRegex: routeRegex.namedRegex,\n routeKeys: routeRegex.routeKeys,\n match: getRouteMatcher({\n // TODO: fix this in the manifest itself, must also be fixed in\n // upstream builder that relies on this\n re: opts.config.i18n\n ? new RegExp(\n route.dataRouteRegex.replace(\n `/${escapedBuildId}/`,\n `/${escapedBuildId}/(?<nextLocale>[^/]+?)/`\n )\n )\n : new RegExp(route.dataRouteRegex),\n groups: routeRegex.groups,\n }),\n })\n }\n nextDataRoutes.add(route.page)\n }\n\n for (const route of routesManifest.dynamicRoutes) {\n // If a route is marked as skipInternalRouting, it's not for the internal\n // router, and instead has been added to support external routers.\n if (route.skipInternalRouting) {\n continue\n }\n\n dynamicRoutes.push({\n ...route,\n match: getRouteMatcher(getRouteRegex(route.page)),\n })\n }\n\n if (middlewareManifest.middleware?.['/']?.matchers) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n middlewareManifest.middleware?.['/']?.matchers\n )\n } else if (functionsConfigManifest?.functions['/_middleware']) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n functionsConfigManifest.functions['/_middleware'].matchers ?? [\n { regexp: '.*', originalSource: '/:path*' },\n ]\n )\n }\n\n customRoutes = {\n redirects: routesManifest.redirects,\n rewrites: routesManifest.rewrites\n ? Array.isArray(routesManifest.rewrites)\n ? {\n beforeFiles: [],\n afterFiles: routesManifest.rewrites,\n fallback: [],\n }\n : routesManifest.rewrites\n : {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n headers: routesManifest.headers,\n onMatchHeaders: routesManifest.onMatchHeaders,\n }\n } else {\n // dev handling\n customRoutes = await loadCustomRoutes(opts.config)\n\n previewProps = {\n previewModeId: (require('crypto') as typeof import('crypto'))\n .randomBytes(16)\n .toString('hex'),\n previewModeSigningKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n previewModeEncryptionKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n }\n }\n\n const headers = customRoutes.headers.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const onMatchHeaders = customRoutes.onMatchHeaders.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const redirects = customRoutes.redirects.map((item) =>\n buildCustomRoute(\n 'redirect',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const rewrites = {\n beforeFiles: customRoutes.rewrites.beforeFiles.map((item) =>\n buildCustomRoute('before_files_rewrite', item)\n ),\n afterFiles: customRoutes.rewrites.afterFiles.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n fallback: customRoutes.rewrites.fallback.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n }\n\n const { i18n } = opts.config\n\n const handleLocale = (pathname: string, locales?: string[]) => {\n let locale: string | undefined\n\n if (i18n) {\n const i18nResult = normalizeLocalePath(pathname, locales || i18n.locales)\n\n pathname = i18nResult.pathname\n locale = i18nResult.detectedLocale\n }\n return { locale, pathname }\n }\n\n debug('nextDataRoutes', nextDataRoutes)\n debug('dynamicRoutes', dynamicRoutes)\n debug('customRoutes', customRoutes)\n debug('publicFolderItems', publicFolderItems)\n debug('nextStaticFolderItems', nextStaticFolderItems)\n debug('pageFiles', pageFiles)\n debug('appFiles', appFiles)\n\n let ensureFn: (item: FsOutput) => Promise<void> | undefined\n\n const normalizers = {\n // Because we can't know if the app directory is enabled or not at this\n // stage, we assume that it is.\n rsc: new RSCPathnameNormalizer(),\n }\n\n return {\n headers,\n onMatchHeaders,\n rewrites,\n redirects,\n\n buildId,\n handleLocale,\n\n appFiles,\n pageFiles,\n staticMetadataFiles,\n dynamicRoutes,\n nextDataRoutes,\n\n exportPathMapRoutes: undefined as\n | undefined\n | ReturnType<typeof buildCustomRoute<Rewrite>>[],\n\n devVirtualFsItems: new Set<string>(),\n\n previewProps,\n middlewareMatcher: middlewareMatcher as MiddlewareRouteMatch | undefined,\n\n ensureCallback(fn: typeof ensureFn) {\n ensureFn = fn\n },\n\n async getItem(itemPath: string): Promise<FsOutput | null> {\n const originalItemPath = itemPath\n const itemKey = originalItemPath\n const lruResult = getItemsLru?.get(itemKey)\n\n if (lruResult) {\n return lruResult\n }\n\n const { basePath } = opts.config\n\n const hasBasePath = pathHasPrefix(itemPath, basePath)\n\n // Return null if path doesn't start with basePath\n if (basePath && !hasBasePath) {\n return null\n }\n\n // Remove basePath if it exists.\n if (basePath && hasBasePath) {\n itemPath = removePathPrefix(itemPath, basePath) || '/'\n }\n\n // Simulate minimal mode requests by normalizing RSC and postponed\n // requests.\n if (opts.minimalMode) {\n if (normalizers.rsc.match(itemPath)) {\n itemPath = normalizers.rsc.normalize(itemPath, true)\n }\n }\n\n if (itemPath !== '/' && itemPath.endsWith('/')) {\n itemPath = itemPath.substring(0, itemPath.length - 1)\n }\n\n let decodedItemPath = itemPath\n\n try {\n decodedItemPath = decodeURIComponent(itemPath)\n } catch {}\n\n if (itemPath === '/_next/image') {\n return {\n itemPath,\n type: 'nextImage',\n }\n }\n\n if (opts.dev && isMetadataRouteFile(itemPath, [], false)) {\n const fsPath = staticMetadataFiles.get(itemPath)\n if (fsPath) {\n return {\n // \"nextStaticFolder\" sets Cache-Control \"no-store\" on dev.\n type: 'nextStaticFolder',\n fsPath,\n itemPath: fsPath,\n }\n }\n }\n\n const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [\n [this.devVirtualFsItems, 'devVirtualFsItem'],\n [nextStaticFolderItems, 'nextStaticFolder'],\n [legacyStaticFolderItems, 'legacyStaticFolder'],\n [publicFolderItems, 'publicFolder'],\n [appFiles, 'appFile'],\n [pageFiles, 'pageFile'],\n ]\n\n for (let [items, type] of itemsToCheck) {\n let locale: string | undefined\n let curItemPath = itemPath\n let curDecodedItemPath = decodedItemPath\n\n const isDynamicOutput = type === 'pageFile' || type === 'appFile'\n\n if (i18n) {\n const localeResult = handleLocale(\n itemPath,\n // legacy behavior allows visiting static assets under\n // default locale but no other locale\n isDynamicOutput\n ? undefined\n : [\n i18n?.defaultLocale,\n // default locales from domains need to be matched too\n ...(i18n.domains?.map((item) => item.defaultLocale) || []),\n ]\n )\n\n if (localeResult.pathname !== curItemPath) {\n curItemPath = localeResult.pathname\n locale = localeResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n }\n\n if (type === 'legacyStaticFolder') {\n if (!pathHasPrefix(curItemPath, '/static')) {\n continue\n }\n curItemPath = curItemPath.substring('/static'.length)\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n if (\n type === 'nextStaticFolder' &&\n !pathHasPrefix(curItemPath, '/_next/static')\n ) {\n continue\n }\n\n const nextDataPrefix = `/_next/data/${buildId}/`\n\n if (\n type === 'pageFile' &&\n curItemPath.startsWith(nextDataPrefix) &&\n curItemPath.endsWith('.json')\n ) {\n items = nextDataRoutes\n // remove _next/data/<build-id> prefix\n curItemPath = curItemPath.substring(nextDataPrefix.length - 1)\n\n // remove .json postfix\n curItemPath = curItemPath.substring(\n 0,\n curItemPath.length - '.json'.length\n )\n const curLocaleResult = handleLocale(curItemPath)\n curItemPath =\n curLocaleResult.pathname === '/index'\n ? '/'\n : curLocaleResult.pathname\n\n locale = curLocaleResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n let matchedItem = items.has(curItemPath)\n\n // check decoded variant as well\n if (!matchedItem && !opts.dev) {\n matchedItem = items.has(curDecodedItemPath)\n if (matchedItem) curItemPath = curDecodedItemPath\n else {\n // x-ref: https://github.com/vercel/next.js/issues/54008\n // There're cases that urls get decoded before requests, we should support both encoded and decoded ones.\n // e.g. nginx could decode the proxy urls, the below ones should be treated as the same:\n // decoded version: `/_next/static/chunks/pages/blog/[slug]-d4858831b91b69f6.js`\n // encoded version: `/_next/static/chunks/pages/blog/%5Bslug%5D-d4858831b91b69f6.js`\n try {\n // encode the special characters in the path and retrieve again to determine if path exists.\n const encodedCurItemPath = encodeURIPath(curItemPath)\n matchedItem = items.has(encodedCurItemPath)\n } catch {}\n }\n }\n\n if (matchedItem || opts.dev) {\n let fsPath: string | undefined\n let itemsRoot: string | undefined\n\n switch (type) {\n case 'nextStaticFolder': {\n itemsRoot = nextStaticFolderPath\n curItemPath = curItemPath.substring('/_next/static'.length)\n break\n }\n case 'legacyStaticFolder': {\n itemsRoot = legacyStaticFolderPath\n break\n }\n case 'publicFolder': {\n itemsRoot = publicFolderPath\n break\n }\n case 'appFile':\n case 'pageFile':\n case 'nextImage':\n case 'devVirtualFsItem': {\n break\n }\n default: {\n ;(type) satisfies never\n }\n }\n\n if (itemsRoot && curItemPath) {\n fsPath = path.posix.join(itemsRoot, curItemPath)\n }\n\n // dynamically check fs in development so we don't\n // have to wait on the watcher\n if (!matchedItem && opts.dev) {\n const isStaticAsset = (\n [\n 'nextStaticFolder',\n 'publicFolder',\n 'legacyStaticFolder',\n ] as (typeof type)[]\n ).includes(type)\n\n if (isStaticAsset && itemsRoot) {\n let found = fsPath && (await fileExists(fsPath, FileType.File))\n\n if (!found) {\n try {\n // In dev, we ensure encoded paths match\n // decoded paths on the filesystem so check\n // that variation as well\n const tempItemPath = decodeURIComponent(curItemPath)\n fsPath = path.posix.join(itemsRoot, tempItemPath)\n found = await fileExists(fsPath, FileType.File)\n } catch {}\n\n if (!found) {\n continue\n }\n }\n } else if (type === 'pageFile' || type === 'appFile') {\n const isAppFile = type === 'appFile'\n\n // Attempt to ensure the page/app file is compiled and ready\n if (ensureFn) {\n const ensureItemPath = isAppFile\n ? normalizeMetadataRoute(curItemPath)\n : curItemPath\n\n try {\n await ensureFn({ type, itemPath: ensureItemPath })\n } catch (error) {\n // If ensure failed, skip this item and continue to the next one\n continue\n }\n }\n } else {\n continue\n }\n }\n\n // i18n locales aren't matched for app dir\n if (type === 'appFile' && locale && locale !== i18n?.defaultLocale) {\n continue\n }\n\n const itemResult = {\n type,\n fsPath,\n locale,\n itemsRoot,\n itemPath: curItemPath,\n }\n\n getItemsLru?.set(itemKey, itemResult)\n return itemResult\n }\n }\n\n getItemsLru?.set(itemKey, null)\n return null\n },\n getDynamicRoutes() {\n // this should include data routes\n return this.dynamicRoutes\n },\n getMiddlewareMatchers() {\n return this.middlewareMatcher\n },\n }\n}\n"],"names":["buildCustomRoute","setupFsCheck","debug","setupDebug","type","item","basePath","caseSensitive","restrictedRedirectPaths","map","p","builtRegex","match","getPathMatch","source","strict","removeUnnamedParams","regexModifier","regex","internal","modifyRouteRegex","undefined","sensitive","check","opts","getItemsLru","dev","LRUCache","length","value","fsPath","itemPath","nextDataRoutes","Set","publicFolderItems","nextStaticFolderItems","legacyStaticFolderItems","appFiles","pageFiles","staticMetadataFiles","Map","dynamicRoutes","middlewareMatcher","distDir","path","join","dir","config","publicFolderPath","nextStaticFolderPath","legacyStaticFolderPath","customRoutes","redirects","rewrites","beforeFiles","afterFiles","fallback","onMatchHeaders","headers","buildId","previewProps","middlewareManifest","buildIdPath","BUILD_ID_FILE","fs","readFile","err","code","Error","file","recursiveReadDir","add","encodeURIPath","normalizePathSep","Log","warn","posix","output","routesManifestPath","ROUTES_MANIFEST","prerenderManifestPath","PRERENDER_MANIFEST","middlewareManifestPath","MIDDLEWARE_MANIFEST","functionsConfigManifestPath","FUNCTIONS_CONFIG_MANIFEST","pagesManifestPath","PAGES_MANIFEST","appRoutesManifestPath","APP_PATH_ROUTES_MANIFEST","routesManifest","JSON","parse","preview","catch","functionsConfigManifest","pagesManifest","appRoutesManifest","key","Object","keys","i18n","normalizeLocalePath","locales","pathname","escapedBuildId","escapeStringRegexp","route","dataRoutes","isDynamicRoute","page","routeRegex","getNamedRouteRegex","prefixRouteKeys","push","re","toString","namedRegex","routeKeys","getRouteMatcher","RegExp","dataRouteRegex","replace","groups","skipInternalRouting","getRouteRegex","middleware","matchers","getMiddlewareRouteMatcher","functions","regexp","originalSource","Array","isArray","loadCustomRoutes","previewModeId","require","randomBytes","previewModeSigningKey","previewModeEncryptionKey","experimental","caseSensitiveRoutes","handleLocale","locale","i18nResult","detectedLocale","ensureFn","normalizers","rsc","RSCPathnameNormalizer","exportPathMapRoutes","devVirtualFsItems","ensureCallback","fn","getItem","originalItemPath","itemKey","lruResult","get","hasBasePath","pathHasPrefix","removePathPrefix","minimalMode","normalize","endsWith","substring","decodedItemPath","decodeURIComponent","isMetadataRouteFile","itemsToCheck","items","curItemPath","curDecodedItemPath","isDynamicOutput","localeResult","defaultLocale","domains","nextDataPrefix","startsWith","curLocaleResult","matchedItem","has","encodedCurItemPath","itemsRoot","isStaticAsset","includes","found","fileExists","FileType","File","tempItemPath","isAppFile","ensureItemPath","normalizeMetadataRoute","error","itemResult","set","getDynamicRoutes","getMiddlewareMatchers"],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;4BACL;wBACF;oBACF;oBAEA,0CAA0C;oBAC1C,IAAI9L,SAAS,aAAa2I,UAAUA,YAAW1C,wBAAAA,KAAM0E,aAAa,GAAE;wBAClE;oBACF;oBAEA,MAAMoB,aAAa;wBACjB/L;wBACA0B;wBACAiH;wBACAwC;wBACAxJ,UAAU4I;oBACZ;oBAEAlJ,+BAAAA,YAAa2K,GAAG,CAACxC,SAASuC;oBAC1B,OAAOA;gBACT;YACF;YAEA1K,+BAAAA,YAAa2K,GAAG,CAACxC,SAAS;YAC1B,OAAO;QACT;QACAyC;YACE,kCAAkC;YAClC,OAAO,IAAI,CAAC5J,aAAa;QAC3B;QACA6J;YACE,OAAO,IAAI,CAAC5J,iBAAiB;QAC/B;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/router-utils/filesystem.ts"],"sourcesContent":["import type {\n FunctionsConfigManifest,\n ManifestRoute,\n PrerenderManifest,\n RoutesManifest,\n} from '../../../build'\nimport type { NextConfigRuntime } from '../../config-shared'\nimport type { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-plugin'\nimport type { UnwrapPromise } from '../../../lib/coalesced-function'\nimport type { PatchMatcher } from '../../../shared/lib/router/utils/path-match'\nimport type { MiddlewareRouteMatch } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport type { __ApiPreviewProps } from '../../api-utils'\n\nimport path from 'path'\nimport fs from 'fs/promises'\nimport * as Log from '../../../build/output/log'\nimport setupDebug from 'next/dist/compiled/debug'\nimport { LRUCache } from '../lru-cache'\nimport loadCustomRoutes, { type Rewrite } from '../../../lib/load-custom-routes'\nimport { modifyRouteRegex } from '../../../lib/redirect-status'\nimport { FileType, fileExists } from '../../../lib/file-exists'\nimport { recursiveReadDir } from '../../../lib/recursive-readdir'\nimport { isDynamicRoute } from '../../../shared/lib/router/utils'\nimport { escapeStringRegexp } from '../../../shared/lib/escape-regexp'\nimport { getPathMatch } from '../../../shared/lib/router/utils/path-match'\nimport {\n getNamedRouteRegex,\n getRouteRegex,\n} from '../../../shared/lib/router/utils/route-regex'\nimport { getRouteMatcher } from '../../../shared/lib/router/utils/route-matcher'\nimport { pathHasPrefix } from '../../../shared/lib/router/utils/path-has-prefix'\nimport { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'\nimport { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'\nimport { getMiddlewareRouteMatcher } from '../../../shared/lib/router/utils/middleware-route-matcher'\nimport {\n APP_PATH_ROUTES_MANIFEST,\n BUILD_ID_FILE,\n FUNCTIONS_CONFIG_MANIFEST,\n MIDDLEWARE_MANIFEST,\n PAGES_MANIFEST,\n PRERENDER_MANIFEST,\n ROUTES_MANIFEST,\n} from '../../../shared/lib/constants'\nimport { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'\nimport { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'\nimport { RSCPathnameNormalizer } from '../../normalizers/request/rsc'\nimport { encodeURIPath } from '../../../shared/lib/encode-uri-path'\nimport { isMetadataRouteFile } from '../../../lib/metadata/is-metadata-route'\n\nexport type FsOutput = {\n type:\n | 'appFile'\n | 'pageFile'\n | 'nextImage'\n | 'publicFolder'\n | 'nextStaticFolder'\n | 'legacyStaticFolder'\n | 'devVirtualFsItem'\n\n itemPath: string\n fsPath?: string\n itemsRoot?: string\n locale?: string\n}\n\nconst debug = setupDebug('next:router-server:filesystem')\n\nexport type FilesystemDynamicRoute = ManifestRoute & {\n /**\n * The path matcher that can be used to match paths against this route.\n */\n match: PatchMatcher\n}\n\nexport const buildCustomRoute = <T>(\n type: 'redirect' | 'header' | 'rewrite' | 'before_files_rewrite',\n item: T & { source: string },\n basePath?: string,\n caseSensitive?: boolean\n): T & { match: PatchMatcher; check?: boolean; regex: string } => {\n const restrictedRedirectPaths = ['/_next'].map((p) =>\n basePath ? `${basePath}${p}` : p\n )\n let builtRegex = ''\n const match = getPathMatch(item.source, {\n strict: true,\n removeUnnamedParams: true,\n regexModifier: (regex: string) => {\n if (!(item as any).internal) {\n regex = modifyRouteRegex(\n regex,\n type === 'redirect' ? restrictedRedirectPaths : undefined\n )\n }\n builtRegex = regex\n return builtRegex\n },\n sensitive: caseSensitive,\n })\n\n return {\n ...item,\n regex: builtRegex,\n ...(type === 'rewrite' ? { check: true } : {}),\n match,\n }\n}\n\n// Measured retained cost of a cache entry beyond its strings (LRUNode,\n// Map slot, string header): ~120 bytes. Counting it keeps the entry count\n// bounded even when keys are short, so the budget approximates retained\n// bytes.\nconst FS_LRU_ENTRY_OVERHEAD = 128\nconst FS_LRU_MAX_SIZE = 8 * 1024 * 1024\n\n// The pathname passed to getItem is usually a V8 slice of the full request\n// URL, and a sliced string retains its parent — including the query string —\n// for as long as the cache holds the key. Store a flat copy instead.\n// The JSON round-trip returns an equal string for every input (unlike a\n// Buffer round-trip, which replaces lone surrogates), so distinct keys can\n// never collide on the stored copy.\nfunction flatKeyCopy(key: string): string {\n return JSON.parse(JSON.stringify(key))\n}\n\n// Cached result for paths that resolve to nothing. Not null, so that a\n// cached miss can't be conflated with an uncached key (undefined).\nconst notFound = Symbol('not-found')\n\nexport async function setupFsCheck(opts: {\n dir: string\n dev: boolean\n minimalMode?: boolean\n config: NextConfigRuntime\n}) {\n const getItemsLru = !opts.dev\n ? new LRUCache<FsOutput | typeof notFound>(FS_LRU_MAX_SIZE, function length(\n value,\n key\n ) {\n const size = FS_LRU_ENTRY_OVERHEAD + key.length\n if (value === notFound) {\n // Negative cache entries only retain their key.\n return size\n }\n return (\n size +\n (value.fsPath || '').length +\n value.itemPath.length +\n value.type.length\n )\n })\n : undefined\n\n // routes that have _next/data endpoints (SSG/SSP)\n const nextDataRoutes = new Set<string>()\n const publicFolderItems = new Set<string>()\n const nextStaticFolderItems = new Set<string>()\n const legacyStaticFolderItems = new Set<string>()\n\n const appFiles = new Set<string>()\n const pageFiles = new Set<string>()\n // Map normalized path to the file path. This is essential\n // for parallel and group routes as their original path\n // cannot be restored from the request path.\n // Example:\n // [normalized-path] -> [file-path]\n // /icon-<hash>.png -> .../app/@parallel/icon.png\n // /icon-<hash>.png -> .../app/(group)/icon.png\n // /icon.png -> .../app/icon.png\n const staticMetadataFiles = new Map<string, string>()\n let dynamicRoutes: FilesystemDynamicRoute[] = []\n\n let middlewareMatcher:\n | ReturnType<typeof getMiddlewareRouteMatcher>\n | undefined = () => false\n\n const distDir = path.join(opts.dir, opts.config.distDir)\n const publicFolderPath = path.join(opts.dir, 'public')\n const nextStaticFolderPath = path.join(distDir, 'static')\n const legacyStaticFolderPath = path.join(opts.dir, 'static')\n let customRoutes: UnwrapPromise<ReturnType<typeof loadCustomRoutes>> = {\n redirects: [],\n rewrites: {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n onMatchHeaders: [],\n headers: [],\n }\n let buildId = 'development'\n let previewProps: __ApiPreviewProps\n\n if (!opts.dev) {\n const buildIdPath = path.join(opts.dir, opts.config.distDir, BUILD_ID_FILE)\n try {\n buildId = await fs.readFile(buildIdPath, 'utf8')\n } catch (err: any) {\n if (err.code !== 'ENOENT') throw err\n throw new Error(\n `Could not find a production build in the '${opts.config.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`\n )\n }\n\n try {\n for (const file of await recursiveReadDir(publicFolderPath)) {\n // Ensure filename is encoded and normalized.\n publicFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(legacyStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n legacyStaticFolderItems.add(encodeURIPath(normalizePathSep(file)))\n }\n Log.warn(\n `The static directory has been deprecated in favor of the public directory. https://nextjs.org/docs/messages/static-dir-deprecated`\n )\n } catch (err: any) {\n if (err.code !== 'ENOENT') {\n throw err\n }\n }\n\n try {\n for (const file of await recursiveReadDir(nextStaticFolderPath)) {\n // Ensure filename is encoded and normalized.\n nextStaticFolderItems.add(\n path.posix.join(\n '/_next/static',\n encodeURIPath(normalizePathSep(file))\n )\n )\n }\n } catch (err) {\n if (opts.config.output !== 'standalone') throw err\n }\n\n const routesManifestPath = path.join(distDir, ROUTES_MANIFEST)\n const prerenderManifestPath = path.join(distDir, PRERENDER_MANIFEST)\n const middlewareManifestPath = path.join(\n distDir,\n 'server',\n MIDDLEWARE_MANIFEST\n )\n const functionsConfigManifestPath = path.join(\n distDir,\n 'server',\n FUNCTIONS_CONFIG_MANIFEST\n )\n const pagesManifestPath = path.join(distDir, 'server', PAGES_MANIFEST)\n const appRoutesManifestPath = path.join(distDir, APP_PATH_ROUTES_MANIFEST)\n\n const routesManifest = JSON.parse(\n await fs.readFile(routesManifestPath, 'utf8')\n ) as RoutesManifest\n\n previewProps = (\n JSON.parse(\n await fs.readFile(prerenderManifestPath, 'utf8')\n ) as PrerenderManifest\n ).preview\n\n const middlewareManifest = JSON.parse(\n await fs.readFile(middlewareManifestPath, 'utf8').catch(() => '{}')\n ) as MiddlewareManifest\n\n const functionsConfigManifest = JSON.parse(\n await fs.readFile(functionsConfigManifestPath, 'utf8').catch(() => '{}')\n ) as FunctionsConfigManifest\n\n const pagesManifest = JSON.parse(\n await fs.readFile(pagesManifestPath, 'utf8')\n )\n const appRoutesManifest = JSON.parse(\n await fs.readFile(appRoutesManifestPath, 'utf8').catch(() => '{}')\n )\n\n for (const key of Object.keys(pagesManifest)) {\n // ensure the non-locale version is in the set\n if (opts.config.i18n) {\n pageFiles.add(\n normalizeLocalePath(key, opts.config.i18n.locales).pathname\n )\n } else {\n pageFiles.add(key)\n }\n }\n for (const key of Object.keys(appRoutesManifest)) {\n appFiles.add(appRoutesManifest[key])\n }\n\n const escapedBuildId = escapeStringRegexp(buildId)\n\n for (const route of routesManifest.dataRoutes) {\n if (isDynamicRoute(route.page)) {\n const routeRegex = getNamedRouteRegex(route.page, {\n prefixRouteKeys: true,\n })\n dynamicRoutes.push({\n ...route,\n regex: routeRegex.re.toString(),\n namedRegex: routeRegex.namedRegex,\n routeKeys: routeRegex.routeKeys,\n match: getRouteMatcher({\n // TODO: fix this in the manifest itself, must also be fixed in\n // upstream builder that relies on this\n re: opts.config.i18n\n ? new RegExp(\n route.dataRouteRegex.replace(\n `/${escapedBuildId}/`,\n `/${escapedBuildId}/(?<nextLocale>[^/]+?)/`\n )\n )\n : new RegExp(route.dataRouteRegex),\n groups: routeRegex.groups,\n }),\n })\n }\n nextDataRoutes.add(route.page)\n }\n\n for (const route of routesManifest.dynamicRoutes) {\n // If a route is marked as skipInternalRouting, it's not for the internal\n // router, and instead has been added to support external routers.\n if (route.skipInternalRouting) {\n continue\n }\n\n dynamicRoutes.push({\n ...route,\n match: getRouteMatcher(getRouteRegex(route.page)),\n })\n }\n\n if (middlewareManifest.middleware?.['/']?.matchers) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n middlewareManifest.middleware?.['/']?.matchers\n )\n } else if (functionsConfigManifest?.functions['/_middleware']) {\n middlewareMatcher = getMiddlewareRouteMatcher(\n functionsConfigManifest.functions['/_middleware'].matchers ?? [\n { regexp: '.*', originalSource: '/:path*' },\n ]\n )\n }\n\n customRoutes = {\n redirects: routesManifest.redirects,\n rewrites: routesManifest.rewrites\n ? Array.isArray(routesManifest.rewrites)\n ? {\n beforeFiles: [],\n afterFiles: routesManifest.rewrites,\n fallback: [],\n }\n : routesManifest.rewrites\n : {\n beforeFiles: [],\n afterFiles: [],\n fallback: [],\n },\n headers: routesManifest.headers,\n onMatchHeaders: routesManifest.onMatchHeaders,\n }\n } else {\n // dev handling\n customRoutes = await loadCustomRoutes(opts.config)\n\n previewProps = {\n previewModeId: (require('crypto') as typeof import('crypto'))\n .randomBytes(16)\n .toString('hex'),\n previewModeSigningKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n previewModeEncryptionKey: (require('crypto') as typeof import('crypto'))\n .randomBytes(32)\n .toString('hex'),\n }\n }\n\n const headers = customRoutes.headers.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const onMatchHeaders = customRoutes.onMatchHeaders.map((item) =>\n buildCustomRoute(\n 'header',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const redirects = customRoutes.redirects.map((item) =>\n buildCustomRoute(\n 'redirect',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n )\n const rewrites = {\n beforeFiles: customRoutes.rewrites.beforeFiles.map((item) =>\n buildCustomRoute('before_files_rewrite', item)\n ),\n afterFiles: customRoutes.rewrites.afterFiles.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n fallback: customRoutes.rewrites.fallback.map((item) =>\n buildCustomRoute(\n 'rewrite',\n item,\n opts.config.basePath,\n opts.config.experimental.caseSensitiveRoutes\n )\n ),\n }\n\n const { i18n } = opts.config\n\n const handleLocale = (pathname: string, locales?: string[]) => {\n let locale: string | undefined\n\n if (i18n) {\n const i18nResult = normalizeLocalePath(pathname, locales || i18n.locales)\n\n pathname = i18nResult.pathname\n locale = i18nResult.detectedLocale\n }\n return { locale, pathname }\n }\n\n debug('nextDataRoutes', nextDataRoutes)\n debug('dynamicRoutes', dynamicRoutes)\n debug('customRoutes', customRoutes)\n debug('publicFolderItems', publicFolderItems)\n debug('nextStaticFolderItems', nextStaticFolderItems)\n debug('pageFiles', pageFiles)\n debug('appFiles', appFiles)\n\n let ensureFn: (item: FsOutput) => Promise<void> | undefined\n\n const normalizers = {\n // Because we can't know if the app directory is enabled or not at this\n // stage, we assume that it is.\n rsc: new RSCPathnameNormalizer(),\n }\n\n return {\n headers,\n onMatchHeaders,\n rewrites,\n redirects,\n\n buildId,\n handleLocale,\n\n appFiles,\n pageFiles,\n staticMetadataFiles,\n dynamicRoutes,\n nextDataRoutes,\n\n exportPathMapRoutes: undefined as\n | undefined\n | ReturnType<typeof buildCustomRoute<Rewrite>>[],\n\n devVirtualFsItems: new Set<string>(),\n\n previewProps,\n middlewareMatcher: middlewareMatcher as MiddlewareRouteMatch | undefined,\n\n ensureCallback(fn: typeof ensureFn) {\n ensureFn = fn\n },\n\n async getItem(itemPath: string): Promise<FsOutput | null> {\n const originalItemPath = itemPath\n const itemKey = originalItemPath\n const lruResult = getItemsLru?.get(itemKey)\n\n if (lruResult !== undefined) {\n return lruResult === notFound ? null : lruResult\n }\n\n const { basePath } = opts.config\n\n const hasBasePath = pathHasPrefix(itemPath, basePath)\n\n // Return null if path doesn't start with basePath\n if (basePath && !hasBasePath) {\n return null\n }\n\n // Remove basePath if it exists.\n if (basePath && hasBasePath) {\n itemPath = removePathPrefix(itemPath, basePath) || '/'\n }\n\n // Simulate minimal mode requests by normalizing RSC and postponed\n // requests.\n if (opts.minimalMode) {\n if (normalizers.rsc.match(itemPath)) {\n itemPath = normalizers.rsc.normalize(itemPath, true)\n }\n }\n\n if (itemPath !== '/' && itemPath.endsWith('/')) {\n itemPath = itemPath.substring(0, itemPath.length - 1)\n }\n\n let decodedItemPath = itemPath\n\n try {\n decodedItemPath = decodeURIComponent(itemPath)\n } catch {}\n\n if (itemPath === '/_next/image') {\n return {\n itemPath,\n type: 'nextImage',\n }\n }\n\n if (opts.dev && isMetadataRouteFile(itemPath, [], false)) {\n const fsPath = staticMetadataFiles.get(itemPath)\n if (fsPath) {\n return {\n // \"nextStaticFolder\" sets Cache-Control \"no-store\" on dev.\n type: 'nextStaticFolder',\n fsPath,\n itemPath: fsPath,\n }\n }\n }\n\n const itemsToCheck: Array<[Set<string>, FsOutput['type']]> = [\n [this.devVirtualFsItems, 'devVirtualFsItem'],\n [nextStaticFolderItems, 'nextStaticFolder'],\n [legacyStaticFolderItems, 'legacyStaticFolder'],\n [publicFolderItems, 'publicFolder'],\n [appFiles, 'appFile'],\n [pageFiles, 'pageFile'],\n ]\n\n for (let [items, type] of itemsToCheck) {\n let locale: string | undefined\n let curItemPath = itemPath\n let curDecodedItemPath = decodedItemPath\n\n const isDynamicOutput = type === 'pageFile' || type === 'appFile'\n\n if (i18n) {\n const localeResult = handleLocale(\n itemPath,\n // legacy behavior allows visiting static assets under\n // default locale but no other locale\n isDynamicOutput\n ? undefined\n : [\n i18n?.defaultLocale,\n // default locales from domains need to be matched too\n ...(i18n.domains?.map((item) => item.defaultLocale) || []),\n ]\n )\n\n if (localeResult.pathname !== curItemPath) {\n curItemPath = localeResult.pathname\n locale = localeResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n }\n\n if (type === 'legacyStaticFolder') {\n if (!pathHasPrefix(curItemPath, '/static')) {\n continue\n }\n curItemPath = curItemPath.substring('/static'.length)\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n if (\n type === 'nextStaticFolder' &&\n !pathHasPrefix(curItemPath, '/_next/static')\n ) {\n continue\n }\n\n const nextDataPrefix = `/_next/data/${buildId}/`\n\n if (\n type === 'pageFile' &&\n curItemPath.startsWith(nextDataPrefix) &&\n curItemPath.endsWith('.json')\n ) {\n items = nextDataRoutes\n // remove _next/data/<build-id> prefix\n curItemPath = curItemPath.substring(nextDataPrefix.length - 1)\n\n // remove .json postfix\n curItemPath = curItemPath.substring(\n 0,\n curItemPath.length - '.json'.length\n )\n const curLocaleResult = handleLocale(curItemPath)\n curItemPath =\n curLocaleResult.pathname === '/index'\n ? '/'\n : curLocaleResult.pathname\n\n locale = curLocaleResult.locale\n\n try {\n curDecodedItemPath = decodeURIComponent(curItemPath)\n } catch {}\n }\n\n let matchedItem = items.has(curItemPath)\n\n // check decoded variant as well\n if (!matchedItem && !opts.dev) {\n matchedItem = items.has(curDecodedItemPath)\n if (matchedItem) curItemPath = curDecodedItemPath\n else {\n // x-ref: https://github.com/vercel/next.js/issues/54008\n // There're cases that urls get decoded before requests, we should support both encoded and decoded ones.\n // e.g. nginx could decode the proxy urls, the below ones should be treated as the same:\n // decoded version: `/_next/static/chunks/pages/blog/[slug]-d4858831b91b69f6.js`\n // encoded version: `/_next/static/chunks/pages/blog/%5Bslug%5D-d4858831b91b69f6.js`\n try {\n // encode the special characters in the path and retrieve again to determine if path exists.\n const encodedCurItemPath = encodeURIPath(curItemPath)\n matchedItem = items.has(encodedCurItemPath)\n } catch {}\n }\n }\n\n if (matchedItem || opts.dev) {\n let fsPath: string | undefined\n let itemsRoot: string | undefined\n\n switch (type) {\n case 'nextStaticFolder': {\n itemsRoot = nextStaticFolderPath\n curItemPath = curItemPath.substring('/_next/static'.length)\n break\n }\n case 'legacyStaticFolder': {\n itemsRoot = legacyStaticFolderPath\n break\n }\n case 'publicFolder': {\n itemsRoot = publicFolderPath\n break\n }\n case 'appFile':\n case 'pageFile':\n case 'nextImage':\n case 'devVirtualFsItem': {\n break\n }\n default: {\n ;(type) satisfies never\n }\n }\n\n if (itemsRoot && curItemPath) {\n fsPath = path.posix.join(itemsRoot, curItemPath)\n }\n\n // dynamically check fs in development so we don't\n // have to wait on the watcher\n if (!matchedItem && opts.dev) {\n const isStaticAsset = (\n [\n 'nextStaticFolder',\n 'publicFolder',\n 'legacyStaticFolder',\n ] as (typeof type)[]\n ).includes(type)\n\n if (isStaticAsset && itemsRoot) {\n let found = fsPath && (await fileExists(fsPath, FileType.File))\n\n if (!found) {\n try {\n // In dev, we ensure encoded paths match\n // decoded paths on the filesystem so check\n // that variation as well\n const tempItemPath = decodeURIComponent(curItemPath)\n fsPath = path.posix.join(itemsRoot, tempItemPath)\n found = await fileExists(fsPath, FileType.File)\n } catch {}\n\n if (!found) {\n continue\n }\n }\n } else if (type === 'pageFile' || type === 'appFile') {\n const isAppFile = type === 'appFile'\n\n // Attempt to ensure the page/app file is compiled and ready\n if (ensureFn) {\n const ensureItemPath = isAppFile\n ? normalizeMetadataRoute(curItemPath)\n : curItemPath\n\n try {\n await ensureFn({ type, itemPath: ensureItemPath })\n } catch (error) {\n // If ensure failed, skip this item and continue to the next one\n continue\n }\n }\n } else {\n continue\n }\n }\n\n // i18n locales aren't matched for app dir\n if (type === 'appFile' && locale && locale !== i18n?.defaultLocale) {\n continue\n }\n\n const itemResult = {\n type,\n fsPath,\n locale,\n itemsRoot,\n // itemPath is usually a slice of the request URL too; keep a\n // flat copy so the cached value doesn't retain the full URL.\n itemPath: flatKeyCopy(curItemPath),\n }\n\n getItemsLru?.set(flatKeyCopy(itemKey), itemResult)\n return itemResult\n }\n }\n\n getItemsLru?.set(flatKeyCopy(itemKey), notFound)\n return null\n },\n getDynamicRoutes() {\n // this should include data routes\n return this.dynamicRoutes\n },\n getMiddlewareMatchers() {\n return this.middlewareMatcher\n },\n }\n}\n"],"names":["buildCustomRoute","setupFsCheck","debug","setupDebug","type","item","basePath","caseSensitive","restrictedRedirectPaths","map","p","builtRegex","match","getPathMatch","source","strict","removeUnnamedParams","regexModifier","regex","internal","modifyRouteRegex","undefined","sensitive","check","FS_LRU_ENTRY_OVERHEAD","FS_LRU_MAX_SIZE","flatKeyCopy","key","JSON","parse","stringify","notFound","Symbol","opts","getItemsLru","dev","LRUCache","length","value","size","fsPath","itemPath","nextDataRoutes","Set","publicFolderItems","nextStaticFolderItems","legacyStaticFolderItems","appFiles","pageFiles","staticMetadataFiles","Map","dynamicRoutes","middlewareMatcher","distDir","path","join","dir","config","publicFolderPath","nextStaticFolderPath","legacyStaticFolderPath","customRoutes","redirects","rewrites","beforeFiles","afterFiles","fallback","onMatchHeaders","headers","buildId","previewProps","middlewareManifest","buildIdPath","BUILD_ID_FILE","fs","readFile","err","code","Error","file","recursiveReadDir","add","encodeURIPath","normalizePathSep","Log","warn","posix","output","routesManifestPath","ROUTES_MANIFEST","prerenderManifestPath","PRERENDER_MANIFEST","middlewareManifestPath","MIDDLEWARE_MANIFEST","functionsConfigManifestPath","FUNCTIONS_CONFIG_MANIFEST","pagesManifestPath","PAGES_MANIFEST","appRoutesManifestPath","APP_PATH_ROUTES_MANIFEST","routesManifest","preview","catch","functionsConfigManifest","pagesManifest","appRoutesManifest","Object","keys","i18n","normalizeLocalePath","locales","pathname","escapedBuildId","escapeStringRegexp","route","dataRoutes","isDynamicRoute","page","routeRegex","getNamedRouteRegex","prefixRouteKeys","push","re","toString","namedRegex","routeKeys","getRouteMatcher","RegExp","dataRouteRegex","replace","groups","skipInternalRouting","getRouteRegex","middleware","matchers","getMiddlewareRouteMatcher","functions","regexp","originalSource","Array","isArray","loadCustomRoutes","previewModeId","require","randomBytes","previewModeSigningKey","previewModeEncryptionKey","experimental","caseSensitiveRoutes","handleLocale","locale","i18nResult","detectedLocale","ensureFn","normalizers","rsc","RSCPathnameNormalizer","exportPathMapRoutes","devVirtualFsItems","ensureCallback","fn","getItem","originalItemPath","itemKey","lruResult","get","hasBasePath","pathHasPrefix","removePathPrefix","minimalMode","normalize","endsWith","substring","decodedItemPath","decodeURIComponent","isMetadataRouteFile","itemsToCheck","items","curItemPath","curDecodedItemPath","isDynamicOutput","localeResult","defaultLocale","domains","nextDataPrefix","startsWith","curLocaleResult","matchedItem","has","encodedCurItemPath","itemsRoot","isStaticAsset","includes","found","fileExists","FileType","File","tempItemPath","isAppFile","ensureItemPath","normalizeMetadataRoute","error","itemResult","set","getDynamicRoutes","getMiddlewareMatchers"],"mappings":";;;;;;;;;;;;;;;IA0EaA,gBAAgB;eAAhBA;;IAuDSC,YAAY;eAAZA;;;6DApHL;iEACF;6DACM;8DACE;0BACE;yEACsB;gCACd;4BACI;kCACJ;uBACF;8BACI;2BACN;4BAItB;8BACyB;+BACF;qCACM;kCACH;wCACS;2BASnC;kCAC0B;kCACM;qBACD;+BACR;iCACM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBpC,MAAMC,QAAQC,IAAAA,cAAU,EAAC;AASlB,MAAMH,mBAAmB,CAC9BI,MACAC,MACAC,UACAC;IAEA,MAAMC,0BAA0B;QAAC;KAAS,CAACC,GAAG,CAAC,CAACC,IAC9CJ,WAAW,GAAGA,WAAWI,GAAG,GAAGA;IAEjC,IAAIC,aAAa;IACjB,MAAMC,QAA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AAW1C,wBAAAA,KAAM0E,aAAa,GAAE;wBAClE;oBACF;oBAEA,MAAMoB,aAAa;wBACjBtM;wBACAoC;wBACA8G;wBACAwC;wBACA,6DAA6D;wBAC7D,6DAA6D;wBAC7DrJ,UAAUf,YAAYwJ;oBACxB;oBAEAhJ,+BAAAA,YAAayK,GAAG,CAACjL,YAAYyI,UAAUuC;oBACvC,OAAOA;gBACT;YACF;YAEAxK,+BAAAA,YAAayK,GAAG,CAACjL,YAAYyI,UAAUpI;YACvC,OAAO;QACT;QACA6K;YACE,kCAAkC;YAClC,OAAO,IAAI,CAACzJ,aAAa;QAC3B;QACA0J;YACE,OAAO,IAAI,CAACzJ,iBAAiB;QAC/B;IACF;AACF","ignoreList":[0]} |
@@ -24,9 +24,9 @@ "use strict"; | ||
| parsedUrl.search = (0, _serverrouteutils.stringifyQuery)(req, query); | ||
| const target = _url.default.format(parsedUrl); | ||
| // Keep in mind that a WHATWG URL's hostname and the parsedUrl's hostname | ||
| // are not strictly equal due to lowercasing, IDN translation, IPv4 and IPv6 normalization, etc. | ||
| // We just make sure this is a valid URL since http-proxy doesn't validate. | ||
| new URL(target); | ||
| const HttpProxy = require('next/dist/compiled/http-proxy'); | ||
| const proxy = new HttpProxy({ | ||
| // We just make sure this is a valid URL since httpxy would only parse it | ||
| // lazily on the `web()`/`ws()` call. | ||
| const target = new URL(_url.default.format(parsedUrl)); | ||
| const { ProxyServer } = require('next/dist/compiled/httpxy'); | ||
| const proxy = new ProxyServer({ | ||
| target, | ||
@@ -44,3 +44,3 @@ changeOrigin: true, | ||
| let finished = false; | ||
| // http-proxy does not properly detect a client disconnect in newer | ||
| // httpxy does not properly detect a client disconnect in newer | ||
| // versions of Node.js. This is caused because it only listens for the | ||
@@ -79,6 +79,6 @@ // `aborted` event on the our request object, but it also fully reads | ||
| const detached = new _detachedpromise.DetachedPromise(); | ||
| proxy.on('error', (err)=>{ | ||
| console.error(`Failed to proxy ${target}`, err); | ||
| const onProxyError = (err)=>{ | ||
| if (!finished) { | ||
| finished = true; | ||
| console.error(`Failed to proxy ${target}`, err); | ||
| detached.reject(err); | ||
@@ -92,3 +92,4 @@ if (!res.destroyed) { | ||
| } | ||
| }); | ||
| }; | ||
| proxy.on('error', onProxyError); | ||
| // If upgrade head is present or the response is a Duplex stream, treat as | ||
@@ -105,3 +106,5 @@ // WebSocket request. | ||
| }); | ||
| proxy.ws(req, res, upgradeHead); | ||
| // The returned promise rejects on errors of the client socket (e.g. an | ||
| // abrupt client disconnect) even when an `error` listener is registered. | ||
| proxy.ws(req, res, {}, upgradeHead).catch(onProxyError); | ||
| detached.resolve(true); | ||
@@ -117,5 +120,8 @@ } else { | ||
| }); | ||
| // The returned promise rejects on errors of the client response stream | ||
| // (e.g. an abrupt client disconnect) even when an `error` listener is | ||
| // registered. | ||
| proxy.web(req, res, { | ||
| buffer: reqBody | ||
| }); | ||
| }).catch(onProxyError); | ||
| } | ||
@@ -122,0 +128,0 @@ // When the proxy finishes proxying the request, shut down the proxy. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/router-utils/proxy-request.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextUrlWithParsedQuery } from '../../request-meta'\n\nimport url from 'url'\nimport { stringifyQuery } from '../../server-route-utils'\nimport { Duplex } from 'stream'\nimport { DetachedPromise } from '../../../lib/detached-promise'\n\nexport async function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse | Duplex,\n parsedUrl: NextUrlWithParsedQuery,\n upgradeHead?: Buffer,\n reqBody?: any,\n proxyTimeout?: number | null\n) {\n const { query } = parsedUrl\n delete (parsedUrl as any).query\n parsedUrl.search = stringifyQuery(req as any, query)\n\n const target = url.format(parsedUrl)\n // Keep in mind that a WHATWG URL's hostname and the parsedUrl's hostname\n // are not strictly equal due to lowercasing, IDN translation, IPv4 and IPv6 normalization, etc.\n // We just make sure this is a valid URL since http-proxy doesn't validate.\n new URL(target)\n const HttpProxy =\n require('next/dist/compiled/http-proxy') as typeof import('next/dist/compiled/http-proxy')\n\n const proxy = new HttpProxy({\n target,\n changeOrigin: true,\n ignorePath: true,\n ws: true,\n // we limit proxy requests to 30s by default, in development\n // we don't time out WebSocket requests to allow proxying\n proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000,\n headers: {\n 'x-forwarded-host': req.headers.host || '',\n },\n })\n\n let finished = false\n\n // http-proxy does not properly detect a client disconnect in newer\n // versions of Node.js. This is caused because it only listens for the\n // `aborted` event on the our request object, but it also fully reads\n // and closes the request object. Node **will not** fire `aborted` when\n // the request is already closed. Listening for `close` on our response\n // object will detect the disconnect, and we can abort the proxy's\n // connection.\n proxy.on('proxyReq', (proxyReq) => {\n res.on('close', () => proxyReq.destroy())\n })\n\n proxy.on('proxyRes', (proxyRes) => {\n if (res.destroyed) {\n proxyRes.destroy()\n } else {\n res.on('close', () => proxyRes.destroy())\n }\n })\n\n proxy.on('proxyRes', (proxyRes, innerReq, innerRes) => {\n const cleanup = (err: any) => {\n // cleanup event listeners to allow clean garbage collection\n proxyRes.removeListener('error', cleanup)\n proxyRes.removeListener('close', cleanup)\n innerRes.removeListener('error', cleanup)\n innerRes.removeListener('close', cleanup)\n\n // destroy all source streams to propagate the caught event backward\n innerReq.destroy(err)\n proxyRes.destroy(err)\n }\n\n proxyRes.once('error', cleanup)\n proxyRes.once('close', cleanup)\n innerRes.once('error', cleanup)\n innerRes.once('close', cleanup)\n })\n\n const detached = new DetachedPromise<boolean>()\n\n proxy.on('error', (err) => {\n console.error(`Failed to proxy ${target}`, err)\n if (!finished) {\n finished = true\n detached.reject(err)\n\n if (!res.destroyed) {\n if (!(res instanceof Duplex)) {\n res.statusCode = 500\n }\n\n res.end('Internal Server Error')\n }\n }\n })\n\n // If upgrade head is present or the response is a Duplex stream, treat as\n // WebSocket request.\n if (upgradeHead || res instanceof Duplex) {\n proxy.on('proxyReqWs', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n proxy.ws(req, res, upgradeHead)\n detached.resolve(true)\n } else {\n proxy.on('proxyReq', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n proxy.web(req, res, {\n buffer: reqBody,\n })\n }\n\n // When the proxy finishes proxying the request, shut down the proxy.\n return detached.promise.finally(() => {\n proxy.close()\n })\n}\n"],"names":["proxyRequest","req","res","parsedUrl","upgradeHead","reqBody","proxyTimeout","query","search","stringifyQuery","target","url","format","URL","HttpProxy","require","proxy","changeOrigin","ignorePath","ws","undefined","headers","host","finished","on","proxyReq","destroy","proxyRes","destroyed","innerReq","innerRes","cleanup","err","removeListener","once","detached","DetachedPromise","console","error","reject","Duplex","statusCode","end","resolve","web","buffer","promise","finally","close"],"mappings":";;;;+BAQsBA;;;eAAAA;;;4DALN;kCACe;wBACR;iCACS;;;;;;AAEzB,eAAeA,aACpBC,GAAoB,EACpBC,GAA4B,EAC5BC,SAAiC,EACjCC,WAAoB,EACpBC,OAAa,EACbC,YAA4B;IAE5B,MAAM,EAAEC,KAAK,EAAE,GAAGJ;IAClB,OAAO,AAACA,UAAkBI,KAAK;IAC/BJ,UAAUK,MAAM,GAAGC,IAAAA,gCAAc,EAACR,KAAYM;IAE9C,MAAMG,SAASC,YAAG,CAACC,MAAM,CAACT;IAC1B,yEAAyE;IACzE,gGAAgG;IAChG,2EAA2E;IAC3E,IAAIU,IAAIH;IACR,MAAMI,YACJC,QAAQ;IAEV,MAAMC,QAAQ,IAAIF,UAAU;QAC1BJ;QACAO,cAAc;QACdC,YAAY;QACZC,IAAI;QACJ,4DAA4D;QAC5D,yDAAyD;QACzDb,cAAcA,iBAAiB,OAAOc,YAAYd,gBAAgB;QAClEe,SAAS;YACP,oBAAoBpB,IAAIoB,OAAO,CAACC,IAAI,IAAI;QAC1C;IACF;IAEA,IAAIC,WAAW;IAEf,mEAAmE;IACnE,sEAAsE;IACtE,qEAAqE;IACrE,uEAAuE;IACv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AASD,EAAE,CAAC,SAAS;gBACnB,IAAI,CAACD,UAAU;oBACbA,WAAW;oBACXY,SAASQ,OAAO,CAAC;gBACnB;YACF;QACF;QACA3B,MAAMG,EAAE,CAAClB,KAAKC,KAAKE;QACnB+B,SAASQ,OAAO,CAAC;IACnB,OAAO;QACL3B,MAAMQ,EAAE,CAAC,YAAY,CAACC;YACpBA,SAASD,EAAE,CAAC,SAAS;gBACnB,IAAI,CAACD,UAAU;oBACbA,WAAW;oBACXY,SAASQ,OAAO,CAAC;gBACnB;YACF;QACF;QACA3B,MAAM4B,GAAG,CAAC3C,KAAKC,KAAK;YAClB2C,QAAQxC;QACV;IACF;IAEA,qEAAqE;IACrE,OAAO8B,SAASW,OAAO,CAACC,OAAO,CAAC;QAC9B/B,MAAMgC,KAAK;IACb;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/router-utils/proxy-request.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'http'\nimport type { Socket } from 'net'\nimport type { NextUrlWithParsedQuery } from '../../request-meta'\n\nimport url from 'url'\nimport { stringifyQuery } from '../../server-route-utils'\nimport { Duplex } from 'stream'\nimport { DetachedPromise } from '../../../lib/detached-promise'\n\nexport async function proxyRequest(\n req: IncomingMessage,\n res: ServerResponse | Duplex,\n parsedUrl: NextUrlWithParsedQuery,\n upgradeHead?: Buffer,\n reqBody?: any,\n proxyTimeout?: number | null\n) {\n const { query } = parsedUrl\n delete (parsedUrl as any).query\n parsedUrl.search = stringifyQuery(req as any, query)\n\n // Keep in mind that a WHATWG URL's hostname and the parsedUrl's hostname\n // are not strictly equal due to lowercasing, IDN translation, IPv4 and IPv6 normalization, etc.\n // We just make sure this is a valid URL since httpxy would only parse it\n // lazily on the `web()`/`ws()` call.\n const target = new URL(url.format(parsedUrl))\n const { ProxyServer } =\n require('next/dist/compiled/httpxy') as typeof import('next/dist/compiled/httpxy')\n\n const proxy = new ProxyServer({\n target,\n changeOrigin: true,\n ignorePath: true,\n ws: true,\n // we limit proxy requests to 30s by default, in development\n // we don't time out WebSocket requests to allow proxying\n proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000,\n headers: {\n 'x-forwarded-host': req.headers.host || '',\n },\n })\n\n let finished = false\n\n // httpxy does not properly detect a client disconnect in newer\n // versions of Node.js. This is caused because it only listens for the\n // `aborted` event on the our request object, but it also fully reads\n // and closes the request object. Node **will not** fire `aborted` when\n // the request is already closed. Listening for `close` on our response\n // object will detect the disconnect, and we can abort the proxy's\n // connection.\n proxy.on('proxyReq', (proxyReq) => {\n res.on('close', () => proxyReq.destroy())\n })\n\n proxy.on('proxyRes', (proxyRes) => {\n if (res.destroyed) {\n proxyRes.destroy()\n } else {\n res.on('close', () => proxyRes.destroy())\n }\n })\n\n proxy.on('proxyRes', (proxyRes, innerReq, innerRes) => {\n const cleanup = (err: any) => {\n // cleanup event listeners to allow clean garbage collection\n proxyRes.removeListener('error', cleanup)\n proxyRes.removeListener('close', cleanup)\n innerRes.removeListener('error', cleanup)\n innerRes.removeListener('close', cleanup)\n\n // destroy all source streams to propagate the caught event backward\n innerReq.destroy(err)\n proxyRes.destroy(err)\n }\n\n proxyRes.once('error', cleanup)\n proxyRes.once('close', cleanup)\n innerRes.once('error', cleanup)\n innerRes.once('close', cleanup)\n })\n\n const detached = new DetachedPromise<boolean>()\n\n const onProxyError = (err: Error) => {\n if (!finished) {\n finished = true\n console.error(`Failed to proxy ${target}`, err)\n detached.reject(err)\n\n if (!res.destroyed) {\n if (!(res instanceof Duplex)) {\n res.statusCode = 500\n }\n\n res.end('Internal Server Error')\n }\n }\n }\n\n proxy.on('error', onProxyError)\n\n // If upgrade head is present or the response is a Duplex stream, treat as\n // WebSocket request.\n if (upgradeHead || res instanceof Duplex) {\n proxy.on('proxyReqWs', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n // The returned promise rejects on errors of the client socket (e.g. an\n // abrupt client disconnect) even when an `error` listener is registered.\n proxy.ws(req, res as Socket, {}, upgradeHead).catch(onProxyError)\n detached.resolve(true)\n } else {\n proxy.on('proxyReq', (proxyReq) => {\n proxyReq.on('close', () => {\n if (!finished) {\n finished = true\n detached.resolve(true)\n }\n })\n })\n // The returned promise rejects on errors of the client response stream\n // (e.g. an abrupt client disconnect) even when an `error` listener is\n // registered.\n proxy\n .web(req, res, {\n buffer: reqBody,\n })\n .catch(onProxyError)\n }\n\n // When the proxy finishes proxying the request, shut down the proxy.\n return detached.promise.finally(() => {\n proxy.close()\n })\n}\n"],"names":["proxyRequest","req","res","parsedUrl","upgradeHead","reqBody","proxyTimeout","query","search","stringifyQuery","target","URL","url","format","ProxyServer","require","proxy","changeOrigin","ignorePath","ws","undefined","headers","host","finished","on","proxyReq","destroy","proxyRes","destroyed","innerReq","innerRes","cleanup","err","removeListener","once","detached","DetachedPromise","onProxyError","console","error","reject","Duplex","statusCode","end","resolve","catch","web","buffer","promise","finally","close"],"mappings":";;;;+BASsBA;;;eAAAA;;;4DALN;kCACe;wBACR;iCACS;;;;;;AAEzB,eAAeA,aACpBC,GAAoB,EACpBC,GAA4B,EAC5BC,SAAiC,EACjCC,WAAoB,EACpBC,OAAa,EACbC,YAA4B;IAE5B,MAAM,EAAEC,KAAK,EAAE,GAAGJ;IAClB,OAAO,AAACA,UAAkBI,KAAK;IAC/BJ,UAAUK,MAAM,GAAGC,IAAAA,gCAAc,EAACR,KAAYM;IAE9C,yEAAyE;IACzE,gGAAgG;IAChG,yEAAyE;IACzE,qCAAqC;IACrC,MAAMG,SAAS,IAAIC,IAAIC,YAAG,CAACC,MAAM,CAACV;IAClC,MAAM,EAAEW,WAAW,EAAE,GACnBC,QAAQ;IAEV,MAAMC,QAAQ,IAAIF,YAAY;QAC5BJ;QACAO,cAAc;QACdC,YAAY;QACZC,IAAI;QACJ,4DAA4D;QAC5D,yDAAyD;QACzDb,cAAcA,iBAAiB,OAAOc,YAAYd,gBAAgB;QAClEe,SAAS;YACP,oBAAoB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3B,MAAMQ,EAAE,CAAC,SAASa;IAElB,0EAA0E;IAC1E,qBAAqB;IACrB,IAAIjC,eAAeF,eAAeuC,cAAM,EAAE;QACxCzB,MAAMQ,EAAE,CAAC,cAAc,CAACC;YACtBA,SAASD,EAAE,CAAC,SAAS;gBACnB,IAAI,CAACD,UAAU;oBACbA,WAAW;oBACXY,SAASS,OAAO,CAAC;gBACnB;YACF;QACF;QACA,uEAAuE;QACvE,yEAAyE;QACzE5B,MAAMG,EAAE,CAAClB,KAAKC,KAAe,CAAC,GAAGE,aAAayC,KAAK,CAACR;QACpDF,SAASS,OAAO,CAAC;IACnB,OAAO;QACL5B,MAAMQ,EAAE,CAAC,YAAY,CAACC;YACpBA,SAASD,EAAE,CAAC,SAAS;gBACnB,IAAI,CAACD,UAAU;oBACbA,WAAW;oBACXY,SAASS,OAAO,CAAC;gBACnB;YACF;QACF;QACA,uEAAuE;QACvE,sEAAsE;QACtE,cAAc;QACd5B,MACG8B,GAAG,CAAC7C,KAAKC,KAAK;YACb6C,QAAQ1C;QACV,GACCwC,KAAK,CAACR;IACX;IAEA,qEAAqE;IACrE,OAAOF,SAASa,OAAO,CAACC,OAAO,CAAC;QAC9BjC,MAAMkC,KAAK;IACb;AACF","ignoreList":[0]} |
@@ -156,4 +156,3 @@ "use strict"; | ||
| const invalidSourceMap = Symbol('invalid-source-map'); | ||
| const sourceMapURLs = new _lrucache.LRUCache(512 * 1024 * 1024, (url)=>url === invalidSourceMap ? // so that we don't create a huge cache with empty source maps. | ||
| 8 * 1024 : url.length); | ||
| const sourceMapURLs = new _lrucache.LRUCache(512 * 1024 * 1024, (url, sourceURL)=>sourceURL.length + (url === invalidSourceMap ? 8 * 1024 : url.length)); | ||
| function findSourceMapURLDEV(scriptNameOrSourceURL) { | ||
@@ -160,0 +159,0 @@ try { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n return undefined\n }\n let payload = sourceMapPayloads.get(sourceMap)\n if (payload === undefined) {\n payload = sourceMap.payload as ModernSourceMapPayload\n sourceMapPayloads.set(sourceMap, payload)\n }\n return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const payload = findSourceMapPayload(sourceURL)\n if (payload === undefined) {\n // No source map associated.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url) =>\n url === invalidSourceMap\n ? // Ideally we'd account for key length. So we just guestimate a small source map\n // so that we don't create a huge cache with empty source maps.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["devirtualizeReactServerURL","filterStackFrameDEV","findApplicableSourceMapPayload","findSourceMapPayload","findSourceMapURLDEV","ignoreListAnonymousStackFramesIfSandwiched","setBundlerFindSourceMapURLImplementation","sourceMapIgnoreListsEverything","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","sourceURL","sourceMap","payload","get","set","ignoreList","sources","length","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","LRUCache","url","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":";;;;;;;;;;;;;;;;;;;;;IA8QgBA,0BAA0B;eAA1BA;;IA3IAC,mBAAmB;eAAnBA;;IA1CAC,8BAA8B;eAA9BA;;IA9BAC,oBAAoB;eAApBA;;IAsKAC,mBAAmB;eAAnBA;;IA2EAC,0CAA0C;eAA1CA;;IAtGAC,wCAAwC;eAAxCA;;IA5HAC,8BAA8B;eAA9BA;;;0BAzES;AAEzB,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,0EAA0E;AAC1E,0EAA0E;AAC1E,qCAAqC;AACrC,MAAMK,oBAAoB,IAAIC;AAOvB,SAASb,qBACdc,SAAiB;IAEjB,MAAMC,YAAYR,cAAcO;IAChC,IAAIC,cAAcT,WAAW;QAC3B,OAAOA;IACT;IACA,IAAIU,UAAUJ,kBAAkBK,GAAG,CAACF;IACpC,IAAIC,YAAYV,WAAW;QACzBU,UAAUD,UAAUC,OAAO;QAC3BJ,kBAAkBM,GAAG,CAACH,WAAWC;IACnC;IACA,OAAOA;AACT;AAEO,SAASZ,+BACdW,SAAgC;IAEhC,OACEA,UAAUI,UAAU,KAAKb,aACzBS,UAAUK,OAAO,CAACC,MAAM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AC3CC,cAAyC,EACzCC,aAAuC,EACvC,2HAA2H,GAC3HC,WAAmC;IAEnC,IAAK,IAAIC,IAAI,GAAGA,IAAIL,OAAOxD,MAAM,EAAE6D,IAAK;QACtC,MAAMC,eAAeN,MAAM,CAACK,EAAE;QAC9B,IACE,CACEJ,CAAAA,iBAAiBK,iBACjBR,+BAA+BK,cAAcG,cAAa,GAE5D;YACA;QACF;QAEA,MAAMC,yBAAyBL,eAAeF,MAAM,CAACK,IAAI,EAAE;QAC3D,IAAIE,0BAA0BF,IAAIL,OAAOxD,MAAM,GAAG,GAAG;YACnD,IAAIgE,iBAAiB;YACrB,IAAIC,IAAIJ,IAAI;YACZ,IAAKI,GAAGA,IAAIT,OAAOxD,MAAM,EAAEiE,IAAK;gBAC9B,MAAMC,YAAYV,MAAM,CAACS,EAAE;gBAC3B,MAAME,uBACJV,iBAAiBS,cACjBZ,+BAA+BK,cAAcO;gBAC/C,IAAIC,sBAAsB;oBACxB;gBACF;gBAEA,MAAMC,qBAAqBV,eAAeQ;gBAC1C,IAAIE,oBAAoB;oBACtBJ,iBAAiB;oBACjB;gBACF;YACF;YAEA,IAAIA,gBAAgB;gBAClB,IAAKH,GAAGA,IAAII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/lib/source-maps.ts"],"sourcesContent":["import type { SourceMap } from 'module'\nimport { LRUCache } from './lru-cache'\n\nfunction noSourceMap(): SourceMap | undefined {\n return undefined\n}\n\n// Edge runtime does not implement `module`\nconst findSourceMap =\n process.env.NEXT_RUNTIME === 'edge'\n ? noSourceMap\n : (require('module') as typeof import('module')).findSourceMap\n\n/**\n * https://tc39.es/source-map/#index-map\n */\ninterface IndexSourceMapSection {\n offset: {\n line: number\n column: number\n }\n map: BasicSourceMapPayload\n}\n\n// TODO(veil): Upstream types\n/** https://tc39.es/ecma426/#sec-index-source-map */\ninterface IndexSourceMap {\n version: number\n file: string\n sections: IndexSourceMapSection[]\n}\n\n/** https://tc39.es/ecma426/#sec-source-map-format */\nexport interface BasicSourceMapPayload {\n version: number\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `file` is optional. */\n file: string\n sourceRoot?: string\n // TODO: Move to https://github.com/jridgewell/sourcemaps which is actively maintained\n /** WARNING: `sources[number]` can be `null`. */\n sources: Array<string>\n names: Array<string>\n mappings: string\n ignoreList?: number[]\n}\n\nexport type ModernSourceMapPayload = BasicSourceMapPayload | IndexSourceMap\n\n// `SourceMap#payload` deep-clones the payload on every access — expensive\n// for large chunk maps — so the clone is shared per `SourceMap` instance,\n// which Node.js memoizes per script.\nconst sourceMapPayloads = new WeakMap<SourceMap, ModernSourceMapPayload>()\n\n/**\n * Like `module.findSourceMap`, but returns the source map's payload without\n * cloning it on every call. Callers must not mutate the returned payload.\n * Throws like `module.findSourceMap` does on invalid source maps.\n */\nexport function findSourceMapPayload(\n sourceURL: string\n): ModernSourceMapPayload | undefined {\n const sourceMap = findSourceMap(sourceURL)\n if (sourceMap === undefined) {\n return undefined\n }\n let payload = sourceMapPayloads.get(sourceMap)\n if (payload === undefined) {\n payload = sourceMap.payload as ModernSourceMapPayload\n sourceMapPayloads.set(sourceMap, payload)\n }\n return payload\n}\n\nexport function sourceMapIgnoreListsEverything(\n sourceMap: BasicSourceMapPayload\n): boolean {\n return (\n sourceMap.ignoreList !== undefined &&\n sourceMap.sources.length === sourceMap.ignoreList.length\n )\n}\n\n/**\n * Finds the sourcemap payload applicable to a given frame.\n * Equal to the input unless an Index Source Map is used.\n * @param line0 - The line number of the frame, 0-based.\n * @param column0 - The column number of the frame, 0-based.\n */\nexport function findApplicableSourceMapPayload(\n line0: number,\n column0: number,\n payload: ModernSourceMapPayload\n): BasicSourceMapPayload | undefined {\n if ('sections' in payload) {\n if (payload.sections.length === 0) {\n return undefined\n }\n\n // Sections must not overlap and must be sorted: https://tc39.es/source-map/#section-object\n // Therefore the last section that has an offset less than or equal to the frame is the applicable one.\n const sections = payload.sections\n let left = 0\n let right = sections.length - 1\n let result: IndexSourceMapSection | null = null\n\n while (left <= right) {\n // fast Math.floor\n const middle = ~~((left + right) / 2)\n const section = sections[middle]\n const offset = section.offset\n\n if (\n offset.line < line0 ||\n (offset.line === line0 && offset.column <= column0)\n ) {\n result = section\n left = middle + 1\n } else {\n right = middle - 1\n }\n }\n\n return result === null ? undefined : result.map\n } else {\n return payload\n }\n}\n\nconst didWarnAboutInvalidSourceMapDEV = new Set<string>()\n\nexport function filterStackFrameDEV(\n sourceURL: string,\n functionName: string,\n line1: number,\n column1: number\n): boolean {\n if (sourceURL === '') {\n // The default implementation filters out <anonymous> stack frames\n // but we want to retain them because current Server Components and\n // built-in Components in parent stacks don't have source location.\n // Filter out frames that show up in Promises to get good names in React's\n // Server Request track until we come up with a better heuristic.\n return functionName !== 'new Promise'\n }\n if (sourceURL.startsWith('node:') || sourceURL.includes('node_modules')) {\n return false\n }\n try {\n // Node.js loads source maps eagerly so this call is cheap.\n // TODO: ESM sourcemaps are O(1) but CommonJS sourcemaps are O(Number of CJS modules).\n // Make sure this doesn't adversely affect performance when CJS is used by Next.js.\n const payload = findSourceMapPayload(sourceURL)\n if (payload === undefined) {\n // No source map associated.\n return true\n }\n const sourceMapPayload = findApplicableSourceMapPayload(\n line1 - 1,\n column1 - 1,\n payload\n )\n if (sourceMapPayload === undefined) {\n // No source map section applicable to the frame.\n return true\n }\n return !sourceMapIgnoreListsEverything(sourceMapPayload)\n } catch (cause) {\n if (process.env.NODE_ENV !== 'production') {\n // TODO: Share cache with patch-error-inspect\n if (!didWarnAboutInvalidSourceMapDEV.has(sourceURL)) {\n didWarnAboutInvalidSourceMapDEV.add(sourceURL)\n // We should not log an actual error instance here because that will re-enter\n // this codepath during error inspection and could lead to infinite recursion.\n console.error(\n `${sourceURL}: Invalid source map. Only conformant source maps can be used to filter stack frames. Cause: ${cause}`\n )\n }\n }\n\n return true\n }\n}\n\n// `scriptNameOrSourceURL` is what React forwards from the stack frame: the\n// script's `getScriptNameOrSourceURL()`, which for the server chunks we can\n// map is an absolute filesystem path, not a URL. The returned value is the\n// source map's URL (`file:` or `data:`).\ntype FindSourceMapURL = (scriptNameOrSourceURL: string) => string | null\n// Find the URL of a source map using the bundler's API.\n// Shared via `globalThis` because this module is compiled both into the server\n// runtime bundles (which call `findSourceMapURLDEV`) and into `next/dist/server`\n// (where the dev server registers the implementation), and each copy has its own\n// module state.\nconst bundlerFindSourceMapURLSymbol = Symbol.for(\n 'next.server.bundlerFindSourceMapURL'\n)\n\nexport function setBundlerFindSourceMapURLImplementation(\n findSourceMapURLImplementation: FindSourceMapURL\n): void {\n ;(globalThis as any)[bundlerFindSourceMapURLSymbol] =\n findSourceMapURLImplementation\n}\n\nfunction bundlerFindSourceMapURL(scriptNameOrSourceURL: string): string | null {\n const implementation: FindSourceMapURL | undefined = (globalThis as any)[\n bundlerFindSourceMapURLSymbol\n ]\n return implementation === undefined\n ? null\n : implementation(scriptNameOrSourceURL)\n}\n\nconst invalidSourceMap = Symbol('invalid-source-map')\nconst sourceMapURLs = new LRUCache<string | typeof invalidSourceMap>(\n 512 * 1024 * 1024,\n (url, sourceURL) =>\n sourceURL.length +\n (url === invalidSourceMap\n ? // Guestimate a small source map so invalid entries don't fill the cache.\n 8 * 1024\n : // these URLs contain only ASCII characters so .length is equal to Buffer.byteLength\n url.length)\n)\nexport function findSourceMapURLDEV(\n scriptNameOrSourceURL: string\n): string | null {\n try {\n const bundlerSourceMapURL = bundlerFindSourceMapURL(scriptNameOrSourceURL)\n if (bundlerSourceMapURL !== null) {\n return bundlerSourceMapURL\n }\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Failed to find the source map URL. Cause: ${cause}`\n )\n }\n\n // No bundler implementation (e.g. Webpack): inline the source map Node.js\n // knows as a `data:` URL.\n let sourceMapURL = sourceMapURLs.get(scriptNameOrSourceURL)\n if (sourceMapURL === undefined) {\n let sourceMapPayload: ModernSourceMapPayload | undefined\n try {\n sourceMapPayload = findSourceMapPayload(scriptNameOrSourceURL)\n } catch (cause) {\n console.error(\n `${scriptNameOrSourceURL}: Invalid source map. Only conformant source maps can be used to find the original code. Cause: ${cause}`\n )\n }\n\n if (sourceMapPayload === undefined) {\n sourceMapURL = invalidSourceMap\n } else {\n // TODO: Might be more efficient to extract the relevant section from Index Maps.\n // Unclear if that search is worth the smaller payload we have to stringify.\n const sourceMapJSON = JSON.stringify(sourceMapPayload)\n const sourceMapURLData = Buffer.from(sourceMapJSON, 'utf8').toString(\n 'base64'\n )\n sourceMapURL = `data:application/json;base64,${sourceMapURLData}`\n }\n\n sourceMapURLs.set(scriptNameOrSourceURL, sourceMapURL)\n }\n\n return sourceMapURL === invalidSourceMap ? null : sourceMapURL\n}\n\nexport function devirtualizeReactServerURL(sourceURL: string): string {\n if (sourceURL.startsWith('about://React/')) {\n // about://React/Server/file://<filename>?42 => file://<filename>\n const envIdx = sourceURL.indexOf('/', 'about://React/'.length)\n const suffixIdx = sourceURL.lastIndexOf('?')\n if (envIdx > -1 && suffixIdx > -1) {\n return decodeURI(sourceURL.slice(envIdx + 1, suffixIdx))\n }\n }\n return sourceURL\n}\n\nfunction isAnonymousFrameLikelyJSNative(methodName: string): boolean {\n // Anonymous frames can also be produced in React parent stacks either from\n // host components or Server Components. We don't want to ignore those.\n // This could hide user-space methods that are named like native JS methods but\n // should you really do that?\n return (\n // e.g. JSON.parse\n methodName.startsWith('JSON.') ||\n // E.g. Promise.withResolves\n methodName.startsWith('Function.') ||\n // various JS built-ins\n methodName.startsWith('Promise.') ||\n methodName.startsWith('Array.') ||\n methodName.startsWith('Set.') ||\n methodName.startsWith('Map.')\n )\n}\n\nexport function ignoreListAnonymousStackFramesIfSandwiched<Frame>(\n frames: Frame[],\n isAnonymousFrame: (frame: Frame) => boolean,\n isIgnoredFrame: (frame: Frame) => boolean,\n getMethodName: (frame: Frame) => string,\n /** only passes frames for which `isAnonymousFrame` and their method is a native JS method or `isIgnoredFrame` return true */\n ignoreFrame: (frame: Frame) => void\n): void {\n for (let i = 1; i < frames.length; i++) {\n const currentFrame = frames[i]\n if (\n !(\n isAnonymousFrame(currentFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(currentFrame))\n )\n ) {\n continue\n }\n\n const previousFrameIsIgnored = isIgnoredFrame(frames[i - 1])\n if (previousFrameIsIgnored && i < frames.length - 1) {\n let ignoreSandwich = false\n let j = i + 1\n for (j; j < frames.length; j++) {\n const nextFrame = frames[j]\n const nextFrameIsAnonymous =\n isAnonymousFrame(nextFrame) &&\n isAnonymousFrameLikelyJSNative(getMethodName(nextFrame))\n if (nextFrameIsAnonymous) {\n continue\n }\n\n const nextFrameIsIgnored = isIgnoredFrame(nextFrame)\n if (nextFrameIsIgnored) {\n ignoreSandwich = true\n break\n }\n }\n\n if (ignoreSandwich) {\n for (i; i < j; i++) {\n ignoreFrame(frames[i])\n }\n }\n }\n }\n}\n"],"names":["devirtualizeReactServerURL","filterStackFrameDEV","findApplicableSourceMapPayload","findSourceMapPayload","findSourceMapURLDEV","ignoreListAnonymousStackFramesIfSandwiched","setBundlerFindSourceMapURLImplementation","sourceMapIgnoreListsEverything","noSourceMap","undefined","findSourceMap","process","env","NEXT_RUNTIME","require","sourceMapPayloads","WeakMap","sourceURL","sourceMap","payload","get","set","ignoreList","sources","length","line0","column0","sections","left","right","result","middle","section","offset","line","column","map","didWarnAboutInvalidSourceMapDEV","Set","functionName","line1","column1","startsWith","includes","sourceMapPayload","cause","NODE_ENV","has","add","console","error","bundlerFindSourceMapURLSymbol","Symbol","for","findSourceMapURLImplementation","globalThis","bundlerFindSourceMapURL","scriptNameOrSourceURL","implementation","invalidSourceMap","sourceMapURLs","LRUCache","url","bundlerSourceMapURL","sourceMapURL","sourceMapJSON","JSON","stringify","sourceMapURLData","Buffer","from","toString","envIdx","indexOf","suffixIdx","lastIndexOf","decodeURI","slice","isAnonymousFrameLikelyJSNative","methodName","frames","isAnonymousFrame","isIgnoredFrame","getMethodName","ignoreFrame","i","currentFrame","previousFrameIsIgnored","ignoreSandwich","j","nextFrame","nextFrameIsAnonymous","nextFrameIsIgnored"],"mappings":";;;;;;;;;;;;;;;;;;;;;IA8QgBA,0BAA0B;eAA1BA;;IA3IAC,mBAAmB;eAAnBA;;IA1CAC,8BAA8B;eAA9BA;;IA9BAC,oBAAoB;eAApBA;;IAsKAC,mBAAmB;eAAnBA;;IA2EAC,0CAA0C;eAA1CA;;IAtGAC,wCAAwC;eAAxCA;;IA5HAC,8BAA8B;eAA9BA;;;0BAzES;AAEzB,SAASC;IACP,OAAOC;AACT;AAEA,2CAA2C;AAC3C,MAAMC,gBACJC,QAAQC,GAAG,CAACC,YAAY,KAAK,SACzBL,cACA,AAACM,QAAQ,UAAsCJ,aAAa;AAsClE,0EAA0E;AAC1E,0EAA0E;AAC1E,qCAAqC;AACrC,MAAMK,oBAAoB,IAAIC;AAOvB,SAASb,qBACdc,SAAiB;IAEjB,MAAMC,YAAYR,cAAcO;IAChC,IAAIC,cAAcT,WAAW;QAC3B,OAAOA;IACT;IACA,IAAIU,UAAUJ,kBAAkBK,GAAG,CAACF;IACpC,IAAIC,YAAYV,WAAW;QACzBU,UAAUD,UAAUC,OAAO;QAC3BJ,kBAAkBM,GAAG,CAACH,WAAWC;IACnC;IACA,OAAOA;AACT;AAEO,SAASZ,+BACdW,SAAgC;IAEhC,OACEA,UAAUI,UAAU,KAAKb,aACzBS,UAAUK,OAAO,CAACC,MAAM,KAAKN,UAAUI,UAAU,CAACE,MAAM;AAE5D;AAQO,SAAStB,+BACduB,KAAa,EACbC,OAAe,EACfP,OAA+B;IAE/B,IAAI,cAAcA,SAAS;QACzB,IAAIA,QAAQQ,QAAQ,CAACH,MAAM,KAAK,GAAG;YACjC,OAAOf;QACT;QAEA,2FAA2F;QAC3F,uGAAuG;QACvG,MAAMkB,WAAWR,QAAQQ,QAAQ;QACjC,IAAIC,OAAO;QACX,IAAIC,QAAQF,SAASH,MAAM,GAAG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CAACK,IAAI,EAAE;QAC3D,IAAIE,0BAA0BF,IAAIL,OAAOxD,MAAM,GAAG,GAAG;YACnD,IAAIgE,iBAAiB;YACrB,IAAIC,IAAIJ,IAAI;YACZ,IAAKI,GAAGA,IAAIT,OAAOxD,MAAM,EAAEiE,IAAK;gBAC9B,MAAMC,YAAYV,MAAM,CAACS,EAAE;gBAC3B,MAAME,uBACJV,iBAAiBS,cACjBZ,+BAA+BK,cAAcO;gBAC/C,IAAIC,sBAAsB;oBACxB;gBACF;gBAEA,MAAMC,qBAAqBV,eAAeQ;gBAC1C,IAAIE,oBAAoB;oBACtBJ,iBAAiB;oBACjB;gBACF;YACF;YAEA,IAAIA,gBAAgB;gBAClB,IAAKH,GAAGA,IAAII,GAAGJ,IAAK;oBAClBD,YAAYJ,MAAM,CAACK,EAAE;gBACvB;YACF;QACF;IACF;AACF","ignoreList":[0]} |
@@ -180,3 +180,3 @@ // Start CPU profile if it wasn't already started. | ||
| let { port } = serverOptions; | ||
| process.title = `next-server (v${"16.3.0-canary.97"})`; | ||
| process.title = `next-server (v${"16.3.0-canary.99"})`; | ||
| let handlersReady = ()=>{}; | ||
@@ -183,0 +183,0 @@ let handlersError = ()=>{}; |
@@ -80,3 +80,4 @@ /** | ||
| waitShellReady = "AppRender.waitShellReady", | ||
| renderToNodeFizzStream = "AppRender.renderToNodeFizzStream" | ||
| renderToNodeFizzStream = "AppRender.renderToNodeFizzStream", | ||
| instantInsights = "AppRender.instantInsights" | ||
| } | ||
@@ -83,0 +84,0 @@ declare enum RouterSpan { |
@@ -158,2 +158,3 @@ /** | ||
| AppRenderSpan["renderToNodeFizzStream"] = "AppRender.renderToNodeFizzStream"; | ||
| AppRenderSpan["instantInsights"] = "AppRender.instantInsights"; | ||
| return AppRenderSpan; | ||
@@ -160,0 +161,0 @@ }(AppRenderSpan || {}); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["AppRenderSpan","AppRouteRouteHandlersSpan","BaseServerSpan","LoadComponentsSpan","LogSpanAllowList","MiddlewareSpan","NextNodeServerSpan","NextServerSpan","NextVanillaSpanAllowlist","NodeSpan","RenderSpan","ResolveMetadataSpan","RouterSpan","StartServerSpan","Set"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA6J1CA,aAAa;eAAbA;;IAEAC,yBAAyB;eAAzBA;;IATAC,cAAc;eAAdA;;IACAC,kBAAkB;eAAlBA;;IARWC,gBAAgB;eAAhBA;;IAkBXC,cAAc;eAAdA;;IARAC,kBAAkB;eAAlBA;;IADAC,cAAc;eAAdA;;IA9BWC,wBAAwB;eAAxBA;;IAoCXC,QAAQ;eAARA;;IAHAC,UAAU;eAAVA;;IAKAC,mBAAmB;eAAnBA;;IAJAC,UAAU;eAAVA;;IAFAC,eAAe;eAAfA;;;AAxJF,IAAA,AAAKX,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKI,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKD,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKO,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKV,uCAAAA;;;;;;;WAAAA;EAAAA;AASL,IAAA,AAAKY,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKR,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKU,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKN,wCAAAA;;WAAAA;EAAAA;AAmBE,MAAMG,2BAA2B,IAAIM,IAAI;;;;;;;;;;;;;;;;;CAiB/C;AAIM,MAAMV,mBAAmB,IAAIU,IAAI;;;;CAIvC","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/constants.ts"],"sourcesContent":["/**\n * Contains predefined constants for the trace span name in next/server.\n *\n * Currently, next/server/tracer is internal implementation only for tracking\n * next.js's implementation only with known span names defined here.\n **/\n\n// eslint typescript has a bug with TS enums\n\nenum BaseServerSpan {\n handleRequest = 'BaseServer.handleRequest',\n run = 'BaseServer.run',\n pipe = 'BaseServer.pipe',\n getStaticHTML = 'BaseServer.getStaticHTML',\n render = 'BaseServer.render',\n renderToResponseWithComponents = 'BaseServer.renderToResponseWithComponents',\n renderToResponse = 'BaseServer.renderToResponse',\n renderToHTML = 'BaseServer.renderToHTML',\n renderError = 'BaseServer.renderError',\n renderErrorToResponse = 'BaseServer.renderErrorToResponse',\n renderErrorToHTML = 'BaseServer.renderErrorToHTML',\n render404 = 'BaseServer.render404',\n}\n\nenum LoadComponentsSpan {\n loadDefaultErrorComponents = 'LoadComponents.loadDefaultErrorComponents',\n loadComponents = 'LoadComponents.loadComponents',\n}\n\nenum NextServerSpan {\n getRequestHandler = 'NextServer.getRequestHandler',\n getRequestHandlerWithMetadata = 'NextServer.getRequestHandlerWithMetadata',\n getServer = 'NextServer.getServer',\n getServerRequestHandler = 'NextServer.getServerRequestHandler',\n createServer = 'createServer.createServer',\n}\n\nenum NextNodeServerSpan {\n compression = 'NextNodeServer.compression',\n getBuildId = 'NextNodeServer.getBuildId',\n createComponentTree = 'NextNodeServer.createComponentTree',\n clientComponentLoading = 'NextNodeServer.clientComponentLoading',\n getLayoutOrPageModule = 'NextNodeServer.getLayoutOrPageModule',\n generateStaticRoutes = 'NextNodeServer.generateStaticRoutes',\n generateFsStaticRoutes = 'NextNodeServer.generateFsStaticRoutes',\n generatePublicRoutes = 'NextNodeServer.generatePublicRoutes',\n generateImageRoutes = 'NextNodeServer.generateImageRoutes.route',\n sendRenderResult = 'NextNodeServer.sendRenderResult',\n proxyRequest = 'NextNodeServer.proxyRequest',\n runApi = 'NextNodeServer.runApi',\n render = 'NextNodeServer.render',\n renderHTML = 'NextNodeServer.renderHTML',\n imageOptimizer = 'NextNodeServer.imageOptimizer',\n getPagePath = 'NextNodeServer.getPagePath',\n getRoutesManifest = 'NextNodeServer.getRoutesManifest',\n findPageComponents = 'NextNodeServer.findPageComponents',\n getFontManifest = 'NextNodeServer.getFontManifest',\n getServerComponentManifest = 'NextNodeServer.getServerComponentManifest',\n getRequestHandler = 'NextNodeServer.getRequestHandler',\n renderToHTML = 'NextNodeServer.renderToHTML',\n renderError = 'NextNodeServer.renderError',\n renderErrorToHTML = 'NextNodeServer.renderErrorToHTML',\n render404 = 'NextNodeServer.render404',\n startResponse = 'NextNodeServer.startResponse',\n\n // nested inner span, does not require parent scope name\n route = 'route',\n onProxyReq = 'onProxyReq',\n apiResolver = 'apiResolver',\n internalFetch = 'internalFetch',\n}\n\nenum StartServerSpan {\n startServer = 'startServer.startServer',\n}\n\nenum RenderSpan {\n getServerSideProps = 'Render.getServerSideProps',\n getStaticProps = 'Render.getStaticProps',\n renderToString = 'Render.renderToString',\n renderDocument = 'Render.renderDocument',\n createBodyResult = 'Render.createBodyResult',\n}\n\nenum AppRenderSpan {\n renderToString = 'AppRender.renderToString',\n renderToReadableStream = 'AppRender.renderToReadableStream',\n getBodyResult = 'AppRender.getBodyResult',\n fetch = 'AppRender.fetch',\n waitShellReady = 'AppRender.waitShellReady',\n renderToNodeFizzStream = 'AppRender.renderToNodeFizzStream',\n instantInsights = 'AppRender.instantInsights',\n}\n\nenum RouterSpan {\n executeRoute = 'Router.executeRoute',\n}\n\nenum NodeSpan {\n runHandler = 'Node.runHandler',\n}\n\nenum AppRouteRouteHandlersSpan {\n runHandler = 'AppRouteRouteHandlers.runHandler',\n}\n\nenum ResolveMetadataSpan {\n generateMetadata = 'ResolveMetadata.generateMetadata',\n generateViewport = 'ResolveMetadata.generateViewport',\n}\n\nenum MiddlewareSpan {\n execute = 'Middleware.execute',\n}\n\ntype SpanTypes =\n | `${BaseServerSpan}`\n | `${LoadComponentsSpan}`\n | `${NextServerSpan}`\n | `${StartServerSpan}`\n | `${NextNodeServerSpan}`\n | `${RenderSpan}`\n | `${RouterSpan}`\n | `${AppRenderSpan}`\n | `${NodeSpan}`\n | `${AppRouteRouteHandlersSpan}`\n | `${ResolveMetadataSpan}`\n | `${MiddlewareSpan}`\n\n// This list is used to filter out spans that are not relevant to the user\nexport const NextVanillaSpanAllowlist = new Set([\n MiddlewareSpan.execute,\n BaseServerSpan.handleRequest,\n RenderSpan.getServerSideProps,\n RenderSpan.getStaticProps,\n AppRenderSpan.fetch,\n AppRenderSpan.getBodyResult,\n RenderSpan.renderDocument,\n NodeSpan.runHandler,\n AppRouteRouteHandlersSpan.runHandler,\n ResolveMetadataSpan.generateMetadata,\n ResolveMetadataSpan.generateViewport,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.getLayoutOrPageModule,\n NextNodeServerSpan.startResponse,\n NextNodeServerSpan.clientComponentLoading,\n])\n\n// These Spans are allowed to be always logged\n// when the otel log prefix env is set\nexport const LogSpanAllowList = new Set([\n NextNodeServerSpan.findPageComponents,\n NextNodeServerSpan.createComponentTree,\n NextNodeServerSpan.clientComponentLoading,\n])\n\nexport {\n BaseServerSpan,\n LoadComponentsSpan,\n NextServerSpan,\n NextNodeServerSpan,\n StartServerSpan,\n RenderSpan,\n RouterSpan,\n AppRenderSpan,\n NodeSpan,\n AppRouteRouteHandlersSpan,\n ResolveMetadataSpan,\n MiddlewareSpan,\n}\n\nexport type { SpanTypes }\n"],"names":["AppRenderSpan","AppRouteRouteHandlersSpan","BaseServerSpan","LoadComponentsSpan","LogSpanAllowList","MiddlewareSpan","NextNodeServerSpan","NextServerSpan","NextVanillaSpanAllowlist","NodeSpan","RenderSpan","ResolveMetadataSpan","RouterSpan","StartServerSpan","Set"],"mappings":"AAAA;;;;;EAKE,GAEF,4CAA4C;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA8J1CA,aAAa;eAAbA;;IAEAC,yBAAyB;eAAzBA;;IATAC,cAAc;eAAdA;;IACAC,kBAAkB;eAAlBA;;IARWC,gBAAgB;eAAhBA;;IAkBXC,cAAc;eAAdA;;IARAC,kBAAkB;eAAlBA;;IADAC,cAAc;eAAdA;;IA9BWC,wBAAwB;eAAxBA;;IAoCXC,QAAQ;eAARA;;IAHAC,UAAU;eAAVA;;IAKAC,mBAAmB;eAAnBA;;IAJAC,UAAU;eAAVA;;IAFAC,eAAe;eAAfA;;;AAzJF,IAAA,AAAKX,wCAAAA;;;;;;;;;;;;;WAAAA;EAAAA;AAeL,IAAA,AAAKC,4CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKI,wCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKD,4CAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4BH,wDAAwD;;;;;WA5BrDA;EAAAA;AAmCL,IAAA,AAAKO,yCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,oCAAAA;;;;;;WAAAA;EAAAA;AAQL,IAAA,AAAKV,uCAAAA;;;;;;;;WAAAA;EAAAA;AAUL,IAAA,AAAKY,oCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKH,kCAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKR,mDAAAA;;WAAAA;EAAAA;AAIL,IAAA,AAAKU,6CAAAA;;;WAAAA;EAAAA;AAKL,IAAA,AAAKN,wCAAAA;;WAAAA;EAAAA;AAmBE,MAAMG,2BAA2B,IAAIM,IAAI;;;;;;;;;;;;;;;;;CAiB/C;AAIM,MAAMV,mBAAmB,IAAIU,IAAI;;;;CAIvC","ignoreList":[0]} |
@@ -141,5 +141,6 @@ "use strict"; | ||
| } | ||
| const eventTime = startTime === undefined && isTimestampInput(attributesOrStartTime) ? attributesOrStartTime : startTime; | ||
| this.events.push({ | ||
| name, | ||
| timestamp: Date.now(), | ||
| timestamp: getTimestamp(eventTime), | ||
| attributes: isSpanStoreAttributes(attributesOrStartTime) ? cleanSpanStoreAttributes(attributesOrStartTime) : undefined | ||
@@ -196,3 +197,3 @@ }); | ||
| name: 'exception', | ||
| timestamp: Date.now(), | ||
| timestamp: getTimestamp(time), | ||
| attributes: getSpanStoreExceptionAttributes(this.exception) | ||
@@ -213,2 +214,3 @@ }); | ||
| requestId: this.requestIdentity.requestId, | ||
| requestInsightKind: this.requestIdentity.requestInsightKind, | ||
| htmlRequestId: this.requestIdentity.htmlRequestId, | ||
@@ -276,11 +278,6 @@ route: getStringAttribute(recordAttributes, 'next.route') ?? getStringAttribute(recordAttributes, 'http.route') ?? this.requestIdentity.route, | ||
| if (typeof time === 'number') { | ||
| const timeOrigin = getPerformanceTimeOrigin(); | ||
| return timeOrigin !== undefined && time < timeOrigin ? timeOrigin + time : time; | ||
| return time < performance.timeOrigin / 2 ? performance.timeOrigin + time : time; | ||
| } | ||
| const timeOrigin = getPerformanceTimeOrigin(); | ||
| return timeOrigin === undefined ? Date.now() : timeOrigin + performance.now(); | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
| function getPerformanceTimeOrigin() { | ||
| return typeof performance !== 'undefined' && typeof performance.timeOrigin === 'number' ? performance.timeOrigin : undefined; | ||
| } | ||
| function getStringAttribute(attributes, key) { | ||
@@ -293,2 +290,5 @@ const value = attributes == null ? void 0 : attributes[key]; | ||
| } | ||
| function isTimestampInput(value) { | ||
| return typeof value === 'number' || Array.isArray(value) || value instanceof Date; | ||
| } | ||
| function getSpanStoreException(exception) { | ||
@@ -338,4 +338,5 @@ if (exception instanceof Error) { | ||
| return { | ||
| requestId: (workStore == null ? void 0 : workStore.requestId) ?? (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId), | ||
| htmlRequestId: (workStore == null ? void 0 : workStore.htmlRequestId) ?? (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId), | ||
| requestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.requestId) ?? (workStore == null ? void 0 : workStore.requestId), | ||
| requestInsightKind: requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.kind, | ||
| htmlRequestId: (requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.htmlRequestId) ?? (workStore == null ? void 0 : workStore.htmlRequestId), | ||
| route: workStore == null ? void 0 : workStore.route, | ||
@@ -342,0 +343,0 @@ url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity == null ? void 0 : requestInsightsIdentity.url |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/local-span-recorder.ts"],"sourcesContent":["import type {\n AttributeValue,\n Span,\n SpanOptions,\n} from 'next/dist/compiled/@opentelemetry/api'\nimport type { AsyncLocalStorage } from 'async_hooks'\nimport { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'\nimport {\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n recordSpan,\n type SpanStoreAttributes,\n type SpanStoreEvent,\n type SpanStoreLink,\n} from './span-store'\n\nexport { isLocalSpanRecordingEnabled } from './span-store'\n\nconst TRACE_ID_HEX_LENGTH = 32\nconst SPAN_ID_HEX_LENGTH = 16\n\ntype LocalSpanAttributes = Partial<Record<string, AttributeValue | undefined>>\n\nlet lastLocalTraceId = 0\nlet lastLocalSpanId = 0\nlet localSpanAsyncStorage: AsyncLocalStorage<Span> | undefined\n\nconst getLocalTraceId = () =>\n (++lastLocalTraceId).toString(16).padStart(TRACE_ID_HEX_LENGTH, '0')\n\nconst getLocalSpanId = () =>\n (++lastLocalSpanId).toString(16).padStart(SPAN_ID_HEX_LENGTH, '0')\n\nexport function createLocalSpan({\n name,\n attributes,\n links,\n startTime,\n traceId,\n spanId,\n parentSpanId,\n delegateSpan,\n}: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n traceId?: string\n spanId?: string\n parentSpanId?: string\n delegateSpan?: Span\n}): Span {\n return new LocalRecordingSpan({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId: traceId ?? getLocalTraceId(),\n spanId: spanId ?? getLocalSpanId(),\n parentSpanId,\n requestIdentity: getCurrentRequestIdentity(),\n })\n}\n\nexport function getActiveLocalSpan(): Span | undefined {\n return localSpanAsyncStorage?.getStore()\n}\n\nexport function isLocalRecordingSpan(span: Span): boolean {\n return span instanceof LocalRecordingSpan\n}\n\nexport function withLocalSpan<T>(span: Span, fn: () => T): T {\n return getLocalSpanAsyncStorage().run(span, fn)\n}\n\nexport type LocalSpanRecorder = {\n createLocalSpan: typeof createLocalSpan\n getActiveLocalSpan: typeof getActiveLocalSpan\n isLocalRecordingSpan: typeof isLocalRecordingSpan\n isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled\n isRequestInsightsEnabled: typeof isRequestInsightsEnabled\n withLocalSpan: typeof withLocalSpan\n}\n\nexport function registerLocalSpanRecorder(): void {\n const key = Symbol.for('@next/local-span-recorder')\n ;(\n globalThis as typeof globalThis & {\n [key]?: LocalSpanRecorder\n }\n )[key] = {\n createLocalSpan,\n getActiveLocalSpan,\n isLocalRecordingSpan,\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n withLocalSpan,\n }\n}\n\nfunction getLocalSpanAsyncStorage(): AsyncLocalStorage<Span> {\n if (!localSpanAsyncStorage) {\n const { createAsyncLocalStorage } =\n require('../../app-render/async-local-storage') as typeof import('../../app-render/async-local-storage')\n localSpanAsyncStorage = createAsyncLocalStorage()\n }\n\n return localSpanAsyncStorage\n}\n\ntype RequestIdentity = {\n requestId?: string\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nclass LocalRecordingSpan implements Span {\n public name: string\n\n private attributes: SpanStoreAttributes\n private events: SpanStoreEvent[]\n private readonly spanContextValue: ReturnType<Span['spanContext']>\n private delegateSpan?: Span\n private links?: SpanStoreLink[]\n private readonly parentSpanId?: string\n private requestIdentity: RequestIdentity\n private readonly startTime: number\n private statusCode: number | undefined\n private statusMessage: string | undefined\n private exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n private ended: boolean\n\n constructor({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId,\n spanId,\n parentSpanId,\n requestIdentity,\n }: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n delegateSpan?: Span\n traceId: string\n spanId: string\n parentSpanId?: string\n requestIdentity: RequestIdentity\n }) {\n this.name = name\n this.attributes = cleanSpanStoreAttributes(attributes)\n this.events = []\n this.delegateSpan = delegateSpan\n this.spanContextValue = delegateSpan?.spanContext() ?? {\n traceId,\n spanId,\n traceFlags: 0,\n }\n this.links = getSpanStoreLinks(links)\n this.parentSpanId = parentSpanId\n this.requestIdentity = requestIdentity\n this.startTime = getTimestamp(startTime)\n this.statusCode = undefined\n this.statusMessage = undefined\n this.exception = undefined\n this.ended = false\n }\n\n spanContext(): ReturnType<Span['spanContext']> {\n return this.spanContextValue\n }\n\n setAttribute(key: string, value: AttributeValue): this {\n if (this.ended) {\n return this\n }\n\n this.attributes[key] = value\n this.delegateSpan?.setAttribute(key, value)\n return this\n }\n\n setAttributes(attributes: Parameters<Span['setAttributes']>[0]): this {\n if (this.ended) {\n return this\n }\n\n // OpenTelemetry attributes may be undefined. Ignore them instead of\n // overwriting an existing value as Object.assign would.\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n this.attributes[key] = value\n }\n }\n this.delegateSpan?.setAttributes(attributes)\n return this\n }\n\n addEvent(\n name: string,\n attributesOrStartTime?: Parameters<Span['addEvent']>[1],\n startTime?: Parameters<Span['addEvent']>[2]\n ): this {\n if (this.ended) {\n return this\n }\n\n this.events.push({\n name,\n timestamp: Date.now(),\n attributes: isSpanStoreAttributes(attributesOrStartTime)\n ? cleanSpanStoreAttributes(attributesOrStartTime)\n : undefined,\n })\n this.delegateSpan?.addEvent(name, attributesOrStartTime, startTime)\n return this\n }\n\n setStatus(status: Parameters<Span['setStatus']>[0]): this {\n if (this.ended) {\n return this\n }\n\n this.statusCode = status.code\n this.statusMessage = status.message\n this.delegateSpan?.setStatus(status)\n return this\n }\n\n updateName(name: string): this {\n if (this.ended) {\n return this\n }\n\n this.name = name\n this.delegateSpan?.updateName(name)\n return this\n }\n\n end(endTime?: Parameters<Span['end']>[0]): void {\n if (this.ended) {\n return\n }\n\n this.ended = true\n try {\n this.delegateSpan?.end(endTime)\n } finally {\n try {\n this.record(endTime)\n } finally {\n this.releaseReferences()\n }\n }\n }\n\n isRecording(): boolean {\n return !this.ended\n }\n\n recordException(\n exception: Parameters<Span['recordException']>[0],\n time?: Parameters<Span['recordException']>[1]\n ): void {\n if (this.ended) {\n return\n }\n\n this.exception = getSpanStoreException(exception)\n this.events.push({\n name: 'exception',\n timestamp: Date.now(),\n attributes: getSpanStoreExceptionAttributes(this.exception),\n })\n this.delegateSpan?.recordException(exception, time)\n }\n\n private record(endTime: Parameters<Span['end']>[0]): void {\n const recordAttributes =\n Object.keys(this.attributes).length > 0 ? this.attributes : undefined\n\n recordSpan({\n name: this.name,\n startTime: this.startTime,\n durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),\n status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',\n traceId: this.spanContextValue.traceId,\n spanId: this.spanContextValue.spanId,\n parentSpanId: this.parentSpanId,\n requestId: this.requestIdentity.requestId,\n htmlRequestId: this.requestIdentity.htmlRequestId,\n route:\n getStringAttribute(recordAttributes, 'next.route') ??\n getStringAttribute(recordAttributes, 'http.route') ??\n this.requestIdentity.route,\n url:\n getStringAttribute(recordAttributes, 'http.url') ??\n this.requestIdentity.url,\n attributes: recordAttributes,\n links: this.links,\n events: this.events.length > 0 ? this.events : undefined,\n error: this.getRecordError(),\n })\n }\n\n private releaseReferences(): void {\n // AsyncLocalStorage can keep an ended span reachable when work spawned\n // inside the span outlives it. Keep only the immutable span context and\n // primitive timing/identity fields needed by the Span API after end.\n this.name = ''\n this.attributes = {}\n this.events = []\n this.delegateSpan = undefined\n this.links = undefined\n this.requestIdentity = {}\n this.statusMessage = undefined\n this.exception = undefined\n }\n\n private getRecordError():\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (this.exception) {\n return this.exception\n }\n\n if (this.statusCode === SpanStatusCode.ERROR && this.statusMessage) {\n return {\n message: this.statusMessage,\n }\n }\n\n return undefined\n }\n}\n\nfunction getSpanStoreLinks(\n links: SpanOptions['links'] | undefined\n): SpanStoreLink[] | undefined {\n const spanStoreLinks = links?.map((link) => ({\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n attributes: cleanSpanStoreAttributes(link.attributes),\n }))\n\n return spanStoreLinks?.length ? spanStoreLinks : undefined\n}\n\nfunction cleanSpanStoreAttributes(\n attributes:\n | Record<string, AttributeValue | undefined>\n | SpanStoreAttributes\n | undefined\n): SpanStoreAttributes {\n const cleanedAttributes: SpanStoreAttributes = {}\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n cleanedAttributes[key] = value\n }\n }\n }\n return cleanedAttributes\n}\n\nfunction getTimestamp(time?: SpanOptions['startTime']): number {\n if (time instanceof Date) {\n return time.getTime()\n }\n\n if (Array.isArray(time)) {\n return time[0] * 1000 + time[1] / 1_000_000\n }\n\n if (typeof time === 'number') {\n const timeOrigin = getPerformanceTimeOrigin()\n return timeOrigin !== undefined && time < timeOrigin\n ? timeOrigin + time\n : time\n }\n\n const timeOrigin = getPerformanceTimeOrigin()\n return timeOrigin === undefined ? Date.now() : timeOrigin + performance.now()\n}\n\nfunction getPerformanceTimeOrigin(): number | undefined {\n return typeof performance !== 'undefined' &&\n typeof performance.timeOrigin === 'number'\n ? performance.timeOrigin\n : undefined\n}\n\nfunction getStringAttribute(\n attributes: SpanStoreAttributes | undefined,\n key: string\n): string | undefined {\n const value = attributes?.[key]\n return typeof value === 'string' ? value : undefined\n}\n\nfunction isSpanStoreAttributes(\n value: Parameters<Span['addEvent']>[1]\n): value is SpanStoreAttributes {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n )\n}\n\nfunction getSpanStoreException(\n exception: Parameters<Span['recordException']>[0]\n):\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (exception instanceof Error) {\n return {\n type: exception.name,\n message: exception.message,\n }\n }\n\n if (typeof exception === 'string') {\n return {\n message: exception,\n }\n }\n\n if (exception && typeof exception === 'object') {\n return {\n type: exception.constructor?.name,\n message: 'message' in exception ? String(exception.message) : undefined,\n }\n }\n\n return undefined\n}\n\nfunction getSpanStoreExceptionAttributes(\n exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n): SpanStoreAttributes | undefined {\n if (!exception) {\n return undefined\n }\n\n const attributes: SpanStoreAttributes = {}\n if (exception.type !== undefined) {\n attributes['exception.type'] = exception.type\n }\n if (exception.message !== undefined) {\n attributes['exception.message'] = exception.message\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined\n}\n\nfunction getCurrentRequestIdentity(): RequestIdentity {\n try {\n const { getRequestInsightsIdentity } =\n require('./request-insights-identity') as typeof import('./request-insights-identity')\n const { workAsyncStorage } =\n require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external')\n const { workUnitAsyncStorage } =\n require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external')\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n const requestInsightsIdentity = getRequestInsightsIdentity()\n const url =\n workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined\n\n return {\n requestId: workStore?.requestId ?? requestInsightsIdentity?.requestId,\n htmlRequestId:\n workStore?.htmlRequestId ?? requestInsightsIdentity?.htmlRequestId,\n route: workStore?.route,\n url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,\n }\n } catch {\n return {}\n }\n}\n"],"names":["createLocalSpan","getActiveLocalSpan","isLocalRecordingSpan","isLocalSpanRecordingEnabled","registerLocalSpanRecorder","withLocalSpan","TRACE_ID_HEX_LENGTH","SPAN_ID_HEX_LENGTH","lastLocalTraceId","lastLocalSpanId","localSpanAsyncStorage","getLocalTraceId","toString","padStart","getLocalSpanId","name","attributes","links","startTime","traceId","spanId","parentSpanId","delegateSpan","LocalRecordingSpan","requestIdentity","getCurrentRequestIdentity","getStore","span","fn","getLocalSpanAsyncStorage","run","key","Symbol","for","globalThis","isRequestInsightsEnabled","createAsyncLocalStorage","require","constructor","cleanSpanStoreAttributes","events","spanContextValue","spanContext","traceFlags","getSpanStoreLinks","getTimestamp","statusCode","undefined","statusMessage","exception","ended","setAttribute","value","setAttributes","Object","keys","addEvent","attributesOrStartTime","push","timestamp","Date","now","isSpanStoreAttributes","setStatus","status","code","message","updateName","end","endTime","record","releaseReferences","isRecording","recordException","time","getSpanStoreException","getSpanStoreExceptionAttributes","recordAttributes","length","recordSpan","durationMs","Math","max","SpanStatusCode","ERROR","requestId","htmlRequestId","route","getStringAttribute","url","error","getRecordError","spanStoreLinks","map","link","context","cleanedAttributes","getTime","Array","isArray","timeOrigin","getPerformanceTimeOrigin","performance","Error","type","String","getRequestInsightsIdentity","workAsyncStorage","workUnitAsyncStorage","workStore","workUnitStore","requestInsightsIdentity","pathname","search"],"mappings":";;;;;;;;;;;;;;;;;;;IAiCgBA,eAAe;eAAfA;;IAgCAC,kBAAkB;eAAlBA;;IAIAC,oBAAoB;eAApBA;;IArDPC,2BAA2B;eAA3BA,sCAA2B;;IAsEpBC,yBAAyB;eAAzBA;;IAbAC,aAAa;eAAbA;;;qBAnEe;2BAQxB;AAIP,MAAMC,sBAAsB;AAC5B,MAAMC,qBAAqB;AAI3B,IAAIC,mBAAmB;AACvB,IAAIC,kBAAkB;AACtB,IAAIC;AAEJ,MAAMC,kBAAkB,IACtB,AAAC,CAAA,EAAEH,gBAAe,EAAGI,QAAQ,CAAC,IAAIC,QAAQ,CAACP,qBAAqB;AAElE,MAAMQ,iBAAiB,IACrB,AAAC,CAAA,EAAEL,eAAc,EAAGG,QAAQ,CAAC,IAAIC,QAAQ,CAACN,oBAAoB;AAEzD,SAASP,gBAAgB,EAC9Be,IAAI,EACJC,UAAU,EACVC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,YAAY,EACZC,YAAY,EAUb;IACC,OAAO,IAAIC,mBAAmB;QAC5BR;QACAC;QACAC;QACAC;QACAI;QACAH,SAASA,WAAWR;QACpBS,QAAQA,UAAUN;QAClBO;QACAG,iBAAiBC;IACnB;AACF;AAEO,SAASxB;IACd,OAAOS,yCAAAA,sBAAuBgB,QAAQ;AACxC;AAEO,SAASxB,qBAAqByB,IAAU;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gBAAgBF,qBAAqBlF,QAAQ;QACnD,MAAMqF,0BAA0BL;QAChC,MAAMjB,MACJqB,iBAAiB,SAASA,gBAAgBA,cAAcrB,GAAG,GAAG1C;QAEhE,OAAO;YACLsC,WAAWwB,CAAAA,6BAAAA,UAAWxB,SAAS,MAAI0B,2CAAAA,wBAAyB1B,SAAS;YACrEC,eACEuB,CAAAA,6BAAAA,UAAWvB,aAAa,MAAIyB,2CAAAA,wBAAyBzB,aAAa;YACpEC,KAAK,EAAEsB,6BAAAA,UAAWtB,KAAK;YACvBE,KAAKA,MAAM,GAAGA,IAAIuB,QAAQ,GAAGvB,IAAIwB,MAAM,EAAE,GAAGF,2CAAAA,wBAAyBtB,GAAG;QAC1E;IACF,EAAE,OAAM;QACN,OAAO,CAAC;IACV;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/local-span-recorder.ts"],"sourcesContent":["import type {\n AttributeValue,\n Span,\n SpanOptions,\n} from 'next/dist/compiled/@opentelemetry/api'\nimport type { AsyncLocalStorage } from 'async_hooks'\nimport { SpanStatusCode } from 'next/dist/compiled/@opentelemetry/api'\nimport {\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n recordSpan,\n type SpanStoreAttributes,\n type SpanStoreEvent,\n type SpanStoreLink,\n} from './span-store'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport { isLocalSpanRecordingEnabled } from './span-store'\n\nconst TRACE_ID_HEX_LENGTH = 32\nconst SPAN_ID_HEX_LENGTH = 16\n\ntype LocalSpanAttributes = Partial<Record<string, AttributeValue | undefined>>\n\nlet lastLocalTraceId = 0\nlet lastLocalSpanId = 0\nlet localSpanAsyncStorage: AsyncLocalStorage<Span> | undefined\n\nconst getLocalTraceId = () =>\n (++lastLocalTraceId).toString(16).padStart(TRACE_ID_HEX_LENGTH, '0')\n\nconst getLocalSpanId = () =>\n (++lastLocalSpanId).toString(16).padStart(SPAN_ID_HEX_LENGTH, '0')\n\nexport function createLocalSpan({\n name,\n attributes,\n links,\n startTime,\n traceId,\n spanId,\n parentSpanId,\n delegateSpan,\n}: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n traceId?: string\n spanId?: string\n parentSpanId?: string\n delegateSpan?: Span\n}): Span {\n return new LocalRecordingSpan({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId: traceId ?? getLocalTraceId(),\n spanId: spanId ?? getLocalSpanId(),\n parentSpanId,\n requestIdentity: getCurrentRequestIdentity(),\n })\n}\n\nexport function getActiveLocalSpan(): Span | undefined {\n return localSpanAsyncStorage?.getStore()\n}\n\nexport function isLocalRecordingSpan(span: Span): boolean {\n return span instanceof LocalRecordingSpan\n}\n\nexport function withLocalSpan<T>(span: Span, fn: () => T): T {\n return getLocalSpanAsyncStorage().run(span, fn)\n}\n\nexport type LocalSpanRecorder = {\n createLocalSpan: typeof createLocalSpan\n getActiveLocalSpan: typeof getActiveLocalSpan\n isLocalRecordingSpan: typeof isLocalRecordingSpan\n isLocalSpanRecordingEnabled: typeof isLocalSpanRecordingEnabled\n isRequestInsightsEnabled: typeof isRequestInsightsEnabled\n withLocalSpan: typeof withLocalSpan\n}\n\nexport function registerLocalSpanRecorder(): void {\n const key = Symbol.for('@next/local-span-recorder')\n ;(\n globalThis as typeof globalThis & {\n [key]?: LocalSpanRecorder\n }\n )[key] = {\n createLocalSpan,\n getActiveLocalSpan,\n isLocalRecordingSpan,\n isLocalSpanRecordingEnabled,\n isRequestInsightsEnabled,\n withLocalSpan,\n }\n}\n\nfunction getLocalSpanAsyncStorage(): AsyncLocalStorage<Span> {\n if (!localSpanAsyncStorage) {\n const { createAsyncLocalStorage } =\n require('../../app-render/async-local-storage') as typeof import('../../app-render/async-local-storage')\n localSpanAsyncStorage = createAsyncLocalStorage()\n }\n\n return localSpanAsyncStorage\n}\n\ntype RequestIdentity = {\n requestId?: string\n requestInsightKind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nclass LocalRecordingSpan implements Span {\n public name: string\n\n private attributes: SpanStoreAttributes\n private events: SpanStoreEvent[]\n private readonly spanContextValue: ReturnType<Span['spanContext']>\n private delegateSpan?: Span\n private links?: SpanStoreLink[]\n private readonly parentSpanId?: string\n private requestIdentity: RequestIdentity\n private readonly startTime: number\n private statusCode: number | undefined\n private statusMessage: string | undefined\n private exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n private ended: boolean\n\n constructor({\n name,\n attributes,\n links,\n startTime,\n delegateSpan,\n traceId,\n spanId,\n parentSpanId,\n requestIdentity,\n }: {\n name: string\n attributes?: LocalSpanAttributes\n links?: SpanOptions['links']\n startTime?: SpanOptions['startTime']\n delegateSpan?: Span\n traceId: string\n spanId: string\n parentSpanId?: string\n requestIdentity: RequestIdentity\n }) {\n this.name = name\n this.attributes = cleanSpanStoreAttributes(attributes)\n this.events = []\n this.delegateSpan = delegateSpan\n this.spanContextValue = delegateSpan?.spanContext() ?? {\n traceId,\n spanId,\n traceFlags: 0,\n }\n this.links = getSpanStoreLinks(links)\n this.parentSpanId = parentSpanId\n this.requestIdentity = requestIdentity\n this.startTime = getTimestamp(startTime)\n this.statusCode = undefined\n this.statusMessage = undefined\n this.exception = undefined\n this.ended = false\n }\n\n spanContext(): ReturnType<Span['spanContext']> {\n return this.spanContextValue\n }\n\n setAttribute(key: string, value: AttributeValue): this {\n if (this.ended) {\n return this\n }\n\n this.attributes[key] = value\n this.delegateSpan?.setAttribute(key, value)\n return this\n }\n\n setAttributes(attributes: Parameters<Span['setAttributes']>[0]): this {\n if (this.ended) {\n return this\n }\n\n // OpenTelemetry attributes may be undefined. Ignore them instead of\n // overwriting an existing value as Object.assign would.\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n this.attributes[key] = value\n }\n }\n this.delegateSpan?.setAttributes(attributes)\n return this\n }\n\n addEvent(\n name: string,\n attributesOrStartTime?: Parameters<Span['addEvent']>[1],\n startTime?: Parameters<Span['addEvent']>[2]\n ): this {\n if (this.ended) {\n return this\n }\n\n const eventTime =\n startTime === undefined && isTimestampInput(attributesOrStartTime)\n ? attributesOrStartTime\n : startTime\n this.events.push({\n name,\n timestamp: getTimestamp(eventTime),\n attributes: isSpanStoreAttributes(attributesOrStartTime)\n ? cleanSpanStoreAttributes(attributesOrStartTime)\n : undefined,\n })\n this.delegateSpan?.addEvent(name, attributesOrStartTime, startTime)\n return this\n }\n\n setStatus(status: Parameters<Span['setStatus']>[0]): this {\n if (this.ended) {\n return this\n }\n\n this.statusCode = status.code\n this.statusMessage = status.message\n this.delegateSpan?.setStatus(status)\n return this\n }\n\n updateName(name: string): this {\n if (this.ended) {\n return this\n }\n\n this.name = name\n this.delegateSpan?.updateName(name)\n return this\n }\n\n end(endTime?: Parameters<Span['end']>[0]): void {\n if (this.ended) {\n return\n }\n\n this.ended = true\n try {\n this.delegateSpan?.end(endTime)\n } finally {\n try {\n this.record(endTime)\n } finally {\n this.releaseReferences()\n }\n }\n }\n\n isRecording(): boolean {\n return !this.ended\n }\n\n recordException(\n exception: Parameters<Span['recordException']>[0],\n time?: Parameters<Span['recordException']>[1]\n ): void {\n if (this.ended) {\n return\n }\n\n this.exception = getSpanStoreException(exception)\n this.events.push({\n name: 'exception',\n timestamp: getTimestamp(time),\n attributes: getSpanStoreExceptionAttributes(this.exception),\n })\n this.delegateSpan?.recordException(exception, time)\n }\n\n private record(endTime: Parameters<Span['end']>[0]): void {\n const recordAttributes =\n Object.keys(this.attributes).length > 0 ? this.attributes : undefined\n\n recordSpan({\n name: this.name,\n startTime: this.startTime,\n durationMs: Math.max(0, getTimestamp(endTime) - this.startTime),\n status: this.statusCode === SpanStatusCode.ERROR ? 'error' : 'ok',\n traceId: this.spanContextValue.traceId,\n spanId: this.spanContextValue.spanId,\n parentSpanId: this.parentSpanId,\n requestId: this.requestIdentity.requestId,\n requestInsightKind: this.requestIdentity.requestInsightKind,\n htmlRequestId: this.requestIdentity.htmlRequestId,\n route:\n getStringAttribute(recordAttributes, 'next.route') ??\n getStringAttribute(recordAttributes, 'http.route') ??\n this.requestIdentity.route,\n url:\n getStringAttribute(recordAttributes, 'http.url') ??\n this.requestIdentity.url,\n attributes: recordAttributes,\n links: this.links,\n events: this.events.length > 0 ? this.events : undefined,\n error: this.getRecordError(),\n })\n }\n\n private releaseReferences(): void {\n // AsyncLocalStorage can keep an ended span reachable when work spawned\n // inside the span outlives it. Keep only the immutable span context and\n // primitive timing/identity fields needed by the Span API after end.\n this.name = ''\n this.attributes = {}\n this.events = []\n this.delegateSpan = undefined\n this.links = undefined\n this.requestIdentity = {}\n this.statusMessage = undefined\n this.exception = undefined\n }\n\n private getRecordError():\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (this.exception) {\n return this.exception\n }\n\n if (this.statusCode === SpanStatusCode.ERROR && this.statusMessage) {\n return {\n message: this.statusMessage,\n }\n }\n\n return undefined\n }\n}\n\nfunction getSpanStoreLinks(\n links: SpanOptions['links'] | undefined\n): SpanStoreLink[] | undefined {\n const spanStoreLinks = links?.map((link) => ({\n traceId: link.context.traceId,\n spanId: link.context.spanId,\n attributes: cleanSpanStoreAttributes(link.attributes),\n }))\n\n return spanStoreLinks?.length ? spanStoreLinks : undefined\n}\n\nfunction cleanSpanStoreAttributes(\n attributes:\n | Record<string, AttributeValue | undefined>\n | SpanStoreAttributes\n | undefined\n): SpanStoreAttributes {\n const cleanedAttributes: SpanStoreAttributes = {}\n if (attributes) {\n for (const key of Object.keys(attributes)) {\n const value = attributes[key]\n if (value !== undefined) {\n cleanedAttributes[key] = value\n }\n }\n }\n return cleanedAttributes\n}\n\nfunction getTimestamp(time?: SpanOptions['startTime']): number {\n if (time instanceof Date) {\n return time.getTime()\n }\n\n if (Array.isArray(time)) {\n return time[0] * 1000 + time[1] / 1_000_000\n }\n\n if (typeof time === 'number') {\n return time < performance.timeOrigin / 2\n ? performance.timeOrigin + time\n : time\n }\n\n return performance.timeOrigin + performance.now()\n}\n\nfunction getStringAttribute(\n attributes: SpanStoreAttributes | undefined,\n key: string\n): string | undefined {\n const value = attributes?.[key]\n return typeof value === 'string' ? value : undefined\n}\n\nfunction isSpanStoreAttributes(\n value: Parameters<Span['addEvent']>[1]\n): value is SpanStoreAttributes {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n )\n}\n\nfunction isTimestampInput(\n value: Parameters<Span['addEvent']>[1]\n): value is SpanOptions['startTime'] {\n return (\n typeof value === 'number' || Array.isArray(value) || value instanceof Date\n )\n}\n\nfunction getSpanStoreException(\n exception: Parameters<Span['recordException']>[0]\n):\n | {\n type?: string\n message?: string\n }\n | undefined {\n if (exception instanceof Error) {\n return {\n type: exception.name,\n message: exception.message,\n }\n }\n\n if (typeof exception === 'string') {\n return {\n message: exception,\n }\n }\n\n if (exception && typeof exception === 'object') {\n return {\n type: exception.constructor?.name,\n message: 'message' in exception ? String(exception.message) : undefined,\n }\n }\n\n return undefined\n}\n\nfunction getSpanStoreExceptionAttributes(\n exception:\n | {\n type?: string\n message?: string\n }\n | undefined\n): SpanStoreAttributes | undefined {\n if (!exception) {\n return undefined\n }\n\n const attributes: SpanStoreAttributes = {}\n if (exception.type !== undefined) {\n attributes['exception.type'] = exception.type\n }\n if (exception.message !== undefined) {\n attributes['exception.message'] = exception.message\n }\n return Object.keys(attributes).length > 0 ? attributes : undefined\n}\n\nfunction getCurrentRequestIdentity(): RequestIdentity {\n try {\n const { getRequestInsightsIdentity } =\n require('./request-insights-identity') as typeof import('./request-insights-identity')\n const { workAsyncStorage } =\n require('../../app-render/work-async-storage.external') as typeof import('../../app-render/work-async-storage.external')\n const { workUnitAsyncStorage } =\n require('../../app-render/work-unit-async-storage.external') as typeof import('../../app-render/work-unit-async-storage.external')\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n const requestInsightsIdentity = getRequestInsightsIdentity()\n const url =\n workUnitStore && 'url' in workUnitStore ? workUnitStore.url : undefined\n\n return {\n requestId: requestInsightsIdentity?.requestId ?? workStore?.requestId,\n requestInsightKind: requestInsightsIdentity?.kind,\n htmlRequestId:\n requestInsightsIdentity?.htmlRequestId ?? workStore?.htmlRequestId,\n route: workStore?.route,\n url: url ? `${url.pathname}${url.search}` : requestInsightsIdentity?.url,\n }\n } catch {\n return {}\n }\n}\n"],"names":["createLocalSpan","getActiveLocalSpan","isLocalRecordingSpan","isLocalSpanRecordingEnabled","registerLocalSpanRecorder","withLocalSpan","TRACE_ID_HEX_LENGTH","SPAN_ID_HEX_LENGTH","lastLocalTraceId","lastLocalSpanId","localSpanAsyncStorage","getLocalTraceId","toString","padStart","getLocalSpanId","name","attributes","links","startTime","traceId","spanId","parentSpanId","delegateSpan","LocalRecordingSpan","requestIdentity","getCurrentRequestIdentity","getStore","span","fn","getLocalSpanAsyncStorage","run","key","Symbol","for","globalThis","isRequestInsightsEnabled","createAsyncLocalStorage","require","constructor","cleanSpanStoreAttributes","events","spanContextValue","spanContext","traceFlags","getSpanStoreLinks","getTimestamp","statusCode","undefined","statusMessage","exception","ended","setAttribute","value","setAttributes","Object","keys","addEvent","attributesOrStartTime","eventTime","isTimestampInput","push","timestamp","isSpanStoreAttributes","setStatus","status","code","message","updateName","end","endTime","record","releaseReferences","isRecording","recordException","time","getSpanStoreException","getSpanStoreExceptionAttributes","recordAttributes","length","recordSpan","durationMs","Math","max","SpanStatusCode","ERROR","requestId","requestInsightKind","htmlRequestId","route","getStringAttribute","url","error","getRecordError","spanStoreLinks","map","link","context","cleanedAttributes","Date","getTime","Array","isArray","performance","timeOrigin","now","Error","type","String","getRequestInsightsIdentity","workAsyncStorage","workUnitAsyncStorage","workStore","workUnitStore","requestInsightsIdentity","kind","pathname","search"],"mappings":";;;;;;;;;;;;;;;;;;;IAkCgBA,eAAe;eAAfA;;IAgCAC,kBAAkB;eAAlBA;;IAIAC,oBAAoB;eAApBA;;IArDPC,2BAA2B;eAA3BA,sCAA2B;;IAsEpBC,yBAAyB;eAAzBA;;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wBAAyBvB,GAAG;QAC1E;IACF,EAAE,OAAM;QACN,OAAO,CAAC;IACV;AACF","ignoreList":[0]} |
@@ -0,3 +1,5 @@ | ||
| import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'; | ||
| export type RequestInsightsIdentity = { | ||
| requestId: string; | ||
| kind?: RequestInsightKind; | ||
| htmlRequestId: string; | ||
@@ -4,0 +6,0 @@ url: string | undefined; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/request-insights-identity.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport { createAsyncLocalStorage } from '../../app-render/async-local-storage'\n\nexport type RequestInsightsIdentity = {\n requestId: string\n htmlRequestId: string\n url: string | undefined\n}\n\n// This storage covers the part of BaseServer request handling that runs before\n// App Render creates workAsyncStorage. Once available, workStore remains the\n// primary identity source for locally recorded spans.\nconst REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY = Symbol.for(\n '@next/request-insights-identity-storage'\n)\n\nfunction getRequestInsightsIdentityStorage(): AsyncLocalStorage<RequestInsightsIdentity> {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY]?: AsyncLocalStorage<RequestInsightsIdentity>\n }\n\n return (globalStore[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY] ??=\n createAsyncLocalStorage())\n}\n\nexport function runWithRequestInsightsIdentity<T>(\n identity: RequestInsightsIdentity,\n fn: () => T\n): T {\n return getRequestInsightsIdentityStorage().run(identity, fn)\n}\n\nexport function getRequestInsightsIdentity():\n | RequestInsightsIdentity\n | undefined {\n return getRequestInsightsIdentityStorage().getStore()\n}\n"],"names":["getRequestInsightsIdentity","runWithRequestInsightsIdentity","REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY","Symbol","for","getRequestInsightsIdentityStorage","globalStore","globalThis","createAsyncLocalStorage","identity","fn","run","getStore"],"mappings":";;;;;;;;;;;;;;;IAgCgBA,0BAA0B;eAA1BA;;IAPAC,8BAA8B;eAA9BA;;;mCAxBwB;AAQxC,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,MAAMC,wCAAwCC,OAAOC,GAAG,CACtD;AAGF,SAASC;IACP,MAAMC,cAAcC;IAIpB,OAAQD,WAAW,CAACJ,sCAAsC,KACxDM,IAAAA,0CAAuB;AAC3B;AAEO,SAASP,+BACdQ,QAAiC,EACjCC,EAAW;IAEX,OAAOL,oCAAoCM,GAAG,CAACF,UAAUC;AAC3D;AAEO,SAASV;IAGd,OAAOK,oCAAoCO,QAAQ;AACrD","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/request-insights-identity.ts"],"sourcesContent":["import type { AsyncLocalStorage } from 'async_hooks'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\nimport { createAsyncLocalStorage } from '../../app-render/async-local-storage'\n\nexport type RequestInsightsIdentity = {\n requestId: string\n kind?: RequestInsightKind\n htmlRequestId: string\n url: string | undefined\n}\n\n// This storage covers the part of BaseServer request handling that runs before\n// App Render creates workAsyncStorage. Once available, workStore remains the\n// primary identity source for locally recorded spans.\nconst REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY = Symbol.for(\n '@next/request-insights-identity-storage'\n)\n\nfunction getRequestInsightsIdentityStorage(): AsyncLocalStorage<RequestInsightsIdentity> {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY]?: AsyncLocalStorage<RequestInsightsIdentity>\n }\n\n return (globalStore[REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY] ??=\n createAsyncLocalStorage())\n}\n\nexport function runWithRequestInsightsIdentity<T>(\n identity: RequestInsightsIdentity,\n fn: () => T\n): T {\n return getRequestInsightsIdentityStorage().run(identity, fn)\n}\n\nexport function getRequestInsightsIdentity():\n | RequestInsightsIdentity\n | undefined {\n return getRequestInsightsIdentityStorage().getStore()\n}\n"],"names":["getRequestInsightsIdentity","runWithRequestInsightsIdentity","REQUEST_INSIGHTS_IDENTITY_STORAGE_KEY","Symbol","for","getRequestInsightsIdentityStorage","globalStore","globalThis","createAsyncLocalStorage","identity","fn","run","getStore"],"mappings":";;;;;;;;;;;;;;;IAkCgBA,0BAA0B;eAA1BA;;IAPAC,8BAA8B;eAA9BA;;;mCAzBwB;AASxC,+EAA+E;AAC/E,6EAA6E;AAC7E,sDAAsD;AACtD,MAAMC,wCAAwCC,OAAOC,GAAG,CACtD;AAGF,SAASC;IACP,MAAMC,cAAcC;IAIpB,OAAQD,WAAW,CAACJ,sCAAsC,KACxDM,IAAAA,0CAAuB;AAC3B;AAEO,SAASP,+BACdQ,QAAiC,EACjCC,EAAW;IAEX,OAAOL,oCAAoCM,GAAG,CAACF,UAAUC;AAC3D;AAEO,SAASV;IAGd,OAAOK,oCAAoCO,QAAQ;AACrD","ignoreList":[0]} |
| import type { RequestInsight, RequestInsightFetch, RequestInsightsSnapshot } from '../../../next-devtools/shared/request-insights'; | ||
| import type { RequestInsightKind } from '../../../shared/lib/request-insights'; | ||
| import type { SpanStoreRecord } from './span-store'; | ||
@@ -7,2 +8,3 @@ export { isRequestInsightsEnabled } from './span-store'; | ||
| requestId?: string; | ||
| kind?: RequestInsightKind; | ||
| htmlRequestId?: string; | ||
@@ -9,0 +11,0 @@ route?: string; |
@@ -39,2 +39,3 @@ "use strict"; | ||
| }); | ||
| const _requestinsights = require("../../../shared/lib/request-insights"); | ||
| const _spanstore = require("./span-store"); | ||
@@ -69,3 +70,9 @@ const MAX_REQUEST_INSIGHTS = 100; | ||
| } | ||
| const insight = this.getOrCreateRequest(span, span.startTime ?? span.timestamp); | ||
| const insight = this.getOrCreateRequest({ | ||
| requestId: span.requestId, | ||
| kind: span.requestInsightKind, | ||
| htmlRequestId: span.htmlRequestId, | ||
| route: span.route, | ||
| url: span.url | ||
| }, span.startTime ?? span.timestamp); | ||
| const spanStartTime = span.startTime ?? span.timestamp; | ||
@@ -100,3 +107,3 @@ insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId; | ||
| } | ||
| const fetchStartTime = fetch.startTime ?? Date.now(); | ||
| const fetchStartTime = fetch.startTime ?? getCurrentTimestamp(); | ||
| const insight = this.getOrCreateRequest(identity, fetchStartTime); | ||
@@ -109,3 +116,3 @@ this.updateTiming(insight, fetchStartTime, fetch.durationMs, false); | ||
| return { | ||
| requests: this.requestOrder.map((requestId)=>this.requests.get(requestId)).filter((request)=>request !== undefined) | ||
| requests: this.requestOrder.map((insightKey)=>this.requests.get(insightKey)).filter((request)=>request !== undefined) | ||
| }; | ||
@@ -125,2 +132,3 @@ } | ||
| updateTiming(insight, startTime, durationMs, isRequestSpan) { | ||
| const insightKey = (0, _requestinsights.getRequestInsightKey)(insight); | ||
| if (isRequestSpan && durationMs !== undefined) { | ||
@@ -131,3 +139,3 @@ const requestTiming = { | ||
| }; | ||
| this.requestTimings.set(insight.requestId, requestTiming); | ||
| this.requestTimings.set(insightKey, requestTiming); | ||
| insight.startTime = requestTiming.startTime; | ||
@@ -137,3 +145,3 @@ insight.durationMs = requestTiming.durationMs; | ||
| } | ||
| const requestTiming = this.requestTimings.get(insight.requestId); | ||
| const requestTiming = this.requestTimings.get(insightKey); | ||
| if (requestTiming) { | ||
@@ -156,6 +164,11 @@ insight.startTime = requestTiming.startTime; | ||
| const requestId = identity.requestId; | ||
| let insight = this.requests.get(requestId); | ||
| const insightKey = (0, _requestinsights.getRequestInsightKey)({ | ||
| requestId, | ||
| kind: identity.kind | ||
| }); | ||
| let insight = this.requests.get(insightKey); | ||
| if (!insight) { | ||
| insight = { | ||
| requestId, | ||
| kind: (0, _requestinsights.getRequestInsightKind)(identity), | ||
| htmlRequestId: identity.htmlRequestId ?? requestId, | ||
@@ -169,4 +182,4 @@ route: identity.route, | ||
| }; | ||
| this.requests.set(requestId, insight); | ||
| this.requestOrder.push(requestId); | ||
| this.requests.set(insightKey, insight); | ||
| this.requestOrder.push(insightKey); | ||
| this.trim(); | ||
@@ -188,6 +201,6 @@ } | ||
| while(this.requestOrder.length > MAX_REQUEST_INSIGHTS){ | ||
| const requestId = this.requestOrder.shift(); | ||
| if (requestId) { | ||
| this.requests.delete(requestId); | ||
| this.requestTimings.delete(requestId); | ||
| const insightKey = this.requestOrder.shift(); | ||
| if (insightKey) { | ||
| this.requests.delete(insightKey); | ||
| this.requestTimings.delete(insightKey); | ||
| } | ||
@@ -248,2 +261,5 @@ } | ||
| } | ||
| function getCurrentTimestamp() { | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
| function sanitizeSpanAttributes(attributes) { | ||
@@ -250,0 +266,0 @@ if (!attributes) { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/request-insights.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type {\n RequestInsight,\n RequestInsightFetch,\n RequestInsightsSnapshot,\n} from '../../../next-devtools/shared/request-insights'\nimport type { SpanStoreRecord } from './span-store'\nexport { isRequestInsightsEnabled } from './span-store'\n\nconst MAX_REQUEST_INSIGHTS = 100\nconst REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')\nconst CLIENT_COMPONENT_LOADING_SPAN_TYPE =\n 'NextNodeServer.clientComponentLoading'\n\ntype RequestInsightsListener = (insight: RequestInsight) => void\ntype RequestInsightIdentity = {\n requestId?: string\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nconst REDACTED_VALUE = 'redacted'\nconst SAFE_SPAN_ATTRIBUTE_KEYS = new Set([\n 'http.method',\n 'http.route',\n 'http.status_code',\n 'http.url',\n 'net.peer.name',\n 'net.peer.port',\n 'next.fetch.cache_reason',\n 'next.fetch.cache_status',\n 'next.fetch.idx',\n 'next.route',\n 'next.rsc',\n 'next.segment',\n 'next.span_category',\n 'next.span_name',\n 'next.span_type',\n])\nconst SENSITIVE_PARAM_NAME_RE =\n /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i\n\nclass InMemoryRequestInsightsStore {\n private readonly requests = new Map<string, RequestInsight>()\n private readonly requestTimings = new Map<\n string,\n { startTime: number; durationMs: number }\n >()\n private readonly requestOrder: string[] = []\n private readonly listeners = new Set<RequestInsightsListener>()\n\n recordSpan(span: SpanStoreRecord): void {\n if (!span.requestId) {\n return\n }\n\n const insight = this.getOrCreateRequest(\n span,\n span.startTime ?? span.timestamp\n )\n\n const spanStartTime = span.startTime ?? span.timestamp\n insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? span.route\n insight.url = insight.url ?? sanitizeUrl(span.url)\n this.updateTiming(\n insight,\n spanStartTime,\n span.durationMs,\n span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'\n )\n insight.status =\n insight.status === 'error' || span.status === 'error'\n ? 'error'\n : span.status === 'ok'\n ? 'ok'\n : insight.status\n\n insight.spans.push({\n name: span.name,\n startTime: spanStartTime,\n durationMs: span.durationMs,\n status: span.status,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n attributes: sanitizeSpanAttributes(span.attributes),\n links: sanitizeSpanLinks(span.links),\n events: sanitizeSpanEvents(span.events),\n error: span.error,\n })\n\n const fetch = getFetchInsight(span)\n if (fetch) {\n this.recordFetchForInsight(insight, fetch)\n }\n\n this.notify(insight)\n }\n\n recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {\n if (!identity.requestId) {\n return\n }\n\n const fetchStartTime = fetch.startTime ?? Date.now()\n const insight = this.getOrCreateRequest(identity, fetchStartTime)\n this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)\n this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))\n this.notify(insight)\n }\n\n getSnapshot(): RequestInsightsSnapshot {\n return {\n requests: this.requestOrder\n .map((requestId) => this.requests.get(requestId))\n .filter((request): request is RequestInsight => request !== undefined),\n }\n }\n\n subscribe(listener: RequestInsightsListener): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n clear(): void {\n this.requests.clear()\n this.requestTimings.clear()\n this.requestOrder.length = 0\n }\n\n private updateTiming(\n insight: RequestInsight,\n startTime: number,\n durationMs: number | undefined,\n isRequestSpan: boolean\n ): void {\n if (isRequestSpan && durationMs !== undefined) {\n const requestTiming = { startTime, durationMs }\n this.requestTimings.set(insight.requestId, requestTiming)\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const requestTiming = this.requestTimings.get(insight.requestId)\n if (requestTiming) {\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const endTime = startTime + (durationMs ?? 0)\n const requestEndTime = insight.startTime + (insight.durationMs ?? 0)\n insight.startTime = Math.min(insight.startTime, startTime)\n insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime\n }\n\n private notify(insight: RequestInsight): void {\n for (const listener of this.listeners) {\n listener(insight)\n }\n }\n\n private getOrCreateRequest(\n identity: RequestInsightIdentity,\n startTime: number\n ): RequestInsight {\n const requestId = identity.requestId!\n let insight = this.requests.get(requestId)\n\n if (!insight) {\n insight = {\n requestId,\n htmlRequestId: identity.htmlRequestId ?? requestId,\n route: identity.route,\n url: sanitizeUrl(identity.url),\n startTime,\n status: 'pending',\n spans: [],\n fetches: [],\n }\n this.requests.set(requestId, insight)\n this.requestOrder.push(requestId)\n this.trim()\n }\n\n insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? identity.route\n insight.url = insight.url ?? sanitizeUrl(identity.url)\n insight.startTime = Math.min(insight.startTime, startTime)\n\n return insight\n }\n\n private recordFetchForInsight(\n insight: RequestInsight,\n fetch: RequestInsightFetch\n ): void {\n if (\n insight.fetches.some(\n (existingFetch) =>\n existingFetch.url === fetch.url &&\n (existingFetch.index !== undefined && fetch.index !== undefined\n ? existingFetch.index === fetch.index\n : existingFetch.startTime === fetch.startTime)\n )\n ) {\n return\n }\n\n insight.fetches.push(sanitizeFetchInsight(fetch))\n }\n\n private trim(): void {\n while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {\n const requestId = this.requestOrder.shift()\n if (requestId) {\n this.requests.delete(requestId)\n this.requestTimings.delete(requestId)\n }\n }\n }\n}\n\nexport function recordRequestInsightSpan(span: SpanStoreRecord): void {\n if (\n span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE\n ) {\n return\n }\n\n getRequestInsightsStore().recordSpan(span)\n}\n\nexport function recordRequestInsightFetch(\n identity: RequestInsightIdentity,\n fetch: RequestInsightFetch\n): void {\n getRequestInsightsStore().recordFetch(identity, fetch)\n}\n\nexport function getRequestInsightsSnapshot(): RequestInsightsSnapshot {\n return getRequestInsightsStore().getSnapshot()\n}\n\nexport function subscribeRequestInsights(\n listener: RequestInsightsListener\n): () => void {\n return getRequestInsightsStore().subscribe(listener)\n}\n\nexport function clearRequestInsightsForTest(): void {\n getRequestInsightsStore().clear()\n}\n\nfunction getRequestInsightsStore(): InMemoryRequestInsightsStore {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore\n }\n\n return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=\n new InMemoryRequestInsightsStore())\n}\n\nfunction getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {\n const attributes = span.attributes\n\n if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {\n return null\n }\n\n return {\n url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),\n method: getStringAttribute(attributes['http.method']),\n statusCode: getNumberAttribute(attributes['http.status_code']),\n startTime: span.startTime ?? span.timestamp,\n durationMs: span.durationMs,\n cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),\n cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),\n index: getNumberAttribute(attributes['next.fetch.idx']),\n }\n}\n\nfunction sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {\n return {\n ...fetch,\n url: sanitizeUrl(fetch.url),\n }\n}\n\nfunction sanitizeSpanAttributes(\n attributes: SpanStoreRecord['attributes']\n): SpanStoreRecord['attributes'] {\n if (!attributes) {\n return undefined\n }\n\n const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {\n continue\n }\n\n sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value\n }\n\n return Object.keys(sanitized).length > 0 ? sanitized : undefined\n}\n\nfunction sanitizeSpanEvents(\n events: SpanStoreRecord['events']\n): SpanStoreRecord['events'] {\n return events?.map((event) => ({\n ...event,\n attributes: sanitizeSpanAttributes(event.attributes),\n }))\n}\n\nfunction sanitizeSpanLinks(\n links: SpanStoreRecord['links']\n): SpanStoreRecord['links'] {\n return links?.map((link) => ({\n ...link,\n attributes: sanitizeSpanAttributes(link.attributes),\n }))\n}\n\nfunction sanitizeUrlAttribute(value: AttributeValue): AttributeValue {\n return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value\n}\n\nfunction sanitizeUrl(value: string | undefined): string | undefined {\n if (!value) {\n return value\n }\n\n const isRelativeUrl = value.startsWith('/')\n\n try {\n const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)\n\n url.username = ''\n url.password = ''\n\n for (const name of Array.from(url.searchParams.keys())) {\n if (SENSITIVE_PARAM_NAME_RE.test(name)) {\n url.searchParams.set(name, REDACTED_VALUE)\n }\n }\n\n return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href\n } catch {\n return value\n }\n}\n\nfunction getStringAttribute(value: AttributeValue | undefined) {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction getNumberAttribute(value: AttributeValue | undefined) {\n return typeof value === 'number' ? value : undefined\n}\n"],"names":["clearRequestInsightsForTest","getRequestInsightsSnapshot","isRequestInsightsEnabled","recordRequestInsightFetch","recordRequestInsightSpan","subscribeRequestInsights","MAX_REQUEST_INSIGHTS","REQUEST_INSIGHTS_STORE_KEY","Symbol","for","CLIENT_COMPONENT_LOADING_SPAN_TYPE","REDACTED_VALUE","SAFE_SPAN_ATTRIBUTE_KEYS","Set","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","requestId","insight","getOrCreateRequest","startTime","timestamp","spanStartTime","htmlRequestId","route","url","sanitizeUrl","updateTiming","durationMs","attributes","status","spans","push","name","traceId","spanId","parentSpanId","sanitizeSpanAttributes","links","sanitizeSpanLinks","events","sanitizeSpanEvents","error","fetch","getFetchInsight","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","Date","now","sanitizeFetchInsight","getSnapshot","requests","requestOrder","map","get","filter","request","undefined","subscribe","listener","listeners","add","delete","clear","requestTimings","length","isRequestSpan","requestTiming","set","endTime","requestEndTime","Math","min","max","fetches","trim","some","existingFetch","index","shift","Map","getRequestInsightsStore","globalStore","globalThis","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","sanitized","key","value","Object","entries","has","sanitizeUrlAttribute","keys","event","link","isRelativeUrl","startsWith","URL","username","password","Array","from","searchParams","test","pathname","search","hash","href"],"mappings":";;;;;;;;;;;;;;;;;;;IA+PgBA,2BAA2B;eAA3BA;;IAVAC,0BAA0B;eAA1BA;;IA9OPC,wBAAwB;eAAxBA,mCAAwB;;IAuOjBC,yBAAyB;eAAzBA;;IAVAC,wBAAwB;eAAxBA;;IAqBAC,wBAAwB;eAAxBA;;;2BAlPyB;AAEzC,MAAMC,uBAAuB;AAC7B,MAAMC,6BAA6BC,OAAOC,GAAG,CAAC;AAC9C,MAAMC,qCACJ;AAUF,MAAMC,iBAAiB;AACvB,MAAMC,2BAA2B,IAAIC,IAAI;IACvC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMC,0BACJ;AAEF,MAAMC;IASJC,WAAWC,IAAq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ACrD,CAAA;AACF;AAEA,SAASU,kBACPD,KAA+B;IAE/B,OAAOA,yBAAAA,MAAOkB,GAAG,CAAC,CAAC8C,OAAU,CAAA;YAC3B,GAAGA,IAAI;YACPzE,YAAYQ,uBAAuBiE,KAAKzE,UAAU;QACpD,CAAA;AACF;AAEA,SAASsE,qBAAqBJ,KAAqB;IACjD,OAAO,OAAOA,UAAU,WAAYrE,YAAYqE,UAAU,KAAMA;AAClE;AAEA,SAASrE,YAAYqE,KAAyB;IAC5C,IAAI,CAACA,OAAO;QACV,OAAOA;IACT;IAEA,MAAMQ,gBAAgBR,MAAMS,UAAU,CAAC;IAEvC,IAAI;QACF,MAAM/E,MAAM8E,gBAAgB,IAAIE,IAAIV,OAAO,cAAc,IAAIU,IAAIV;QAEjEtE,IAAIiF,QAAQ,GAAG;QACfjF,IAAIkF,QAAQ,GAAG;QAEf,KAAK,MAAM1E,QAAQ2E,MAAMC,IAAI,CAACpF,IAAIqF,YAAY,CAACV,IAAI,IAAK;YACtD,IAAIvF,wBAAwBkG,IAAI,CAAC9E,OAAO;gBACtCR,IAAIqF,YAAY,CAACvC,GAAG,CAACtC,MAAMvB;YAC7B;QACF;QAEA,OAAO6F,gBAAgB,GAAG9E,IAAIuF,QAAQ,GAAGvF,IAAIwF,MAAM,GAAGxF,IAAIyF,IAAI,EAAE,GAAGzF,IAAI0F,IAAI;IAC7E,EAAE,OAAM;QACN,OAAOpB;IACT;AACF;AAEA,SAASR,mBAAmBQ,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQnC;AAC7C;AAEA,SAAS8B,mBAAmBK,KAAiC;IAC3D,OAAO,OAAOA,UAAU,WAAWA,QAAQnC;AAC7C","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/request-insights.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type {\n RequestInsight,\n RequestInsightFetch,\n RequestInsightsSnapshot,\n} from '../../../next-devtools/shared/request-insights'\nimport type { RequestInsightKind } from '../../../shared/lib/request-insights'\nimport {\n getRequestInsightKey,\n getRequestInsightKind,\n} from '../../../shared/lib/request-insights'\nimport type { SpanStoreRecord } from './span-store'\nexport { isRequestInsightsEnabled } from './span-store'\n\nconst MAX_REQUEST_INSIGHTS = 100\nconst REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')\nconst CLIENT_COMPONENT_LOADING_SPAN_TYPE =\n 'NextNodeServer.clientComponentLoading'\n\ntype RequestInsightsListener = (insight: RequestInsight) => void\ntype RequestInsightIdentity = {\n requestId?: string\n kind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n}\n\nconst REDACTED_VALUE = 'redacted'\nconst SAFE_SPAN_ATTRIBUTE_KEYS = new Set([\n 'http.method',\n 'http.route',\n 'http.status_code',\n 'http.url',\n 'net.peer.name',\n 'net.peer.port',\n 'next.fetch.cache_reason',\n 'next.fetch.cache_status',\n 'next.fetch.idx',\n 'next.route',\n 'next.rsc',\n 'next.segment',\n 'next.span_category',\n 'next.span_name',\n 'next.span_type',\n])\nconst SENSITIVE_PARAM_NAME_RE =\n /(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i\n\nclass InMemoryRequestInsightsStore {\n private readonly requests = new Map<string, RequestInsight>()\n private readonly requestTimings = new Map<\n string,\n { startTime: number; durationMs: number }\n >()\n private readonly requestOrder: string[] = []\n private readonly listeners = new Set<RequestInsightsListener>()\n\n recordSpan(span: SpanStoreRecord): void {\n if (!span.requestId) {\n return\n }\n\n const insight = this.getOrCreateRequest(\n {\n requestId: span.requestId,\n kind: span.requestInsightKind,\n htmlRequestId: span.htmlRequestId,\n route: span.route,\n url: span.url,\n },\n span.startTime ?? span.timestamp\n )\n\n const spanStartTime = span.startTime ?? span.timestamp\n insight.htmlRequestId = span.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? span.route\n insight.url = insight.url ?? sanitizeUrl(span.url)\n this.updateTiming(\n insight,\n spanStartTime,\n span.durationMs,\n span.attributes?.['next.span_type'] === 'BaseServer.handleRequest'\n )\n insight.status =\n insight.status === 'error' || span.status === 'error'\n ? 'error'\n : span.status === 'ok'\n ? 'ok'\n : insight.status\n\n insight.spans.push({\n name: span.name,\n startTime: spanStartTime,\n durationMs: span.durationMs,\n status: span.status,\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n attributes: sanitizeSpanAttributes(span.attributes),\n links: sanitizeSpanLinks(span.links),\n events: sanitizeSpanEvents(span.events),\n error: span.error,\n })\n\n const fetch = getFetchInsight(span)\n if (fetch) {\n this.recordFetchForInsight(insight, fetch)\n }\n\n this.notify(insight)\n }\n\n recordFetch(identity: RequestInsightIdentity, fetch: RequestInsightFetch) {\n if (!identity.requestId) {\n return\n }\n\n const fetchStartTime = fetch.startTime ?? getCurrentTimestamp()\n const insight = this.getOrCreateRequest(identity, fetchStartTime)\n this.updateTiming(insight, fetchStartTime, fetch.durationMs, false)\n this.recordFetchForInsight(insight, sanitizeFetchInsight(fetch))\n this.notify(insight)\n }\n\n getSnapshot(): RequestInsightsSnapshot {\n return {\n requests: this.requestOrder\n .map((insightKey) => this.requests.get(insightKey))\n .filter((request): request is RequestInsight => request !== undefined),\n }\n }\n\n subscribe(listener: RequestInsightsListener): () => void {\n this.listeners.add(listener)\n return () => {\n this.listeners.delete(listener)\n }\n }\n\n clear(): void {\n this.requests.clear()\n this.requestTimings.clear()\n this.requestOrder.length = 0\n }\n\n private updateTiming(\n insight: RequestInsight,\n startTime: number,\n durationMs: number | undefined,\n isRequestSpan: boolean\n ): void {\n const insightKey = getRequestInsightKey(insight)\n if (isRequestSpan && durationMs !== undefined) {\n const requestTiming = { startTime, durationMs }\n this.requestTimings.set(insightKey, requestTiming)\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const requestTiming = this.requestTimings.get(insightKey)\n if (requestTiming) {\n insight.startTime = requestTiming.startTime\n insight.durationMs = requestTiming.durationMs\n return\n }\n\n const endTime = startTime + (durationMs ?? 0)\n const requestEndTime = insight.startTime + (insight.durationMs ?? 0)\n insight.startTime = Math.min(insight.startTime, startTime)\n insight.durationMs = Math.max(requestEndTime, endTime) - insight.startTime\n }\n\n private notify(insight: RequestInsight): void {\n for (const listener of this.listeners) {\n listener(insight)\n }\n }\n\n private getOrCreateRequest(\n identity: RequestInsightIdentity,\n startTime: number\n ): RequestInsight {\n const requestId = identity.requestId!\n const insightKey = getRequestInsightKey({\n requestId,\n kind: identity.kind,\n })\n let insight = this.requests.get(insightKey)\n\n if (!insight) {\n insight = {\n requestId,\n kind: getRequestInsightKind(identity),\n htmlRequestId: identity.htmlRequestId ?? requestId,\n route: identity.route,\n url: sanitizeUrl(identity.url),\n startTime,\n status: 'pending',\n spans: [],\n fetches: [],\n }\n this.requests.set(insightKey, insight)\n this.requestOrder.push(insightKey)\n this.trim()\n }\n\n insight.htmlRequestId = identity.htmlRequestId ?? insight.htmlRequestId\n insight.route = insight.route ?? identity.route\n insight.url = insight.url ?? sanitizeUrl(identity.url)\n insight.startTime = Math.min(insight.startTime, startTime)\n\n return insight\n }\n\n private recordFetchForInsight(\n insight: RequestInsight,\n fetch: RequestInsightFetch\n ): void {\n if (\n insight.fetches.some(\n (existingFetch) =>\n existingFetch.url === fetch.url &&\n (existingFetch.index !== undefined && fetch.index !== undefined\n ? existingFetch.index === fetch.index\n : existingFetch.startTime === fetch.startTime)\n )\n ) {\n return\n }\n\n insight.fetches.push(sanitizeFetchInsight(fetch))\n }\n\n private trim(): void {\n while (this.requestOrder.length > MAX_REQUEST_INSIGHTS) {\n const insightKey = this.requestOrder.shift()\n if (insightKey) {\n this.requests.delete(insightKey)\n this.requestTimings.delete(insightKey)\n }\n }\n }\n}\n\nexport function recordRequestInsightSpan(span: SpanStoreRecord): void {\n if (\n span.attributes?.['next.span_type'] === CLIENT_COMPONENT_LOADING_SPAN_TYPE\n ) {\n return\n }\n\n getRequestInsightsStore().recordSpan(span)\n}\n\nexport function recordRequestInsightFetch(\n identity: RequestInsightIdentity,\n fetch: RequestInsightFetch\n): void {\n getRequestInsightsStore().recordFetch(identity, fetch)\n}\n\nexport function getRequestInsightsSnapshot(): RequestInsightsSnapshot {\n return getRequestInsightsStore().getSnapshot()\n}\n\nexport function subscribeRequestInsights(\n listener: RequestInsightsListener\n): () => void {\n return getRequestInsightsStore().subscribe(listener)\n}\n\nexport function clearRequestInsightsForTest(): void {\n getRequestInsightsStore().clear()\n}\n\nfunction getRequestInsightsStore(): InMemoryRequestInsightsStore {\n const globalStore = globalThis as typeof globalThis & {\n [REQUEST_INSIGHTS_STORE_KEY]?: InMemoryRequestInsightsStore\n }\n\n return (globalStore[REQUEST_INSIGHTS_STORE_KEY] ??=\n new InMemoryRequestInsightsStore())\n}\n\nfunction getFetchInsight(span: SpanStoreRecord): RequestInsightFetch | null {\n const attributes = span.attributes\n\n if (!attributes || attributes['next.span_type'] !== 'AppRender.fetch') {\n return null\n }\n\n return {\n url: sanitizeUrl(getStringAttribute(attributes['http.url']) ?? span.url),\n method: getStringAttribute(attributes['http.method']),\n statusCode: getNumberAttribute(attributes['http.status_code']),\n startTime: span.startTime ?? span.timestamp,\n durationMs: span.durationMs,\n cacheStatus: getStringAttribute(attributes['next.fetch.cache_status']),\n cacheReason: getStringAttribute(attributes['next.fetch.cache_reason']),\n index: getNumberAttribute(attributes['next.fetch.idx']),\n }\n}\n\nfunction sanitizeFetchInsight(fetch: RequestInsightFetch): RequestInsightFetch {\n return {\n ...fetch,\n url: sanitizeUrl(fetch.url),\n }\n}\n\nfunction getCurrentTimestamp(): number {\n return performance.timeOrigin + performance.now()\n}\n\nfunction sanitizeSpanAttributes(\n attributes: SpanStoreRecord['attributes']\n): SpanStoreRecord['attributes'] {\n if (!attributes) {\n return undefined\n }\n\n const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}\n for (const [key, value] of Object.entries(attributes)) {\n if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {\n continue\n }\n\n sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value\n }\n\n return Object.keys(sanitized).length > 0 ? sanitized : undefined\n}\n\nfunction sanitizeSpanEvents(\n events: SpanStoreRecord['events']\n): SpanStoreRecord['events'] {\n return events?.map((event) => ({\n ...event,\n attributes: sanitizeSpanAttributes(event.attributes),\n }))\n}\n\nfunction sanitizeSpanLinks(\n links: SpanStoreRecord['links']\n): SpanStoreRecord['links'] {\n return links?.map((link) => ({\n ...link,\n attributes: sanitizeSpanAttributes(link.attributes),\n }))\n}\n\nfunction sanitizeUrlAttribute(value: AttributeValue): AttributeValue {\n return typeof value === 'string' ? (sanitizeUrl(value) ?? '') : value\n}\n\nfunction sanitizeUrl(value: string | undefined): string | undefined {\n if (!value) {\n return value\n }\n\n const isRelativeUrl = value.startsWith('/')\n\n try {\n const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)\n\n url.username = ''\n url.password = ''\n\n for (const name of Array.from(url.searchParams.keys())) {\n if (SENSITIVE_PARAM_NAME_RE.test(name)) {\n url.searchParams.set(name, REDACTED_VALUE)\n }\n }\n\n return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href\n } catch {\n return value\n }\n}\n\nfunction getStringAttribute(value: AttributeValue | undefined) {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction getNumberAttribute(value: AttributeValue | undefined) {\n return typeof value === 'number' ? value : undefined\n}\n"],"names":["clearRequestInsightsForTest","getRequestInsightsSnapshot","isRequestInsightsEnabled","recordRequestInsightFetch","recordRequestInsightSpan","subscribeRequestInsights","MAX_REQUEST_INSIGHTS","REQUEST_INSIGHTS_STORE_KEY","Symbol","for","CLIENT_COMPONENT_LOADING_SPAN_TYPE","REDACTED_VALUE","SAFE_SPAN_ATTRIBUTE_KEYS","Set","SENSITIVE_PARAM_NAME_RE","InMemoryRequestInsightsStore","recordSpan","span","requestId","insight","getOrCreateRequest","kind","requestInsightKind","htmlRequestId","route","url","startTime","timestamp","spanStartTime","sanitizeUrl","updateTiming","durationMs","attributes","status","spans","push","name","traceId","spanId","parentSpanId","sanitizeSpanAttributes","links","sanitizeSpanLinks","events","sanitizeSpanEvents","error","fetch","getFetchInsight","recordFetchForInsight","notify","recordFetch","identity","fetchStartTime","getCurrentTimestamp","sanitizeFetchInsight","getSnapshot","requests","requestOrder","map","insightKey","get","filter","request","undefined","subscribe","listener","listeners","add","delete","clear","requestTimings","length","isRequestSpan","getRequestInsightKey","requestTiming","set","endTime","requestEndTime","Math","min","max","getRequestInsightKind","fetches","trim","some","existingFetch","index","shift","Map","getRequestInsightsStore","globalStore","globalThis","getStringAttribute","method","statusCode","getNumberAttribute","cacheStatus","cacheReason","performance","timeOrigin","now","sanitized","key","value","Object","entries","has","sanitizeUrlAttribute","keys","event","link","isRelativeUrl","startsWith","URL","username","password","Array","from","searchParams","test","pathname","search","hash","href"],"mappings":";;;;;;;;;;;;;;;;;;;IAiRgBA,2BAA2B;eAA3BA;;IAVAC,0BAA0B;eAA1BA;;IA3PPC,wBAAwB;eAAxBA,mCAAwB;;IAoPjBC,yBAAyB;eAAzBA;;IAVAC,wBAAwB;eAAxBA;;IAqBAC,wBAAwB;eAAxBA;;;iCAjQT;2BAEkC;AAEzC,MAAMC,uBAAuB;AAC7B,MAAMC,6BAA6BC,OAAOC,GAAG,CAAC;AAC9C,MAAMC,qCACJ;AAWF,MAAMC,iBAAiB;AACvB,MAAMC,2BAA2B,IAAIC,IAAI;IACvC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMC,0BACJ;AAEF,MAAMC;IASJC,WAAWC,IAAqB,EAAQ;YAwBpCA;QAvBF,IAAI,CAACA,KAAKC,SAAS,EAAE;YACnB;QACF;QAEA,MAAMC,UAAU,IAAI,CAACC,kBAAkB,CACrC;YACEF,WAAWD,KAAKC,SAAS;YACzBG,MAAMJ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ignoreList":[0]} |
| import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'; | ||
| import type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'; | ||
| export type SpanStoreAttributes = Record<string, AttributeValue>; | ||
@@ -23,2 +24,3 @@ export type SpanStoreLink = { | ||
| requestId?: string; | ||
| requestInsightKind?: RequestInsightKind; | ||
| htmlRequestId?: string; | ||
@@ -25,0 +27,0 @@ route?: string; |
@@ -37,3 +37,3 @@ "use strict"; | ||
| const spanRecord = { | ||
| timestamp: Date.now(), | ||
| timestamp: getCurrentTimestamp(), | ||
| ...record | ||
@@ -66,3 +66,6 @@ }; | ||
| } | ||
| function getCurrentTimestamp() { | ||
| return performance.timeOrigin + performance.now(); | ||
| } | ||
| //# sourceMappingURL=span-store.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/span-store.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\n\nexport type SpanStoreAttributes = Record<string, AttributeValue>\n\nexport type SpanStoreLink = {\n traceId: string\n spanId: string\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreEvent = {\n name: string\n timestamp: number\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreRecord = {\n name: string\n timestamp: number\n startTime?: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n requestId?: string\n htmlRequestId?: string\n route?: string\n url?: string\n attributes?: SpanStoreAttributes\n links?: SpanStoreLink[]\n events?: SpanStoreEvent[]\n error?: {\n type?: string\n message?: string\n }\n}\n\ntype SpanRecorderForTest = (span: SpanStoreRecord) => void\n\nlet spanRecorderForTest: SpanRecorderForTest | undefined\n\nexport function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {\n if (!isLocalSpanRecordingEnabled()) {\n return\n }\n\n const spanRecord: SpanStoreRecord = {\n timestamp: Date.now(),\n ...record,\n }\n\n spanRecorderForTest?.(spanRecord)\n\n if (isRequestInsightsEnabled() && spanRecord.requestId) {\n const { recordRequestInsightSpan } =\n require('./request-insights') as typeof import('./request-insights')\n recordRequestInsightSpan(spanRecord)\n }\n}\n\nexport function setSpanRecorderForTest(\n recorder: SpanRecorderForTest | undefined\n): void {\n spanRecorderForTest = recorder\n}\n\nexport function isLocalSpanRecordingEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n return spanRecorderForTest !== undefined || isRequestInsightsEnabled()\n}\n\nexport function isRequestInsightsEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n const value = process.env.__NEXT_REQUEST_INSIGHTS\n return isEnabledEnvValue(value)\n}\n\nfunction isEnabledEnvValue(value: string | undefined): boolean {\n return value === '1' || value === 'true' || (value as unknown) === true\n}\n"],"names":["isLocalSpanRecordingEnabled","isRequestInsightsEnabled","recordSpan","setSpanRecorderForTest","spanRecorderForTest","record","spanRecord","timestamp","Date","now","requestId","recordRequestInsightSpan","require","recorder","process","env","__NEXT_DEV_SERVER","undefined","value","__NEXT_REQUEST_INSIGHTS","isEnabledEnvValue"],"mappings":";;;;;;;;;;;;;;;;;IAmEgBA,2BAA2B;eAA3BA;;IAQAC,wBAAwB;eAAxBA;;IAjCAC,UAAU;eAAVA;;IAmBAC,sBAAsB;eAAtBA;;;AArBhB,IAAIC;AAEG,SAASF,WAAWG,MAA0C;IACnE,IAAI,CAACL,+BAA+B;QAClC;IACF;IAEA,MAAMM,aAA8B;QAClCC,WAAWC,KAAKC,GAAG;QACnB,GAAGJ,MAAM;IACX;IAEAD,uCAAAA,oBAAsBE;IAEtB,IAAIL,8BAA8BK,WAAWI,SAAS,EAAE;QACtD,MAAM,EAAEC,wBAAwB,EAAE,GAChCC,QAAQ;QACVD,yBAAyBL;IAC3B;AACF;AAEO,SAASH,uBACdU,QAAyC;IAEzCT,sBAAsBS;AACxB;AAEO,SAASb;IACd,IAAI,CAACc,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,OAAOZ,wBAAwBa,aAAahB;AAC9C;AAEO,SAASA;IACd,IAAI,CAACa,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,MAAME,QAAQJ,QAAQC,GAAG,CAACI,uBAAuB;IACjD,OAAOC,kBAAkBF;AAC3B;AAEA,SAASE,kBAAkBF,KAAyB;IAClD,OAAOA,UAAU,OAAOA,UAAU,UAAU,AAACA,UAAsB;AACrE","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../../src/server/lib/trace/span-store.ts"],"sourcesContent":["import type { AttributeValue } from 'next/dist/compiled/@opentelemetry/api'\nimport type { RequestInsightKind } from '../../../next-devtools/shared/request-insights'\n\nexport type SpanStoreAttributes = Record<string, AttributeValue>\n\nexport type SpanStoreLink = {\n traceId: string\n spanId: string\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreEvent = {\n name: string\n timestamp: number\n attributes?: SpanStoreAttributes\n}\n\nexport type SpanStoreRecord = {\n name: string\n timestamp: number\n startTime?: number\n durationMs?: number\n status?: 'ok' | 'error'\n traceId?: string\n spanId?: string\n parentSpanId?: string\n requestId?: string\n requestInsightKind?: RequestInsightKind\n htmlRequestId?: string\n route?: string\n url?: string\n attributes?: SpanStoreAttributes\n links?: SpanStoreLink[]\n events?: SpanStoreEvent[]\n error?: {\n type?: string\n message?: string\n }\n}\n\ntype SpanRecorderForTest = (span: SpanStoreRecord) => void\n\nlet spanRecorderForTest: SpanRecorderForTest | undefined\n\nexport function recordSpan(record: Omit<SpanStoreRecord, 'timestamp'>): void {\n if (!isLocalSpanRecordingEnabled()) {\n return\n }\n\n const spanRecord: SpanStoreRecord = {\n timestamp: getCurrentTimestamp(),\n ...record,\n }\n\n spanRecorderForTest?.(spanRecord)\n\n if (isRequestInsightsEnabled() && spanRecord.requestId) {\n const { recordRequestInsightSpan } =\n require('./request-insights') as typeof import('./request-insights')\n recordRequestInsightSpan(spanRecord)\n }\n}\n\nexport function setSpanRecorderForTest(\n recorder: SpanRecorderForTest | undefined\n): void {\n spanRecorderForTest = recorder\n}\n\nexport function isLocalSpanRecordingEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n return spanRecorderForTest !== undefined || isRequestInsightsEnabled()\n}\n\nexport function isRequestInsightsEnabled(): boolean {\n if (!process.env.__NEXT_DEV_SERVER) {\n return false\n }\n\n const value = process.env.__NEXT_REQUEST_INSIGHTS\n return isEnabledEnvValue(value)\n}\n\nfunction isEnabledEnvValue(value: string | undefined): boolean {\n return value === '1' || value === 'true' || (value as unknown) === true\n}\n\nfunction getCurrentTimestamp(): number {\n return performance.timeOrigin + performance.now()\n}\n"],"names":["isLocalSpanRecordingEnabled","isRequestInsightsEnabled","recordSpan","setSpanRecorderForTest","spanRecorderForTest","record","spanRecord","timestamp","getCurrentTimestamp","requestId","recordRequestInsightSpan","require","recorder","process","env","__NEXT_DEV_SERVER","undefined","value","__NEXT_REQUEST_INSIGHTS","isEnabledEnvValue","performance","timeOrigin","now"],"mappings":";;;;;;;;;;;;;;;;;IAqEgBA,2BAA2B;eAA3BA;;IAQAC,wBAAwB;eAAxBA;;IAjCAC,UAAU;eAAVA;;IAmBAC,sBAAsB;eAAtBA;;;AArBhB,IAAIC;AAEG,SAASF,WAAWG,MAA0C;IACnE,IAAI,CAACL,+BAA+B;QAClC;IACF;IAEA,MAAMM,aAA8B;QAClCC,WAAWC;QACX,GAAGH,MAAM;IACX;IAEAD,uCAAAA,oBAAsBE;IAEtB,IAAIL,8BAA8BK,WAAWG,SAAS,EAAE;QACtD,MAAM,EAAEC,wBAAwB,EAAE,GAChCC,QAAQ;QACVD,yBAAyBJ;IAC3B;AACF;AAEO,SAASH,uBACdS,QAAyC;IAEzCR,sBAAsBQ;AACxB;AAEO,SAASZ;IACd,IAAI,CAACa,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,OAAOX,wBAAwBY,aAAaf;AAC9C;AAEO,SAASA;IACd,IAAI,CAACY,QAAQC,GAAG,CAACC,iBAAiB,EAAE;QAClC,OAAO;IACT;IAEA,MAAME,QAAQJ,QAAQC,GAAG,CAACI,uBAAuB;IACjD,OAAOC,kBAAkBF;AAC3B;AAEA,SAASE,kBAAkBF,KAAyB;IAClD,OAAOA,UAAU,OAAOA,UAAU,UAAU,AAACA,UAAsB;AACrE;AAEA,SAAST;IACP,OAAOY,YAAYC,UAAU,GAAGD,YAAYE,GAAG;AACjD","ignoreList":[0]} |
@@ -151,3 +151,8 @@ "use strict"; | ||
| // budget then classifies the route as dynamic. | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(renderSignal, workStore.route, 'dynamic `ImageResponse`'); | ||
| // Whatever dynamic input made the element partial already classified | ||
| // itself when it created its own hanging promise (cookies() creates a | ||
| // runtime hanging promise, an uncached fetch creates a dynamic one, | ||
| // ...), so this wrapper adds no new information and can use the | ||
| // non-recording dynamic variant. | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(renderSignal, workStore.route, 'dynamic `ImageResponse`'); | ||
| } | ||
@@ -154,0 +159,0 @@ // The serialization finished before any dynamic input was needed, so we |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n return makeHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["getCachedImageResponseBody","importOgModule","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","workAsyncStorage","InvariantError","element","options","hangingInputAbortSignal","createHangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","getClientReferenceManifest","prelude","prerenderToNodeStream","signal","filterStackFrame","onError","error","makeHangingPromise","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","createHash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","createFromNodeStream","Readable","from","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":";;;;+BA+CgBA;;;eAAAA;;;4BA/CS;4BACa;gCAEP;0CACE;8CACI;kCACS;uCACX;oCAI5B;wBAE+B;wBAED;AAMrC,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAoBO,SAASD,2BACdE,IAAuB;IAEvB,OAAO,IAAIC,eAA2B;QACpC,MAAMC,OAAMC,UAAU;YACpB,MAAMC,cAAc,MAAMC,kCAAkCL;YAC5D,IAAII,YAAYE,UAAU,GAAG,GAAG;gBAC9BH,WAAWI,OAAO,CAAC,IAAIC,WAAWJ;YACpC;YACAD,WAAWM,KAAK;QAClB;IACF;AACF;AAEA,eAAeJ,kCACbL,IAAuB;IAEvB,MAAMU,gBAAgBC,kDAAoB,CAACC,QAAQ;IAEnD,OAAQF,iCAAAA,cAAeG,IAAI;QACzB,KAAK;YAGH;QACF,KAAKC;Q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AAM,CAAC,GAAG6C,MAAMC,MAAM/F,UAAU,CAAC,CAAC,CAAC;IACxC+C,KAAKE,MAAM,CAAC8C;AACd;AAEA,eAAetF,+BACbf,IAAuB;IAEvB,MAAMsG,kBAAkB,AAAC,CAAA,MAAMvG,gBAAe,EAAGwG,aAAa;IAC9D,MAAMC,gBAAgB,IAAIF,mBAAmBtG;IAE7C,IAAI,CAACwG,cAAcC,IAAI,EAAE;QACvB,OAAO,IAAIxB,YAAY;IACzB;IAEA,OAAOuB,cAAcpG,WAAW;AAClC;AAEA,MAAMsG,kBAAkBC,OAAOC,GAAG,CAAC;AAEnC;;;;;;CAMC,GACD,SAASpC,oBAAoBqC,IAAa;IACxC,IAAIA,SAAS,QAAQ,OAAOA,SAAS,UAAU;QAC7C,OAAOA;IACT;IAEA,IAAI,AAACA,KAA+BC,QAAQ,KAAKJ,iBAAiB;QAChE,MAAMK,OAAOF;QAIb,OAAOrC,oBAAoBuC,KAAKC,KAAK,CAACD,KAAKE,QAAQ;IACrD;IAEA,IAAI5B,MAAMC,OAAO,CAACuB,OAAO;QACvB,OAAOA,KAAKK,GAAG,CAAC1C;IAClB;IAEA,MAAMlD,UAAUuF;IAChB,IAAIvF,QAAQ6F,KAAK,IAAI,cAAc7F,QAAQ6F,KAAK,EAAE;QAChD,OAAO;YACL,GAAG7F,OAAO;YACV6F,OAAO;gBACL,GAAG7F,QAAQ6F,KAAK;gBAChBC,UAAU5C,oBAAoBlD,QAAQ6F,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/og/cache-image-response.ts"],"sourcesContent":["import { Readable } from 'node:stream'\nimport { createHash, type Hash } from 'node:crypto'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { createHangingInputAbortSignal } from '../app-render/dynamic-rendering'\nimport { makeDynamicHangingPromise } from '../dynamic-rendering-utils'\nimport {\n getClientReferenceManifest,\n getServerModuleMap,\n} from '../app-render/manifests-singleton'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { prerenderToNodeStream } from 'react-server-dom-webpack/static'\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { createFromNodeStream } from 'react-server-dom-webpack/client'\n\ntype OgModule = typeof import('next/dist/compiled/@vercel/og')\n\ntype ImageResponseArgs = ConstructorParameters<OgModule['ImageResponse']>\n\nfunction importOgModule(): Promise<OgModule> {\n // Cache Components is Node-only (rejected for the edge runtime at compile\n // time), so we always load the Node build. Loading it dynamically keeps the\n // heavy `@vercel/og` renderer (satori + WASM) off the module-load path, so\n // it's pulled in only when an image is actually rendered.\n return import('next/dist/compiled/@vercel/og/index.node.js')\n}\n\n/**\n * Builds the body for a Cache Components `ImageResponse`. The rendered image is\n * cached in the Resume Data Cache during a prerender, so the prospective\n * prerender renders it once and the final prerender retrieves it from memory\n * within microtasks. This lets metadata image routes be statically prerendered\n * under Cache Components instead of being treated as dynamic.\n *\n * The cache boundary is drawn around only the deterministic rasterization of\n * the element tree into an image. The `ImageResponse` element tree is rendered\n * with React Flight once, inside the prerender work-unit store, so any\n * user-space I/O (e.g. `cookies()` or an uncached `fetch`) runs in the correct\n * scope and is subject to the normal Cache Components rules. If that tree\n * needs dynamic input the serialization can't complete, and the route falls\n * back to dynamic. Otherwise the fully resolved tree is handed to satori,\n * which never re-runs the user's components.\n *\n * Outside of a prerender (normal requests) this just renders.\n */\nexport function getCachedImageResponseBody(\n args: ImageResponseArgs\n): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const arrayBuffer = await getCachedImageResponseArrayBuffer(args)\n if (arrayBuffer.byteLength > 0) {\n controller.enqueue(new Uint8Array(arrayBuffer))\n }\n controller.close()\n },\n })\n}\n\nasync function getCachedImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n switch (workUnitStore?.type) {\n case 'prerender':\n // We only cache during a prerender. Metadata image routes compile to\n // route handlers, which use the `prerender` store.\n break\n case undefined:\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'prerender-runtime':\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'generate-static-params':\n return renderImageResponseArrayBuffer(args)\n default:\n return workUnitStore satisfies never\n }\n\n const { cacheSignal, resumeDataCache, renderSignal } = workUnitStore\n\n if (!resumeDataCache) {\n return renderImageResponseArrayBuffer(args)\n }\n\n const workStore = workAsyncStorage.getStore()\n\n if (!workStore) {\n throw new InvariantError(\n 'Expected a work store while caching an `ImageResponse` during prerendering.'\n )\n }\n\n const [element, options] = args\n\n // `createHangingInputAbortSignal` aborts once the prerender's cache-sourced\n // input is ready, so anything the serialization below is still awaiting past\n // that point can be treated as dynamic (non-cache) input. In the prospective\n // pass it aborts when `cacheSignal.inputReady()` resolves (no cache reads\n // in progress); in the final pass the caches are already filled, so it just\n // aborts on the next tick.\n const hangingInputAbortSignal = createHangingInputAbortSignal(workUnitStore)\n\n // We open the cache read lazily, once we know the serialization completed and\n // we're about to render and store the image. Opening it before serializing\n // would keep `cacheSignal.inputReady()` from resolving and thus prevent the\n // abort signal from ever firing, deadlocking the prospective prerender.\n let readState: 'ready' | 'pending' | 'done' = 'ready'\n\n function beginReadOnce() {\n if (readState === 'ready') {\n readState = 'pending'\n cacheSignal?.beginRead()\n }\n }\n\n function endReadIfStarted() {\n if (readState === 'pending') {\n cacheSignal?.endRead()\n }\n readState = 'done'\n }\n\n // We serialize the element tree with `prerenderToNodeStream` rather than\n // `renderToPipeableStream`. It's the right fit for prerendering, and it\n // schedules work deferred for size (`deferTask`) on microtasks, so a fully\n // static tree finishes flushing before the abort signal fires; a tree still\n // pending at abort time is then genuinely waiting on dynamic input rather\n // than just deferred.\n //\n // `renderToPipeableStream` would schedule that deferred work on\n // `setImmediate` instead, which isn't necessarily a deal-breaker: the\n // sequential-task scheme page rendering uses (`runInSequentialTasks`) drains\n // pending immediates at each task boundary, so deferred work still runs in\n // time. But route handler prerendering doesn't use that scheme, so here the\n // deferred immediates would race the abort.\n //\n // The prerender halts silently on abort, leaving unfulfilled references in\n // place rather than reporting through `onError`. So to tell a halt (the tree\n // needed dynamic input) apart from a normal completion, we record whether the\n // abort fired before the serialization finished. `abort()` runs this listener\n // synchronously, well before we read `resultIsPartial` below.\n let prerenderCompleted = false\n let resultIsPartial = false\n let serializationError: unknown\n\n hangingInputAbortSignal.addEventListener(\n 'abort',\n () => {\n if (!prerenderCompleted) {\n resultIsPartial = true\n }\n },\n { once: true }\n )\n\n const { clientModules, rscModuleMapping } = getClientReferenceManifest()\n\n try {\n // We serialize only the `element`. It's the part that needs Flight, to run\n // its async Server Components once and to surface any dynamic input. The\n // `options` are already-resolved plain data; they're folded into the cache\n // key directly and passed to satori as-is below.\n const { prelude } = await prerenderToNodeStream(element, clientModules, {\n signal: hangingInputAbortSignal,\n filterStackFrame: undefined,\n onError(error) {\n // A halt (our deliberate abort) emits nothing, so this is only called\n // for genuine serialization errors. We surface the first one.\n if (serializationError === undefined && !resultIsPartial) {\n serializationError = error\n }\n },\n })\n\n prerenderCompleted = true\n\n if (serializationError !== undefined) {\n throw serializationError\n }\n\n if (resultIsPartial) {\n // The element tree needed dynamic input (e.g. `cookies()` or an uncached\n // `fetch`), so the image can't be produced statically. Return a hanging\n // promise: the body never resolves, and the final prerender's macrotask\n // budget then classifies the route as dynamic.\n // Whatever dynamic input made the element partial already classified\n // itself when it created its own hanging promise (cookies() creates a\n // runtime hanging promise, an uncached fetch creates a dynamic one,\n // ...), so this wrapper adds no new information and can use the\n // non-recording dynamic variant.\n return makeDynamicHangingPromise<ArrayBuffer>(\n renderSignal,\n workStore.route,\n 'dynamic `ImageResponse`'\n )\n }\n\n // The serialization finished before any dynamic input was needed, so we\n // will render and cache the image. Hold the cache read now, before the\n // stream is buffered and deserialized below, so that the prospective\n // prerender's `cacheReady()` waits for the image to be stored.\n beginReadOnce()\n\n const chunks: Buffer[] = []\n for await (const chunk of prelude) {\n chunks.push(chunk)\n }\n\n const elementBuffer = Buffer.concat(chunks)\n\n // Derive a stable cache key from the serialized element plus the options.\n // We hash rather than reuse the raw serialized bytes so the key stays\n // compact even for large inputs (e.g. embedded fonts), and we fold the\n // options in by content so two images that differ only in their options\n // (size, fonts, ...) don't collide. The options are hashed directly here,\n // never serialized through Flight, which would both bloat the key and apply\n // `Buffer.prototype .toJSON` to font data.\n const hash = createHash('sha256')\n hash.update(elementBuffer)\n updateHashWithOptions(hash, options)\n const cacheKey = hash.digest('base64')\n\n const cached = resumeDataCache.imageResponses.get(cacheKey)\n\n if (cached) {\n return await cached\n }\n\n // Deserialize the element and hand it to satori. Because the user's\n // components already ran during serialization, satori only walks resolved\n // host elements and never re-runs them, confining user-space I/O to the\n // in-store serialization above.\n const deserializedElement = await createFromNodeStream(\n Readable.from([elementBuffer]),\n {\n // We don't want to trigger preloads of client references here.\n moduleLoading: null,\n moduleMap: rscModuleMapping,\n serverModuleMap: getServerModuleMap(),\n },\n { findSourceMapURL: undefined }\n )\n\n // The Flight client hands back the output of an async Server Component as\n // a `React.lazy` (sync components and plain host elements are inlined).\n // satori can't unwrap lazies, so we resolve them into plain elements first.\n // We only reach here once the serialization completed, so every lazy is\n // already resolved and `_init` returns synchronously.\n const resolvedElement = resolveFlightLazies(deserializedElement)\n\n // Pair the resolved element with the original, in-memory `options`, which\n // never went through Flight. This keeps the font `Buffer` intact: had it\n // been serialized, Flight would apply the `toJSON` method that Node's\n // `Buffer` carries, turning it into a `{ type: 'Buffer', data: [...] }`\n // object that satori's font parser rejects (it needs an `ArrayBuffer` or a\n // typed array).\n const resolvedArgs = [resolvedElement, options] as ImageResponseArgs\n\n // Render satori outside the prerender work-unit store. It does uncached\n // `fetch` calls (e.g. loading a font), and inside a Cache Components\n // prerender an uncached `fetch` outside a cache scope becomes a hanging\n // promise. Those are framework fetches, not user I/O, so we let them\n // resolve normally with no store.\n const arrayBufferPromise = workUnitAsyncStorage.exit(() =>\n renderImageResponseArrayBuffer(resolvedArgs)\n )\n\n if (resumeDataCache.mutable) {\n resumeDataCache.imageResponses.set(cacheKey, arrayBufferPromise)\n }\n\n return await arrayBufferPromise\n } finally {\n endReadIfStarted()\n }\n}\n\n/**\n * Updates a hash with a stable encoding of the `ImageResponse` options so they\n * can participate in the cache key without being serialized through Flight.\n * Binary values (font `Buffer`s, `ArrayBuffer`s, typed arrays) are hashed by\n * their raw bytes; objects are walked in sorted-key order.\n *\n * `ImageResponse` options are plain data: numbers, strings, booleans, nested\n * plain objects/arrays, and binary font data. Exotic objects such as `Map` or\n * `Date` keep their state outside their enumerable own keys, so the key walk\n * below would hash them incorrectly. Options never contain these, but we warn\n * if one ever shows up so a mis-keyed cache can be reported.\n *\n * The encoding is self-delimiting: every node starts with a type tag, and\n * variable-length parts (byte runs, primitives, keys) are length-prefixed,\n * while arrays and objects are count-prefixed. This makes it injective, so no\n * concatenation of values can be mistaken for a differently shaped input.\n */\nfunction updateHashWithOptions(hash: Hash, value: unknown): void {\n if (value === undefined) {\n hash.update('u')\n return\n }\n\n if (value === null) {\n hash.update('n')\n return\n }\n\n const type = typeof value\n\n if (type !== 'object') {\n // Tag with the primitive type so e.g. the number `1` and the string `'1'`\n // don't hash the same.\n updateHashWithBytes(hash, 'p', Buffer.from(`${type}:${String(value)}`))\n return\n }\n\n if (value instanceof ArrayBuffer) {\n updateHashWithBytes(hash, 'a', new Uint8Array(value))\n return\n }\n\n if (ArrayBuffer.isView(value)) {\n updateHashWithBytes(\n hash,\n 'v',\n new Uint8Array(value.buffer, value.byteOffset, value.byteLength)\n )\n return\n }\n\n if (Array.isArray(value)) {\n hash.update(`[${value.length},`)\n for (const item of value) {\n updateHashWithOptions(hash, item)\n }\n return\n }\n\n // The key walk below captures a plain object faithfully, but an exotic object\n // keeps its state elsewhere (a `Map`'s/`Set`'s entries, a `Date`'s time), so\n // two different values would hash the same and could return the wrong cached\n // image. This shouldn't happen for `ImageResponse` options, so we warn rather\n // than fail, then hash best-effort, so it can be reported. Not gated on\n // `NODE_ENV`: this runs during the production `next build` prerender, where\n // the warning is most useful.\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n const typeName =\n (value as { constructor?: { name?: string } }).constructor?.name ??\n 'object'\n console.warn(\n `Cannot reliably include an \\`ImageResponse\\` option of type ` +\n `\\`${typeName}\\` in the cache key, so different images may collide and ` +\n `return an incorrect cached result. Please report this to the Next.js ` +\n `team.`\n )\n }\n\n const keys = Object.keys(value).sort()\n hash.update(`{${keys.length},`)\n for (const key of keys) {\n updateHashWithBytes(hash, 'k', Buffer.from(key))\n updateHashWithOptions(hash, (value as Record<string, unknown>)[key])\n }\n}\n\n/**\n * Hashes a length-prefixed, tagged byte run: `<tag><byteLength>:<bytes>`. The\n * length prefix keeps the run self-delimiting so it can't blend into adjacent\n * nodes.\n */\nfunction updateHashWithBytes(hash: Hash, tag: string, bytes: Uint8Array): void {\n hash.update(`${tag}${bytes.byteLength}:`)\n hash.update(bytes)\n}\n\nasync function renderImageResponseArrayBuffer(\n args: ImageResponseArgs\n): Promise<ArrayBuffer> {\n const OGImageResponse = (await importOgModule()).ImageResponse\n const imageResponse = new OGImageResponse(...args)\n\n if (!imageResponse.body) {\n return new ArrayBuffer(0)\n }\n\n return imageResponse.arrayBuffer()\n}\n\nconst REACT_LAZY_TYPE = Symbol.for('react.lazy')\n\n/**\n * Recursively replaces the `React.lazy` references that Flight emits for\n * resolved async Server Components with the elements they resolve to, so that\n * satori (which doesn't understand lazy nodes) can walk the tree. This must\n * only be called on a fully resolved (completed) Flight result, where each\n * lazy's `_init` returns synchronously rather than suspending.\n */\nfunction resolveFlightLazies(node: unknown): unknown {\n if (node === null || typeof node !== 'object') {\n return node\n }\n\n if ((node as { $$typeof?: symbol }).$$typeof === REACT_LAZY_TYPE) {\n const lazy = node as {\n _init: (payload: unknown) => unknown\n _payload: unknown\n }\n return resolveFlightLazies(lazy._init(lazy._payload))\n }\n\n if (Array.isArray(node)) {\n return node.map(resolveFlightLazies)\n }\n\n const element = node as { props?: { children?: unknown } }\n if (element.props && 'children' in element.props) {\n return {\n ...element,\n props: {\n ...element.props,\n children: resolveFlightLazies(element.props.children),\n },\n }\n }\n\n return node\n}\n"],"names":["getCachedImageResponseBody","importOgModule","args","ReadableStream","start","controller","arrayBuffer","getCachedImageResponseArrayBuffer","byteLength","enqueue","Uint8Array","close","workUnitStore","workUnitAsyncStorage","getStore","type","undefined","renderImageResponseArrayBuffer","cacheSignal","resumeDataCache","renderSignal","workStore","workAsyncStorage","InvariantError","element","options","hangingInputAbortSignal","createHangingInputAbortSignal","readState","beginReadOnce","beginRead","endReadIfStarted","endRead","prerenderCompleted","resultIsPartial","serializationError","addEventListener","once","clientModules","rscModuleMapping","getClientReferenceManifest","prelude","prerenderToNodeStream","signal","filterStackFrame","onError","error","makeDynamicHangingPromise","route","chunks","chunk","push","elementBuffer","Buffer","concat","hash","createHash","update","updateHashWithOptions","cacheKey","digest","cached","imageResponses","get","deserializedElement","createFromNodeStream","Readable","from","moduleLoading","moduleMap","serverModuleMap","getServerModuleMap","findSourceMapURL","resolvedElement","resolveFlightLazies","resolvedArgs","arrayBufferPromise","exit","mutable","set","value","updateHashWithBytes","String","ArrayBuffer","isView","buffer","byteOffset","Array","isArray","length","item","prototype","Object","getPrototypeOf","typeName","constructor","name","console","warn","keys","sort","key","tag","bytes","OGImageResponse","ImageResponse","imageResponse","body","REACT_LAZY_TYPE","Symbol","for","node","$$typeof","lazy","_init","_payload","map","props","children"],"mappings":";;;;+BA+CgBA;;;eAAAA;;;4BA/CS;4BACa;gCAEP;0CACE;8CACI;kCACS;uCACJ;oCAInC;wBAE+B;wBAED;AAMrC,SAASC;IACP,0EAA0E;IAC1E,4EAA4E;IAC5E,2EAA2E;IAC3E,0DAA0D;IAC1D,OAAO,MAAM,CAAC;AAChB;AAo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AAQ6F,KAAK,EAAE;QAChD,OAAO;YACL,GAAG7F,OAAO;YACV6F,OAAO;gBACL,GAAG7F,QAAQ6F,KAAK;gBAChBC,UAAU5C,oBAAoBlD,QAAQ6F,KAAK,CAACC,QAAQ;YACtD;QACF;IACF;IAEA,OAAOP;AACT","ignoreList":[0]} |
@@ -89,3 +89,3 @@ "use strict"; | ||
| // stall at this point. | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, '`connection()`'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`connection()`'); | ||
| case 'validation-client': | ||
@@ -92,0 +92,0 @@ { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-ppr':\n // We use React's postpone API to interrupt rendering here to create a\n // dynamic hole\n return postponeWithTracking(\n workStore.route,\n 'connection',\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["connection","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeHangingPromise","renderSignal","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","throwForMissingRequestStore"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;0CAzBiB;8CAI1B;kCAKA;yCAC+B;uCAI/B;uBAC2C;iCAEtB;gCACG;AAOxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,wVAAwV,CAAC,GAD9W,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,sEAAsE;YACtE,+CAA+C;YAC/C,OAAOC,QAAQC,OAAO,CAACC;QACzB;QAEA,IAAIX,UAAUY,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEb,UAAUO,KAAK,CAAC,sNAAsN,CAAC,GAD5O,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBAAS;wBACZ,MAAMC,QAAQ,qBAEb,CAFa,IAAIT,MAChB,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,sVAAsV,CAAC,GADpW,qBAAA;mCAAA;wCAAA;0CAAA;wBAEd;wBACAD,MAAMU,iBAAiB,CAACD,OAAOjB;wBAC/BmB,IAAAA,sCAAe,EAACF;wBAChBf,UAAUkB,wBAAwB,KAAKH;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BACHuB,IAAAA,iDAA+B,EAACvB;oBAChC,IAAIwB,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;wBAC1C,wEAAwE;wBACxE,8EAA8E;wBAC9E,4EAA4E;wBAC5E,IAAI1B,cAAc2B,gBAAgB,EAAE;4BAClC,OAAO3B,cAAc2B,gBAAgB,CAAChC,UAAU;wBAClD;wBACA,OAAOiC,IAAAA,iDAA0B,EAC/BpB,WACAR,eACA6B,4BAAW,CAACC,OAAO;oBAEvB,OAAO,IAAI9B,cAAc2B,gBAAgB,EAAE;wBACzC,OAAO3B,cAAc2B,gBAAgB,CAAChC,UAAU;oBAClD,OAAO;wBACL,OAAOW,QAAQC,OAAO,CAACC;oBACzB;gBACF;oBACER;YACJ;QACF;IACF;IAEA,yEAAyE;IACzE,8GAA8G;IAC9G,sDAAsD;IACtD+B,IAAAA,yDAA2B,EAACnC;AAC9B","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/connection.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to indicate that you require an actual user Request before continuing.\n *\n * During prerendering it will never resolve and during rendering it resolves immediately.\n */\nexport function connection(): Promise<void> {\n const callingExpression = 'connection'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`after()\\` while rendering. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic, we override all other logic and always just\n // return a resolving promise without tracking.\n return Promise.resolve(undefined)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`connection()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual request, but caches must be able to be produced before a request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'private-cache': {\n // It might not be intuitive to throw for private caches as well, but\n // we don't consider runtime prefetches as \"actual requests\" (in the\n // navigation sense), despite allowing them to read cookies.\n const error = new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \"use cache: private\". The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, connection)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside a function cached with \\`unstable_cache()\\`. The \\`connection()\\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // We return a promise that never resolves to allow the prerender to\n // stall at this point.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`connection()`'\n )\n case 'validation-client': {\n // TODO(NAR-789): make this consistent with the actual browser behavior when we change it.\n // Until then, erroring is fine.\n const exportName = '`connection`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n }\n case 'prerender-ppr':\n // We use React's postpone API to interrupt rendering here to create a\n // dynamic hole\n return postponeWithTracking(\n workStore.route,\n 'connection',\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We throw an error here to interrupt prerendering to mark the route\n // as dynamic\n return throwToInterruptStaticGeneration(\n 'connection',\n workStore,\n workUnitStore\n )\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.connection\n } else {\n return Promise.resolve(undefined)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n // TODO(NAR-789): connection() is not currently statically prevented from being imported in client components,\n // so we always error about a missing work unit store.\n throwForMissingRequestStore(callingExpression)\n}\n"],"names":["connection","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","Promise","resolve","undefined","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeDynamicHangingPromise","renderSignal","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","trackDynamicDataInDynamicRender","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","throwForMissingRequestStore"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;0CAzBiB;8CAI1B;kCAKA;yCAC+B;uCAI/B;uBAC2C;iCAEtB;gCACG;AAOxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,wVAAwV,CAAC,GAD9W,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,sEAAsE;YACtE,+CAA+C;YAC/C,OAAOC,QAAQC,OAAO,CAACC;QACzB;QAEA,IAAIX,UAAUY,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEb,UAAUO,KAAK,CAAC,sNAAsN,CAAC,GAD5O,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBAAS;wBACZ,MAAMC,QAAQ,qBAEb,CAFa,IAAIT,MAChB,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,sVAAsV,CAAC,GADpW,qBAA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,EACf,cACAJ,cAAcqB,eAAe;gBAEjC,KAAK;oBACH,qEAAqE;oBACrE,aAAa;oBACb,OAAOC,IAAAA,kDAAgC,EACrC,cACAzB,WACAG;gBAEJ,KAAK;oBACHuB,IAAAA,iDAA+B,EAACvB;oBAChC,IAAIwB,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;wBAC1C,wEAAwE;wBACxE,8EAA8E;wBAC9E,4EAA4E;wBAC5E,IAAI1B,cAAc2B,gBAAgB,EAAE;4BAClC,OAAO3B,cAAc2B,gBAAgB,CAAChC,UAAU;wBAClD;wBACA,OAAOiC,IAAAA,iDAA0B,EAC/BpB,WACAR,eACA6B,4BAAW,CAACC,OAAO;oBAEvB,OAAO,IAAI9B,cAAc2B,gBAAgB,EAAE;wBACzC,OAAO3B,cAAc2B,gBAAgB,CAAChC,UAAU;oBAClD,OAAO;wBACL,OAAOW,QAAQC,OAAO,CAACC;oBACzB;gBACF;oBACER;YACJ;QACF;IACF;IAEA,yEAAyE;IACzE,8GAA8G;IAC9G,sDAAsD;IACtD+B,IAAAA,yDAA2B,EAACnC;AAC9B","ignoreList":[0]} |
@@ -142,3 +142,3 @@ "use strict"; | ||
| } | ||
| const promise = (0, _dynamicrenderingutils.makeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`cookies()`'); | ||
| const promise = (0, _dynamicrenderingutils.makeRuntimeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`cookies()`', prerenderStore); | ||
| CachedCookies.set(prerenderStore, promise); | ||
@@ -145,0 +145,0 @@ return promise; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // We need track dynamic access here eagerly to keep continuity with\n // how cookies has worked in PPR without cacheComponents.\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`'\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["cookies","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeHangingCookies","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","areCookiesMutableInCurrentPhase","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","throwForMissingRequestStore","RequestCookiesAdapter","seal","RequestCookies","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","makeHangingPromise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;gCA5BT;yBACwB;0CAIxB;8CAMA;kCAKA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAExB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBC;YAC1B,OAAOC,qBAAqBF;QAC9B;QAEA,IAAIT,UAAUY,kBAAkB,EAAE;YAChC,MAAM,qBAEL,CAFK,IAAIC,8CAAqB,CAC7B,CAAC,MAAM,EAAEb,UAAUO,KAAK,CAAC,mNAAmN,CAAC,GADzO,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIJ,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBACH,MAAMC,QAAQ,qBAEb,CAFa,IAAIT,MAChB,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,kVAAkV,CAAC,GADhW,qBAAA;+BAAA;oCAAA;sCAAA;oBAEd;oBACAD,MAAMU,iBAAiB,CAACD,OAAOjB;oBAC/BmB,IAAAA,sCAAe,EAACF;oBAChBf,UAAUkB,wBAAwB,KAAKH;oBACvC,MAAMA;gBACR,KAAK;oBACH,MAAM,qBAEL,CAFK,IAAIT,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,0XAA0X,CAAC,GAD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AAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASf,8CACPQ,MAAe,EACfnE,KAAyB;IAEzB,OAAO;QACLqE,YAAY;QACZ7B;YACEY,kBAAkBpD,OAAO;YACzB,OAAOsE;QACT;QACA1B,KAAI2B,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPtD,KAAyB,EACzB2E,UAAkB;IAElB,MAAMC,SAAS5E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG6E,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/cookies.ts"],"sourcesContent":["import {\n type ReadonlyRequestCookies,\n areCookiesMutableInCurrentPhase,\n RequestCookiesAdapter,\n} from '../web/spec-extension/adapters/request-cookies'\nimport { RequestCookies } from '../web/spec-extension/cookies'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function cookies(): Promise<ReadonlyRequestCookies> {\n const callingExpression = 'cookies'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`cookies()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // cookies object without tracking\n const underlyingCookies = createEmptyCookies()\n return makeUntrackedCookies(underlyingCookies)\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`cookies()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n const error = new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, cookies)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`cookies()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n return makeHangingCookies(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`cookies`'\n throw new InvariantError(\n `${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // We need track dynamic access here eagerly to keep continuity with\n // how cookies has worked in PPR without cacheComponents.\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // We track dynamic access here so we don't need to wrap the cookies\n // in individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'cookies',\n workUnitStore.cookies\n )\n } else {\n return makeUntrackedCookies(workUnitStore.cookies)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedCookies(workUnitStore.cookies)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n let underlyingCookies: ReadonlyRequestCookies\n\n if (areCookiesMutableInCurrentPhase(workUnitStore)) {\n // We can't conditionally return different types here based on the context.\n // To avoid confusion, we always return the readonly type here.\n underlyingCookies =\n workUnitStore.userspaceMutableCookies as unknown as ReadonlyRequestCookies\n } else {\n underlyingCookies = workUnitStore.cookies\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedCookiesWithDevWarnings(\n workUnitStore,\n underlyingCookies,\n workStore?.route\n )\n } else if (workUnitStore.asyncApiPromises) {\n if (underlyingCookies === workUnitStore.mutableCookies) {\n return workUnitStore.asyncApiPromises.mutableCookies\n } else {\n return workUnitStore.asyncApiPromises.cookies\n }\n } else {\n return makeUntrackedCookies(underlyingCookies)\n }\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\nfunction createEmptyCookies(): ReadonlyRequestCookies {\n return RequestCookiesAdapter.seal(new RequestCookies(new Headers({})))\n}\n\ninterface CacheLifetime {}\nconst CachedCookies = new WeakMap<\n CacheLifetime,\n Promise<ReadonlyRequestCookies>\n>()\n\nfunction makeHangingCookies(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyRequestCookies> {\n const cachedPromise = CachedCookies.get(prerenderStore)\n if (cachedPromise) {\n return cachedPromise\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyRequestCookies>(\n prerenderStore.renderSignal,\n workStore.route,\n '`cookies()`',\n prerenderStore\n )\n CachedCookies.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookies(\n underlyingCookies: ReadonlyRequestCookies\n): Promise<ReadonlyRequestCookies> {\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = Promise.resolve(underlyingCookies)\n CachedCookies.set(underlyingCookies, promise)\n\n return promise\n}\n\nfunction makeUntrackedCookiesWithDevWarnings(\n requestStore: RequestStore,\n underlyingCookies: ReadonlyRequestCookies,\n route?: string\n): Promise<ReadonlyRequestCookies> {\n if (requestStore.asyncApiPromises) {\n let promise: Promise<ReadonlyRequestCookies>\n if (underlyingCookies === requestStore.mutableCookies) {\n promise = requestStore.asyncApiPromises.mutableCookies\n } else if (underlyingCookies === requestStore.cookies) {\n promise = requestStore.asyncApiPromises.cookies\n } else {\n throw new InvariantError(\n 'Received an underlying cookies object that does not match either `cookies` or `mutableCookies`'\n )\n }\n return instrumentCookiesPromiseWithDevWarnings(promise, route)\n }\n\n const cachedCookies = CachedCookies.get(underlyingCookies)\n if (cachedCookies) {\n return cachedCookies\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingCookies,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentCookiesPromiseWithDevWarnings(promise, route)\n\n CachedCookies.set(underlyingCookies, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createCookiesAccessError\n)\n\nfunction instrumentCookiesPromiseWithDevWarnings(\n promise: Promise<ReadonlyRequestCookies>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n size: replaceableWarningDescriptor(promise, 'size', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n getAll: replaceableWarningDescriptor(promise, 'getAll', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n clear: replaceableWarningDescriptor(promise, 'clear', route),\n toString: replaceableWarningDescriptor(promise, 'toString', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`cookies().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...cookies()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createCookiesAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`cookies()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["cookies","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingCookies","createEmptyCookies","makeUntrackedCookies","dynamicShouldError","StaticGenBailoutError","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","makeHangingCookies","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","areCookiesMutableInCurrentPhase","userspaceMutableCookies","process","env","NODE_ENV","makeUntrackedCookiesWithDevWarnings","asyncApiPromises","mutableCookies","throwForMissingRequestStore","RequestCookiesAdapter","seal","RequestCookies","Headers","CachedCookies","WeakMap","prerenderStore","cachedPromise","get","promise","makeRuntimeHangingPromise","renderSignal","set","cachedCookies","Promise","resolve","requestStore","instrumentCookiesPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createCookiesAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","size","replaceableWarningDescriptor","getAll","has","delete","clear","toString","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;gCA5BT;yBACwB;0CAIxB;8CAMA;kCAKA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAExB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,C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ACA1B,KAAI2B,KAAc;YAChBhB,OAAOiB,cAAc,CAACL,QAAQV,OAAOC,QAAQ,EAAE;gBAC7Ca;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASpB,yBACPtD,KAAyB,EACzB2E,UAAkB;IAElB,MAAMC,SAAS5E,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAG6E,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
@@ -148,3 +148,3 @@ "use strict"; | ||
| } | ||
| const promise = (0, _dynamicrenderingutils.makeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`headers()`'); | ||
| const promise = (0, _dynamicrenderingutils.makeRuntimeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`headers()`', prerenderStore); | ||
| CachedHeaders.set(prerenderStore, promise); | ||
@@ -151,0 +151,0 @@ return promise; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // PPR Prerender (no cacheComponents)\n // We are prerendering with PPR. We need track dynamic access here eagerly\n // to keep continuity with how headers has worked in PPR without cacheComponents.\n // TODO consider switching the semantic to throw on property access instead\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`'\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["headers","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingHeaders","HeadersAdapter","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","dynamicShouldError","StaticGenBailoutError","makeHangingHeaders","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","throwForMissingRequestStore","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","makeHangingPromise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAuCgBA;;;eAAAA;;;yBApCT;0CAIA;8CAMA;kCAKA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAWxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAM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IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAGyE,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/headers.ts"],"sourcesContent":["import {\n HeadersAdapter,\n type ReadonlyHeaders,\n} from '../web/spec-extension/adapters/headers'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n type PrerenderStoreModern,\n type RequestStore,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n trackDynamicDataInDynamicRender,\n} from '../app-render/dynamic-rendering'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\nimport { applyOwnerStack } from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\n/**\n * This function allows you to read the HTTP incoming request headers in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers) and\n * [Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware).\n *\n * Read more: [Next.js Docs: `headers`](https://nextjs.org/docs/app/api-reference/functions/headers)\n */\nexport function headers(): Promise<ReadonlyHeaders> {\n const callingExpression = 'headers'\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`after()\\` while rendering. This is not supported. If you need this data inside an \\`after()\\` callback, use \\`headers()\\` outside of the callback. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // headers object without tracking\n const underlyingHeaders = HeadersAdapter.seal(new Headers({}))\n return makeUntrackedHeaders(underlyingHeaders)\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache': {\n const error = new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \"use cache\". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`\n )\n Error.captureStackTrace(error, headers)\n applyOwnerStack(error)\n workStore.invalidDynamicUsageError ??= error\n throw error\n }\n case 'unstable-cache':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside a function cached with \\`unstable_cache()\\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \\`headers()\\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`\n )\n case 'generate-static-params':\n throw new Error(\n `Route ${workStore.route} used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`\n )\n case 'prerender':\n case 'prerender-client':\n case 'validation-client':\n case 'private-cache':\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n if (workStore.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${workStore.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`headers()\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n return makeHangingHeaders(workStore, workUnitStore)\n case 'prerender-client':\n case 'validation-client':\n const exportName = '`headers`'\n throw new InvariantError(\n `${exportName} must not be used within a client component. Next.js should be preventing ${exportName} from being included in client components statically, but did not in this case.`\n )\n case 'prerender-ppr':\n // PPR Prerender (no cacheComponents)\n // We are prerendering with PPR. We need track dynamic access here eagerly\n // to keep continuity with how headers has worked in PPR without cacheComponents.\n // TODO consider switching the semantic to throw on property access instead\n return postponeWithTracking(\n workStore.route,\n callingExpression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n // Legacy Prerender\n // We are in a legacy static generation mode while prerendering\n // We track dynamic access here so we don't need to wrap the headers in\n // individual property access tracking.\n return throwToInterruptStaticGeneration(\n callingExpression,\n workStore,\n workUnitStore\n )\n case 'prerender-runtime': {\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n return stagedRendering.delayUntilStage(\n RENDER_STAGES_BY_DATA_KIND.sessionData,\n 'headers',\n workUnitStore.headers\n )\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n }\n case 'private-cache':\n // Private caches are delayed until the runtime stage in use-cache-wrapper,\n // so we don't need an additional delay here.\n return makeUntrackedHeaders(workUnitStore.headers)\n case 'request':\n trackDynamicDataInDynamicRender(workUnitStore)\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedHeadersWithDevWarnings(\n workUnitStore.headers,\n workStore?.route,\n workUnitStore\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.headers\n } else {\n return makeUntrackedHeaders(workUnitStore.headers)\n }\n break\n default:\n workUnitStore satisfies never\n }\n }\n }\n\n // If we end up here, there was no work store or work unit store present.\n throwForMissingRequestStore(callingExpression)\n}\n\ninterface CacheLifetime {}\nconst CachedHeaders = new WeakMap<CacheLifetime, Promise<ReadonlyHeaders>>()\n\nfunction makeHangingHeaders(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(prerenderStore)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeRuntimeHangingPromise<ReadonlyHeaders>(\n prerenderStore.renderSignal,\n workStore.route,\n '`headers()`',\n prerenderStore\n )\n CachedHeaders.set(prerenderStore, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeaders(\n underlyingHeaders: ReadonlyHeaders\n): Promise<ReadonlyHeaders> {\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = Promise.resolve(underlyingHeaders)\n CachedHeaders.set(underlyingHeaders, promise)\n\n return promise\n}\n\nfunction makeUntrackedHeadersWithDevWarnings(\n underlyingHeaders: ReadonlyHeaders,\n route: string | undefined,\n requestStore: RequestStore\n): Promise<ReadonlyHeaders> {\n if (requestStore.asyncApiPromises) {\n return instrumentHeadersPromiseWithDevWarnings(\n requestStore.asyncApiPromises.headers,\n route\n )\n }\n\n const cachedHeaders = CachedHeaders.get(underlyingHeaders)\n if (cachedHeaders) {\n return cachedHeaders\n }\n\n const promise = makeDevtoolsIOAwarePromise(\n underlyingHeaders,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.sessionData\n )\n\n const proxiedPromise = instrumentHeadersPromiseWithDevWarnings(promise, route)\n\n CachedHeaders.set(underlyingHeaders, proxiedPromise)\n\n return proxiedPromise\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createHeadersAccessError\n)\n\nfunction instrumentHeadersPromiseWithDevWarnings(\n promise: Promise<ReadonlyHeaders>,\n route: string | undefined\n) {\n Object.defineProperties(promise, {\n [Symbol.iterator]: replaceableWarningDescriptorForSymbolIterator(\n promise,\n route\n ),\n append: replaceableWarningDescriptor(promise, 'append', route),\n delete: replaceableWarningDescriptor(promise, 'delete', route),\n get: replaceableWarningDescriptor(promise, 'get', route),\n has: replaceableWarningDescriptor(promise, 'has', route),\n set: replaceableWarningDescriptor(promise, 'set', route),\n getSetCookie: replaceableWarningDescriptor(promise, 'getSetCookie', route),\n forEach: replaceableWarningDescriptor(promise, 'forEach', route),\n keys: replaceableWarningDescriptor(promise, 'keys', route),\n values: replaceableWarningDescriptor(promise, 'values', route),\n entries: replaceableWarningDescriptor(promise, 'entries', route),\n })\n return promise\n}\n\nfunction replaceableWarningDescriptor(\n target: unknown,\n prop: string,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, `\\`headers().${prop}\\``)\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction replaceableWarningDescriptorForSymbolIterator(\n target: unknown,\n route: string | undefined\n) {\n return {\n enumerable: false,\n get() {\n warnForSyncAccess(route, '`...headers()` or similar iteration')\n return undefined\n },\n set(value: unknown) {\n Object.defineProperty(target, Symbol.iterator, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n })\n },\n configurable: true,\n }\n}\n\nfunction createHeadersAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`headers()\\` returns a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["headers","callingExpression","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","forceStatic","underlyingHeaders","HeadersAdapter","seal","Headers","makeUntrackedHeaders","type","error","captureStackTrace","applyOwnerStack","invalidDynamicUsageError","dynamicShouldError","StaticGenBailoutError","makeHangingHeaders","exportName","InvariantError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","stagedRendering","delayUntilStage","RENDER_STAGES_BY_DATA_KIND","sessionData","trackDynamicDataInDynamicRender","process","env","NODE_ENV","makeUntrackedHeadersWithDevWarnings","asyncApiPromises","throwForMissingRequestStore","CachedHeaders","WeakMap","prerenderStore","cachedHeaders","get","promise","makeRuntimeHangingPromise","renderSignal","set","Promise","resolve","requestStore","instrumentHeadersPromiseWithDevWarnings","makeDevtoolsIOAwarePromise","proxiedPromise","warnForSyncAccess","createDedupedByCallsiteServerErrorLoggerDev","createHeadersAccessError","Object","defineProperties","Symbol","iterator","replaceableWarningDescriptorForSymbolIterator","append","replaceableWarningDescriptor","delete","has","getSetCookie","forEach","keys","values","entries","target","prop","enumerable","undefined","value","defineProperty","writable","configurable","expression","prefix"],"mappings":";;;;+BAuCgBA;;;eAAAA;;;yBApCT;0CAIA;8CAMA;kCAKA;yCAC+B;uCAK/B;0DACqD;uBACV;gCAEnB;AAWxB,SAASA;IACd,MAAMC,oBAAoB;IAC1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,WAAW;QACb,IAAIG,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,6PAA6P,CAAC,GADnR,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,IAAIP,UAAUQ,WAAW,EAAE;YACzB,qFAAqF;YACrF,kCAAkC;YAClC,MAAMC,oBAAoBC,uBAAc,CAACC,IAAI,CAAC,IAAIC,QAAQ,CAAC;YAC3D,OAAOC,qBAAqBJ;QAC9B;QAEA,IAAIN,eAAe;YACjB,OAAQA,cAAcW,IAAI;gBACxB,KAAK;oBAAS;wBACZ,MAAMC,QAAQ,qBAEb,CAFa,IAAIT,MAChB,CAA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AOoC;AACT;AAEA,SAASmB,6BACPQ,MAAe,EACfC,IAAY,EACZhE,KAAyB;IAEzB,OAAO;QACLiE,YAAY;QACZ9B;YACEW,kBAAkB9C,OAAO,CAAC,YAAY,EAAEgE,KAAK,EAAE,CAAC;YAChD,OAAOE;QACT;QACA3B,KAAI4B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQC,MAAM;gBAClCG;gBACAE,UAAU;gBACVC,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAASjB,8CACPU,MAAe,EACf/D,KAAyB;IAEzB,OAAO;QACLiE,YAAY;QACZ9B;YACEW,kBAAkB9C,OAAO;YACzB,OAAOkE;QACT;QACA3B,KAAI4B,KAAc;YAChBlB,OAAOmB,cAAc,CAACL,QAAQZ,OAAOC,QAAQ,EAAE;gBAC7Ce;gBACAE,UAAU;gBACVJ,YAAY;gBACZK,cAAc;YAChB;QACF;QACAA,cAAc;IAChB;AACF;AAEA,SAAStB,yBACPhD,KAAyB,EACzBuE,UAAkB;IAElB,MAAMC,SAASxE,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAID,MACT,GAAGyE,OAAO,KAAK,EAAED,WAAW,EAAE,CAAC,GAC7B,CAAC,yHAAyH,CAAC,GAC3H,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} |
@@ -56,3 +56,3 @@ "use strict"; | ||
| // anything after it by making it return a hanging promise. | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, '`io()`'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`io()`'); | ||
| case 'prerender-ppr': | ||
@@ -59,0 +59,0 @@ // Dead code to be removed when we eliminate legacy ppr code |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'prerender-ppr':\n // Dead code to be removed when we eliminate legacy ppr code\n throwPrerenderPPRRemovedError()\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["io","resolvedIOPromise","Promise","resolve","undefined","status","value","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","type","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","makeHangingPromise","renderSignal","throwPrerenderPPRRemovedError"],"mappings":";;;;+BA2BgBA;;;eAAAA;;;0CA3BiB;8CACI;uCAI9B;iCACqB;iCACkB;uBACI;AAElD,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAMC,oBAAmCC,QAAQC,OAAO,CAACC;AACvDH,kBAA0B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DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOxB;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/io.ts"],"sourcesContent":["import { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeDevtoolsIOAwarePromise,\n} from '../dynamic-rendering-utils'\nimport { RenderStage } from '../app-render/staged-rendering'\nimport { throwPrerenderPPRRemovedError } from '../../shared/lib/ppr-removed-error'\nimport { isRequestApiAllowedInCurrentPhase } from './utils'\n\n// A fulfilled thenable that React can unwrap synchronously via `use()` without\n// ever suspending. Reusing a single instance avoids allocating on every call.\nconst resolvedIOPromise: Promise<void> = Promise.resolve(undefined)\n;(resolvedIOPromise as any).status = 'fulfilled'\n;(resolvedIOPromise as any).value = undefined\n\n/**\n * This function allows you to indicate that the code following it performs\n * I/O or accesses dynamic data sources such as `new Date()` or `Math.random()`.\n *\n * During prerendering it will prevent the prerender from continuing past this\n * point, creating a dynamic boundary. Inside `\"use cache\"` scopes or during\n * a real request it resolves immediately.\n *\n * Unlike `connection()`, `io()` does not require an actual HTTP request and\n * can be used freely inside cache scopes and client components.\n */\nexport function io(): Promise<void> {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (workStore && workUnitStore) {\n if (workUnitStore && !isRequestApiAllowedInCurrentPhase(workUnitStore)) {\n throw new Error(\n `Route ${workStore.route} used \\`io()\\` inside \\`after()\\` while rendering. The \\`io()\\` function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`\n )\n }\n switch (workUnitStore.type) {\n case 'request':\n // For dev renders we instrument the promise so it will show up in\n // React Suspense Devtools and, if also doing `instant` validation,\n // ensure it resolves in the right stage for staged rendering\n // In production we just let it resolve immediately because we're doing\n // a dynamic SSR or resume render and have no need to delay anything\n // after this call\n if (process.env.NODE_ENV === 'development') {\n if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return makeDevtoolsIOAwarePromise(\n undefined,\n workUnitStore,\n RenderStage.Dynamic\n )\n } else if (workUnitStore.asyncApiPromises) {\n return workUnitStore.asyncApiPromises.io\n }\n return resolvedIOPromise\n case 'prerender':\n case 'prerender-client':\n case 'prerender-runtime':\n // When prerendering with Cache Components we consider `io()` to be\n // actual IO if not in a cache scope and we can avoid actually executing\n // anything after it by making it return a hanging promise.\n return makeDynamicHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`io()`'\n )\n case 'prerender-ppr':\n // Dead code to be removed when we eliminate legacy ppr code\n throwPrerenderPPRRemovedError()\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n // Inside cache scopes, io() resolves immediately.\n // Caches can contain IO-dependent code like new Date() — it will\n // simply return the value at cache-fill time.\n // ...\n // intentional fallthrough\n case 'generate-static-params':\n // generateStaticParams runs at build time. There is no prerender\n // to stall so we resolve immediately.\n // ...\n // intentional fallthrough\n case 'validation-client':\n // io() is usable in client components, resolve immediately.\n // The reason we take this position is most io shielding you would do\n // in a browser is for sync IO as there aren't many non-fetch based IO\n // operations you can do in the browser that have meaningful latency.\n // So while you might use\n // ...\n // intentional fallthrough\n case 'prerender-legacy':\n // Without cache components, IO is not inherently dynamic.\n // Resolve immediately rather than interrupting static generation.\n return resolvedIOPromise\n default:\n workUnitStore satisfies never\n }\n }\n\n // No work store — we're outside the Next.js rendering context (e.g. in\n // a client component on the browser or in a standalone script). Resolve\n // immediately.\n return resolvedIOPromise\n}\n"],"names":["io","resolvedIOPromise","Promise","resolve","undefined","status","value","workStore","workAsyncStorage","getStore","workUnitStore","workUnitAsyncStorage","isRequestApiAllowedInCurrentPhase","Error","route","type","process","env","NODE_ENV","asyncApiPromises","makeDevtoolsIOAwarePromise","RenderStage","Dynamic","makeDynamicHangingPromise","renderSignal","throwPrerenderPPRRemovedError"],"mappings":";;;;+BA2BgBA;;;eAAAA;;;0CA3BiB;8CACI;uCAI9B;iCACqB;iCACkB;uBACI;AAElD,+EAA+E;AAC/E,8EAA8E;AAC9E,MAAMC,oBAAmCC,QAAQC,OAAO,CAACC;AACvDH,kBAA0BI,MAAM,GAAG;AACnCJ,kBAA0BK,KAAK,GAAGF;AAa7B,SAASJ;IACd,MAAMO,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,MAAMC,gBAAgBC,kDAAoB,CAACF,QAAQ;IAEnD,IAAIF,aAAaG,eAAe;QAC9B,IAAIA,iBAAiB,CAACE,IAAAA,wCAAiC,EAACF,gBAAgB;YACtE,MAAM,qBAEL,CAFK,IAAIG,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,oLAAoL,CAAC,GAD1M,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QACA,OAAQJ,cAAcK,IAAI;YACxB,KAAK;gBACH,kEAAkE;gBAClE,mEAAmE;gBACnE,6DAA6D;gBAC7D,uEAAuE;gBACvE,oEAAoE;gBACpE,kBAAkB;gBAClB,IAAIC,QAAQC,GAAG,CAACC,QAAQ,KAAK,eAAe;oBAC1C,IAAIR,cAAcS,gBAAgB,EAAE;wBAClC,OAAOT,cAAcS,gBAAgB,CAACnB,EAAE;oBAC1C;oBACA,OAAOoB,IAAAA,iDAA0B,EAC/BhB,WACAM,eACAW,4BAAW,CAACC,OAAO;gBAEvB,OAAO,IAAIZ,cAAcS,gBAAgB,EAAE;oBACzC,OAAOT,cAAcS,gBAAgB,CAACnB,EAAE;gBAC1C;gBACA,OAAOC;YACT,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,wEAAwE;gBACxE,2DAA2D;gBAC3D,OAAOsB,IAAAA,gDAAyB,EAC9Bb,cAAcc,YAAY,EAC1BjB,UAAUO,KAAK,EACf;YAEJ,KAAK;gBACH,4DAA4D;gBAC5DW,IAAAA,8CAA6B;gBAC7B;YACF,KAAK;YACL,KAAK;YACL,KAAK;YACL,kDAAkD;YAClD,iEAAiE;YACjE,8CAA8C;YAC9C,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,iEAAiE;YACjE,sCAAsC;YACtC,MAAM;YACN,0BAA0B;YAC1B,KAAK;YACL,4DAA4D;YAC5D,qEAAqE;YACrE,sEAAsE;YACtE,qEAAqE;YACrE,yBAAyB;YACzB,MAAM;YACN,0BAA0B;YAC1B,KAAK;gBACH,0DAA0D;gBAC1D,kEAAkE;gBAClE,OAAOxB;YACT;gBACES;QACJ;IACF;IAEA,uEAAuE;IACvE,wEAAwE;IACxE,eAAe;IACf,OAAOT;AACT","ignoreList":[0]} |
@@ -247,3 +247,3 @@ "use strict"; | ||
| // resolves. | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, '`params`'); | ||
| return (0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(workUnitStore.renderSignal, workStore.route, '`params`', workUnitStore); | ||
| } | ||
@@ -490,2 +490,10 @@ } | ||
| [prop]: (...args)=>{ | ||
| // Record against the store that's active at access time: the | ||
| // hanging promise is cached by params object across prerender | ||
| // stores, so the store that created it may not be the one that's | ||
| // rendering when it's finally awaited. | ||
| const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); | ||
| if (workUnitStore !== undefined) { | ||
| (0, _dynamicrenderingutils.trackFallbackParamsAccessed)(workUnitStore); | ||
| } | ||
| const store = _dynamicaccessasyncstorageexternal.dynamicAccessAsyncStorage.getStore(); | ||
@@ -511,3 +519,6 @@ if (store) { | ||
| } | ||
| const promise = new Proxy((0, _dynamicrenderingutils.makeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`params`'), fallbackParamsProxyHandler); | ||
| const promise = new Proxy((0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, '`params`', // This promise is created for every segment on a fallback route whether | ||
| // or not it reads params, so recording the access at creation would mark | ||
| // every render. The access is tracked in the proxy traps instead. | ||
| null), fallbackParamsProxyHandler); | ||
| CachedParams.set(underlyingParams, promise); | ||
@@ -514,0 +525,0 @@ return promise; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n makePromiseFromTrigger,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`'\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsSessionShell`.\n const staticParamsStage = workUnitStore.needsSessionShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`'\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackRouteParams","key","has","makeHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsSessionShell","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","store","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","wellKnownProperties","defineProperty","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","enumerable","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAkDgBA,sBAAsB;eAAtBA;;IAwNAC,qCAAqC;eAArCA;;IAxIAC,6BAA6B;eAA7BA;;IAaAC,0BAA0B;eAA1BA;;IA8DAC,kCAAkC;eAAlCA;;;0CA1MT;4BAMA;yBAEwB;kCAIxB;8CAYA;gCACwB;8BAIxB;uCAMA;0DACqD;mDAClB;6BAKnC;AAKA,SAASJ,uBACdK,gBAAwB;IAExB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,iEAAiE;gBACjE,yBAAyB;gBACzB,MAAMC,wBAAwB;gBAC9B,OAAOC,4BACLT,kBACA,MACAC,WACAI,eACAG;YAEJ,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIJ,8BAAc,CACtB,mEADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB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EA,OAAO,IAAIU,MAAMvC,SAAS;QACxB2B,KAAIC,MAAM,EAAEC,IAAI,EAAEC,QAAQ;YACxB,IAAI,OAAOD,SAAS,UAAU;gBAC5B,IACE,uEAAuE;gBACvE2B,kBAAkBhF,GAAG,CAACqD,OACtB;oBACA,MAAMkB,aAAaC,IAAAA,0CAA4B,EAAC,UAAUnB;oBAC1D6B,kBAAkB7G,UAAU8B,KAAK,EAAEoE;gBACrC;YACF;YACA,OAAOf,uBAAc,CAACL,GAAG,CAACC,QAAQC,MAAMC;QAC1C;QACAY,KAAId,MAAM,EAAEC,IAAI,EAAE8B,KAAK,EAAE7B,QAAQ;YAC/B,IAAI,OAAOD,SAAS,UAAU;gBAC5B2B,kBAAkBI,MAAM,CAAC/B;YAC3B;YACA,OAAOG,uBAAc,CAACU,GAAG,CAACd,QAAQC,MAAM8B,OAAO7B;QACjD;QACA+B,SAAQjC,MAAM;YACZ,MAAMmB,aAAa;YACnBW,kBAAkB7G,UAAU8B,KAAK,EAAEoE;YACnC,OAAOe,QAAQD,OAAO,CAACjC;QACzB;IACF;AACF;AAEA,MAAM8B,oBAAoBK,IAAAA,qFAA2C,EACnEC;AAGF,SAASA,wBACPrF,KAAyB,EACzBoE,UAAkB;IAElB,MAAMkB,SAAStF,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAI2D,MACT,GAAG2B,OAAO,KAAK,EAAElB,WAAW,EAAE,CAAC,GAC7B,CAAC,iHAAiH,CAAC,GACnH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { OpaqueFallbackRouteParams } from './fallback-params'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n} from '../app-render/dynamic-rendering'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStorePPR,\n type PrerenderStoreLegacy,\n type StaticPrerenderStoreModern,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type PrerenderStoreModernRuntime,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n describeStringPropertyAccess,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n makeDevtoolsIOAwarePromise,\n makeFallbackParamsHangingPromise,\n makePromiseFromTrigger,\n trackFallbackParamsAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\nimport {\n isEmptyParams,\n hasFallbackRouteParams,\n allParamsAreRootParams,\n} from '../lib/params-utils'\n\nexport type ParamValue = string | Array<string> | undefined\nexport type Params = Record<string, ParamValue>\n\nexport function createParamsFromClient(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n // Client params don't need additional vary tracking because by the\n // time they reach the client, the access would have already been\n // tracked by the server.\n const varyParamsAccumulator = null\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createParamsFromClient should not be called in cache contexts.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createParamsFromClient should not be called in a runtime prerender.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n return makeUntrackedParams(underlyingParams)\n }\n case 'request': {\n if (workUnitStore.validationSamples) {\n return createClientParamsInInstantValidation(\n underlyingParams,\n workStore,\n workUnitStore.validationSamples\n )\n }\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport type CreateServerParamsForMetadata = typeof createServerParamsForMetadata\nexport function createServerParamsForMetadata(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null\n): Promise<Params> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerParamsForServerSegment(\n underlyingParams,\n optionalCatchAllParamName,\n metadataVaryParamsAccumulator\n )\n}\n\n// routes always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerParamsForRoute(\n underlyingParams: Params,\n varyParamsAccumulator: VaryParamsAccumulator | null = null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n null,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForRoute should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n throw new InvariantError(\n 'createServerParamsForRoute should not be called in runtime prerenders.'\n )\n }\n case 'request':\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n const userspaceParams = underlyingParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(underlyingParams)\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createServerParamsForServerSegment(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'validation-client':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerParamsForServerSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderParams(\n underlyingParams,\n optionalCatchAllParamName,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request': {\n return createRenderParamsForPage(\n workStore,\n workUnitStore,\n underlyingParams,\n optionalCatchAllParamName,\n varyParamsAccumulator\n )\n }\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderParamsForClientSegment(\n underlyingParams: Params\n): Promise<Params> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(\n 'Missing workStore in createPrerenderParamsForClientSegment'\n )\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams) {\n for (let key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeFallbackParamsHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`params`',\n workUnitStore\n )\n }\n }\n }\n break\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in validation contexts.'\n )\n break\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n break\n default:\n workUnitStore satisfies never\n }\n }\n // We're prerendering in a mode that does not abort. We resolve the promise without\n // any tracking because we're just transporting a value from server to client where the tracking\n // will be applied.\n return Promise.resolve(underlyingParams)\n}\n\nfunction createStaticPrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n switch (prerenderStore.type) {\n case 'prerender': {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (hasFallbackRouteParams(underlyingParams, fallbackParams)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object dynamic.\n return makeHangingParams(underlyingParams, workStore, prerenderStore)\n }\n\n // All params are static.\n\n const { stagedRendering } = prerenderStore\n if (stagedRendering) {\n // Even if all params are static, we need to exclude them from the app shell\n // by delaying them to the static stage. However, root params are allowed in shells,\n // so if all the params are root params, they can be included as well.\n if (\n !allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)\n ) {\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n }\n\n return makeUntrackedParams(userspaceParams)\n }\n case 'prerender-client': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n // This params object has one or more fallback params, so we need\n // to consider the awaiting of this params object \"dynamic\". Since\n // we are in cacheComponents mode we encode this as a promise that never\n // resolves.\n return makeHangingParams(\n underlyingParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams) {\n for (const key in underlyingParams) {\n if (fallbackParams.has(key)) {\n return makeErroringParams(\n underlyingParams,\n fallbackParams,\n workStore,\n prerenderStore\n )\n }\n }\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRuntimePrerenderParams(\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<Params> {\n let userspaceParams = underlyingParams\n if (varyParamsAccumulator !== null) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n underlyingParams,\n optionalCatchAllParamName\n )\n }\n\n if (isEmptyParams(underlyingParams)) {\n // This route has no params.\n return makeUntrackedParams(userspaceParams)\n }\n\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, params should be hanging,\n // because they'll be a hanging input in the final prerender.\n return makeHangingParams(underlyingParams, workStore, workUnitStore)\n } else {\n return makeUntrackedParams(userspaceParams)\n }\n }\n\n // We don't have fallbackParams in runtime prerenders, so we don't know\n // when params are static. However, root params are static by definition,\n // so we can at least check for that.\n // Note that resolving them without a delay is valid because root params are\n // allowed in shells.\n if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // Semantically, we should resolve static params in the static stage.\n // But params are link data, and we need to recover a param-less session shell,\n // so we delay all params until the runtime stage instead.\n const staticParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n}\n\nfunction createRenderParamsForPage(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n underlyingParams: Params,\n optionalCatchAllParamName: string | null,\n varyParamsAccumulator: VaryParamsAccumulator | null\n) {\n const { stagedRendering, asyncApiPromises, validationSamples } = workUnitStore\n\n // Distinguish the params that we expose to userspace (potentially wrapped in proxies)\n // and the underlying object containing params values. We do this because wrappers\n // like `instrumentParamsPromiseWithDevWarnings` need to be able to get the known param names\n // without triggering other wrapper proxies.\n let userspaceParams = underlyingParams\n if (validationSamples) {\n userspaceParams = createServerParamsProxyForInstantValidation(\n underlyingParams,\n workStore,\n validationSamples\n )\n }\n if (varyParamsAccumulator) {\n userspaceParams = createVaryingParams(\n varyParamsAccumulator,\n userspaceParams,\n optionalCatchAllParamName\n )\n }\n\n if (stagedRendering && asyncApiPromises) {\n return createStagedRenderParams(\n workStore,\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n if (process.env.NODE_ENV === 'development') {\n const fallbackParams = workUnitStore.fallbackParams\n return createRenderParamsInDev(\n underlyingParams,\n userspaceParams,\n fallbackParams,\n workStore,\n workUnitStore\n )\n } else {\n return createRenderParamsInProd(userspaceParams)\n }\n}\n\nfunction createStagedRenderParams(\n workStore: WorkStore,\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingParams: Params,\n userspaceParams: Params\n) {\n const promise = createStagedRenderParamsImpl(\n workUnitStore,\n stagedRendering,\n asyncApiPromises,\n underlyingParams,\n userspaceParams\n )\n if (process.env.NODE_ENV === 'development') {\n return instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n } else {\n return promise\n }\n}\n\nfunction createStagedRenderParamsImpl(\n workUnitStore: RequestStore,\n stagedRendering: NonNullable<RequestStore['stagedRendering']>,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n /** The actual param values, without any instrumentation */\n underlyingParams: Params,\n /** The params object to return to userspace, possibly wrapped in a proxy */\n userspaceParams: Params\n) {\n // If the route has no params, they should resolve immediately.\n if (isEmptyParams(underlyingParams)) {\n return makeUntrackedParams(userspaceParams)\n }\n\n // If we have fallback params, then they should always resolve in the runtime link data stage.\n // We do this indirectly via the shared params parent for better debug info.\n if (hasFallbackRouteParams(underlyingParams, workUnitStore.fallbackParams)) {\n return createParamsPromiseFromTrigger(\n asyncApiPromises.sharedParamsParent,\n userspaceParams\n )\n }\n\n // All params are static.\n\n // If we're rendering with shells, even static params must be delayed to exclude them from the shell.\n // However, root params are allowed in shells, so if all the params are root params, they can be included as well.\n if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {\n // For a dynamic request we generally want to recover a static shell,\n // so static params can resolve in the static stage, because session\n // shells are handled with a separate render.\n // However, in dev we might need to recover a session shell for instant validation.\n // This is indicated by `needsSessionShell`.\n const staticParamsStage = workUnitStore.needsSessionShell\n ? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n : RENDER_STAGES_BY_DATA_KIND.staticLinkData\n return stagedRendering.delayUntilStage(\n staticParamsStage,\n 'params',\n userspaceParams\n )\n }\n\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createParamsPromiseFromTrigger(\n trigger: Promise<any>,\n userspaceParams: Params\n) {\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of params in a `new Promise()`, which lets us show each\n // await a different set of values. This is important when all awaits\n // are in third party which would otherwise track all the way to the\n // internal params.\n const promise: Promise<Params> = new Promise((resolve, reject) => {\n trigger.then(() => resolve(userspaceParams), reject)\n })\n promise.catch(noop)\n // @ts-expect-error\n promise.displayName = 'params'\n return promise\n } else {\n return makePromiseFromTrigger(trigger, userspaceParams)\n }\n}\n\nfunction noop() {}\n\nfunction createServerParamsProxyForInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>\n): Params {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples.params ?? {}))\n return createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n}\n\nfunction createClientParamsInInstantValidation(\n underlyingParams: Params,\n workStore: WorkStore,\n validationSamples: ValidationStoreClient['validationSamples']\n): Promise<Params> {\n const { createExhaustiveParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredParams = new Set(Object.keys(validationSamples?.params ?? {}))\n const proxiedUnderlying = createExhaustiveParamsProxy(\n underlyingParams,\n declaredParams,\n workStore.route\n )\n return Promise.resolve(proxiedUnderlying)\n}\n\nfunction createRenderParamsInProd(userspaceParams: Params): Promise<Params> {\n return makeUntrackedParams(userspaceParams)\n}\n\nfunction createRenderParamsInDev(\n underlyingParams: Params,\n userpaceParams: Params,\n fallbackParams: OpaqueFallbackRouteParams | null | undefined,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n return makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams,\n userpaceParams,\n hasFallbackRouteParams(underlyingParams, fallbackParams),\n workStore,\n requestStore\n )\n}\n\ninterface CacheLifetime {}\nconst CachedParams = new WeakMap<CacheLifetime, Promise<Params>>()\n\nconst fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {\n get: function get(target, prop, receiver) {\n if (prop === 'then' || prop === 'catch' || prop === 'finally') {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n\n return {\n [prop]: (...args: unknown[]) => {\n // Record against the store that's active at access time: the\n // hanging promise is cached by params object across prerender\n // stores, so the store that created it may not be the one that's\n // rendering when it's finally awaited.\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore !== undefined) {\n trackFallbackParamsAccessed(workUnitStore)\n }\n\n const store = dynamicAccessAsyncStorage.getStore()\n\n if (store) {\n store.abortController.abort(\n new Error(`Accessed fallback \\`params\\` during prerendering.`)\n )\n }\n\n return new Proxy(\n originalMethod.apply(target, args),\n fallbackParamsProxyHandler\n )\n },\n }[prop]\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n}\n\nfunction makeHangingParams(\n underlyingParams: Params,\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = new Proxy(\n makeFallbackParamsHangingPromise<Params>(\n prerenderStore.renderSignal,\n workStore.route,\n '`params`',\n // This promise is created for every segment on a fallback route whether\n // or not it reads params, so recording the access at creation would mark\n // every render. The access is tracked in the proxy traps instead.\n null\n ),\n fallbackParamsProxyHandler\n )\n\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeErroringParams(\n underlyingParams: Params,\n fallbackParams: OpaqueFallbackRouteParams,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const augmentedUnderlying = { ...underlyingParams }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = Promise.resolve(augmentedUnderlying)\n CachedParams.set(underlyingParams, promise)\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n if (fallbackParams.has(prop)) {\n Object.defineProperty(augmentedUnderlying, prop, {\n get() {\n const expression = describeStringPropertyAccess('params', prop)\n // In most dynamic APIs we also throw if `dynamic = \"error\"` however\n // for params is only dynamic when we're generating a fallback shell\n // and even when `dynamic = \"error\"` we still support generating dynamic\n // fallback shells\n // TODO remove this comment when cacheComponents is the default since there\n // will be no `dynamic = \"error\"`\n if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n },\n enumerable: true,\n })\n }\n }\n })\n\n return promise\n}\n\nfunction makeUntrackedParams(underlyingParams: Params): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n const promise = Promise.resolve(underlyingParams)\n CachedParams.set(underlyingParams, promise)\n\n return promise\n}\n\nfunction makeDynamicallyTrackedParamsWithDevWarnings(\n underlyingParams: Params,\n userspaceParams: Params,\n hasFallbackParams: boolean,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<Params> {\n const cachedParams = CachedParams.get(underlyingParams)\n if (cachedParams) {\n return cachedParams\n }\n\n // We don't use makeResolvedReactPromise here because params\n // supports copying with spread and we don't want to unnecessarily\n // instrument the promise with spreadable properties of ReactPromise.\n const promise = hasFallbackParams\n ? makeDevtoolsIOAwarePromise(\n userspaceParams,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n : // We don't want to force an environment transition when this params is not part of the fallback params set\n Promise.resolve(userspaceParams)\n\n const proxiedPromise = instrumentParamsPromiseWithDevWarnings(\n underlyingParams,\n promise,\n workStore\n )\n CachedParams.set(underlyingParams, proxiedPromise)\n return proxiedPromise\n}\n\nfunction instrumentParamsPromiseWithDevWarnings(\n underlyingParams: Params,\n promise: Promise<Params>,\n workStore: WorkStore\n): Promise<Params> {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (typeof prop === 'string') {\n if (\n // We are accessing a property that was proxied to the promise instance\n proxiedProperties.has(prop)\n ) {\n const expression = describeStringPropertyAccess('params', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return ReflectAdapter.set(target, prop, value, receiver)\n },\n ownKeys(target) {\n const expression = '`...params` or similar expression'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createParamsAccessError\n)\n\nfunction createParamsAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`params\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n"],"names":["createParamsFromClient","createPrerenderParamsForClientSegment","createServerParamsForMetadata","createServerParamsForRoute","createServerParamsForServerSegment","underlyingParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","varyParamsAccumulator","createStaticPrerenderParams","validationSamples","createClientParamsInInstantValidation","makeUntrackedParams","process","env","NODE_ENV","fallbackParams","userspaceParams","createRenderParamsInDev","createRenderParamsInProd","throwInvariantForMissingStore","optionalCatchAllParamName","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","createRuntimePrerenderParams","createRenderParamsForPage","fallbackRouteParams","key","has","makeFallbackParamsHangingPromise","renderSignal","route","Promise","resolve","prerenderStore","createVaryingParams","isEmptyParams","hasFallbackRouteParams","makeHangingParams","stagedRendering","allParamsAreRootParams","rootParams","staticParamsStage","RENDER_STAGES_BY_DATA_KIND","staticLinkData","delayUntilStage","makeErroringParams","isSessionShell","runtimeLinkData","asyncApiPromises","createServerParamsProxyForInstantValidation","createStagedRenderParams","promise","createStagedRenderParamsImpl","instrumentParamsPromiseWithDevWarnings","createParamsPromiseFromTrigger","sharedParamsParent","needsSessionShell","trigger","reject","then","catch","noop","displayName","makePromiseFromTrigger","createExhaustiveParamsProxy","require","declaredParams","Set","Object","keys","params","proxiedUnderlying","userpaceParams","requestStore","makeDynamicallyTrackedParamsWithDevWarnings","CachedParams","WeakMap","fallbackParamsProxyHandler","get","target","prop","receiver","originalMethod","ReflectAdapter","args","undefined","trackFallbackParamsAccessed","store","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","cachedParams","set","augmentedUnderlying","forEach","wellKnownProperties","defineProperty","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","enumerable","hasFallbackParams","makeDevtoolsIOAwarePromise","proxiedPromise","proxiedProperties","add","warnForSyncAccess","value","delete","ownKeys","Reflect","createDedupedByCallsiteServerErrorLoggerDev","createParamsAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAmDgBA,sBAAsB;eAAtBA;;IAwNAC,qCAAqC;eAArCA;;IAxIAC,6BAA6B;eAA7BA;;IAaAC,0BAA0B;eAA1BA;;IA8DAC,kCAAkC;eAAlCA;;;0CA3MT;4BAMA;yBAEwB;kCAIxB;8CAYA;gCACwB;8BAIxB;uCAOA;0DACqD;mDAClB;6BAKnC;AAKA,SAASJ,uBACdK,gBAAwB;IAExB,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,mEAAmE;gBACnE,iEAAiE;gBACjE,yBAAyB;gBACzB,MAAMC,wBAAwB;gBAC9B,OAAOC,4BACLT,kBACA,MACAC,WACAI,eACAG;YAEJ,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIJ,8BAAc,CACtB,mEADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,wEADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,6EADI,q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| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, '`pathname`'); | ||
| return (0, _dynamicrenderingutils.makeDynamicHangingPromise)(workUnitStore.renderSignal, workStore.route, '`pathname`'); | ||
| } else { | ||
@@ -91,3 +91,6 @@ return createRenderPathname(underlyingPathname); | ||
| if (fallbackParams && fallbackParams.size > 0) { | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`pathname`'); | ||
| // The pathname only hangs when there are fallback params, and a | ||
| // concrete (ISR-upgraded) prerender resolves it — so this access is | ||
| // fallback-param data for the static-prefetch hint. | ||
| return (0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, '`pathname`', prerenderStore); | ||
| } | ||
@@ -94,0 +97,0 @@ break; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n postponeWithTracking,\n type DynamicTrackingState,\n} from '../app-render/dynamic-rendering'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeErroringPathname(workStore, prerenderStore.dynamicTracking)\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction makeErroringPathname<T>(\n workStore: WorkStore,\n dynamicTracking: null | DynamicTrackingState\n): Promise<T> {\n let reject: null | ((reason: unknown) => void) = null\n const promise = new Promise<T>((_, re) => {\n reject = re\n })\n\n const originalThen = promise.then.bind(promise)\n\n // We instrument .then so that we can generate a tracking event only if you actually\n // await this promise, not just that it is created.\n promise.then = (onfulfilled, onrejected) => {\n if (reject) {\n try {\n postponeWithTracking(\n workStore.route,\n 'metadata relative url resolving',\n dynamicTracking\n )\n } catch (error) {\n reject(error)\n reject = null\n }\n }\n return originalThen(onfulfilled, onrejected)\n }\n\n // We wrap in a noop proxy to trick the runtime into thinking it\n // isn't a native promise (it's not really). This is so that awaiting\n // the promise will call the `then` property triggering the lazy postpone\n return new Proxy(promise, {})\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["createServerPathnameForMetadata","underlyingPathname","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createPrerenderPathname","stagedRendering","pathnameStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","delayUntilStage","undefined","isSessionShell","makeHangingPromise","renderSignal","route","createRenderPathname","throwInvariantForMissingStore","prerenderStore","fallbackParams","fallbackRouteParams","size","makeErroringPathname","dynamicTracking","Promise","resolve","reject","promise","_","re","originalThen","then","bind","onfulfilled","onrejected","postponeWithTracking","error","Proxy"],"mappings":";;;;+BAuBgBA;;;eAAAA;;;0CApBT;kCAKA;8CAQA;uCAIA;gCACwB;AAExB,SAASA,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cA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EAC3BhB,UAAUiB,KAAK,EACf;gBAEJ;gBACA;YACF;QACA,KAAK;YAAiB;gBACpB,MAAMI,iBAAiBD,eAAeE,mBAAmB;gBACzD,IAAID,kBAAkBA,eAAeE,IAAI,GAAG,GAAG;oBAC7C,OAAOC,qBAAqBxB,WAAWoB,eAAeK,eAAe;gBACvE;gBACA;YACF;QACA,KAAK;YACH;QACF;YACEL;IACJ;IAEA,qFAAqF;IACrF,OAAOM,QAAQC,OAAO,CAAC5B;AACzB;AAEA,SAASyB,qBACPxB,SAAoB,EACpByB,eAA4C;IAE5C,IAAIG,SAA6C;IACjD,MAAMC,UAAU,IAAIH,QAAW,CAACI,GAAGC;QACjCH,SAASG;IACX;IAEA,MAAMC,eAAeH,QAAQI,IAAI,CAACC,IAAI,CAACL;IAEvC,oFAAoF;IACpF,mDAAmD;IACnDA,QAAQI,IAAI,GAAG,CAACE,aAAaC;QAC3B,IAAIR,QAAQ;YACV,IAAI;gBACFS,IAAAA,sCAAoB,EAClBrC,UAAUiB,KAAK,EACf,mCACAQ;YAEJ,EAAE,OAAOa,OAAO;gBACdV,OAAOU;gBACPV,SAAS;YACX;QACF;QACA,OAAOI,aAAaG,aAAaC;IACnC;IAEA,gEAAgE;IAChE,qEAAqE;IACrE,yEAAyE;IACzE,OAAO,IAAIG,MAAMV,SAAS,CAAC;AAC7B;AAEA,SAASX,qBAAqBnB,kBAA0B;IACtD,OAAO2B,QAAQC,OAAO,CAAC5B;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/pathname.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\n\nimport {\n postponeWithTracking,\n type DynamicTrackingState,\n} from '../app-render/dynamic-rendering'\n\nimport {\n throwInvariantForMissingStore,\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport {\n makeDynamicHangingPromise,\n makeFallbackParamsHangingPromise,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nexport function createServerPathnameForMetadata(\n underlyingPathname: string\n): Promise<string> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderPathname(\n underlyingPathname,\n workStore,\n workUnitStore\n )\n }\n case 'prerender-client':\n case 'validation-client':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in client contexts.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerPathnameForMetadata should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime': {\n // TODO(app-shells): whether or not this is included in the shell\n // should depend on whether this route has params.\n // if there's no params, it can be included.\n // for now, we defensively exclude it to match the earlier pessimistic\n // behavior of always resolving in the runtime stage\n // (i.e. assuming that we have non-static params in the pathname)\n const { stagedRendering } = workUnitStore\n if (stagedRendering) {\n const pathnameStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.delayUntilStage(\n pathnameStage,\n undefined,\n underlyingPathname\n )\n } else {\n if (workUnitStore.isSessionShell) {\n return makeDynamicHangingPromise<string>(\n workUnitStore.renderSignal,\n workStore.route,\n '`pathname`'\n )\n } else {\n return createRenderPathname(underlyingPathname)\n }\n }\n }\n case 'request':\n // TODO(app-shells): this should be delayed if there's non-static params\n return createRenderPathname(underlyingPathname)\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createPrerenderPathname(\n underlyingPathname: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStoreLegacy\n | PrerenderStorePPR\n | PrerenderStoreModernServer\n): Promise<string> {\n switch (prerenderStore.type) {\n case 'prerender': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n // The pathname only hangs when there are fallback params, and a\n // concrete (ISR-upgraded) prerender resolves it — so this access is\n // fallback-param data for the static-prefetch hint.\n return makeFallbackParamsHangingPromise<string>(\n prerenderStore.renderSignal,\n workStore.route,\n '`pathname`',\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = prerenderStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return makeErroringPathname(workStore, prerenderStore.dynamicTracking)\n }\n break\n }\n case 'prerender-legacy':\n break\n default:\n prerenderStore satisfies never\n }\n\n // We don't have any fallback params so we have an entirely static safe params object\n return Promise.resolve(underlyingPathname)\n}\n\nfunction makeErroringPathname<T>(\n workStore: WorkStore,\n dynamicTracking: null | DynamicTrackingState\n): Promise<T> {\n let reject: null | ((reason: unknown) => void) = null\n const promise = new Promise<T>((_, re) => {\n reject = re\n })\n\n const originalThen = promise.then.bind(promise)\n\n // We instrument .then so that we can generate a tracking event only if you actually\n // await this promise, not just that it is created.\n promise.then = (onfulfilled, onrejected) => {\n if (reject) {\n try {\n postponeWithTracking(\n workStore.route,\n 'metadata relative url resolving',\n dynamicTracking\n )\n } catch (error) {\n reject(error)\n reject = null\n }\n }\n return originalThen(onfulfilled, onrejected)\n }\n\n // We wrap in a noop proxy to trick the runtime into thinking it\n // isn't a native promise (it's not really). This is so that awaiting\n // the promise will call the `then` property triggering the lazy postpone\n return new Proxy(promise, {})\n}\n\nfunction createRenderPathname(underlyingPathname: string): Promise<string> {\n return Promise.resolve(underlyingPathname)\n}\n"],"names":["createServerPathnameForMetadata","underlyingPathname","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createPrerenderPathname","stagedRendering","pathnameStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","delayUntilStage","undefined","isSessionShell","makeDynamicHangingPromise","renderSignal","route","createRenderPathname","throwInvariantForMissingStore","prerenderStore","fallbackParams","fallbackRouteParams","size","makeFallbackParamsHangingPromise","makeErroringPathname","dynamicTracking","Promise","resolve","reject","promise","_","re","originalThen","then","bind","onfulfilled","onrejected","postponeWithTracking","error","Proxy"],"mappings":";;;;+BAwBgBA;;;eAAAA;;;0CArBT;kCAKA;8CAQA;uCAKA;gCACwB;AAExB,SAASA,gCACdC,kBAA0B;IAE1B,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;gBAAoB;oBACvB,OAAOC,wBACLR,oBACAC,WACAI;gBAEJ;YACA,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAID,8BAAc,CACtB,6EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,4EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,sFADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBAAqB;oBACxB,iEAAiE;oBACjE,kDAAkD;oBAClD,4CAA4C;oBAC5C,sEAAsE;oBACtE,oDAAoD;oBACpD,iEAAiE;oBACjE,MAAM,EAAEK,eAAe,EAAE,GAAGJ;oBAC5B,IAAII,iBAAiB;wBACnB,MAAMC,gBAAgBC,iDAA0B,CAACC,eAAe;wBAChE,OAAOH,gBAAgBI,eAAe,CACpCH,eAC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B,KAAK,EACf,mCACAS;YAEJ,EAAE,OAAOa,OAAO;gBACdV,OAAOU;gBACPV,SAAS;YACX;QACF;QACA,OAAOI,aAAaG,aAAaC;IACnC;IAEA,gEAAgE;IAChE,qEAAqE;IACrE,yEAAyE;IACzE,OAAO,IAAIG,MAAMV,SAAS,CAAC;AAC7B;AAEA,SAASZ,qBAAqBnB,kBAA0B;IACtD,OAAO4B,QAAQC,OAAO,CAAC7B;AACzB","ignoreList":[0]} |
@@ -154,3 +154,3 @@ "use strict"; | ||
| if (prerenderStore.fallbackRouteParams && prerenderStore.fallbackRouteParams.has(paramName)) { | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(prerenderStore.renderSignal, workStore.route, apiName); | ||
| return (0, _dynamicrenderingutils.makeFallbackParamsHangingPromise)(prerenderStore.renderSignal, workStore.route, apiName, prerenderStore); | ||
| } | ||
@@ -157,0 +157,0 @@ break; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStorePPR\n | PrerenderStoreLegacy\n | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-ppr':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName\n )\n }\n break\n }\n case 'prerender-ppr': {\n // We aren't in a cacheComponents prerender, but the param is a fallback,\n // so we need to make an erroring params object which will postpone/error if you access it\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeErroringRootParamPromise(\n paramName,\n workStore,\n prerenderStore,\n apiName\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n\n/** Deliberately async -- we want to create a rejected promise, not error synchronously. */\nasync function makeErroringRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,\n apiName: string\n): Promise<ParamValue> {\n const expression = describeStringPropertyAccess(apiName, paramName)\n // In most dynamic APIs, we also throw if `dynamic = \"error\"`.\n // However, root params are only dynamic when we're generating a fallback shell,\n // and even with `dynamic = \"error\"` we still support generating dynamic fallback shells.\n // TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = \"error\"`\n switch (prerenderStore.type) {\n case 'prerender-ppr': {\n return postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n }\n case 'prerender-legacy': {\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n default: {\n prerenderStore satisfies never\n }\n }\n}\n"],"names":["getRootParam","paramName","apiName","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","Error","route","actionStore","actionAsyncStorage","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","accumulateRootVaryParam","prerenderStore","underlyingParams","fallbackRouteParams","has","makeHangingPromise","renderSignal","makeErroringRootParamPromise","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;gCAzBe;kCAIxB;0CAIA;8CAMA;uCAC4B;8BAEU;4CACV;4BACK;AAMjC,SAASA,aAAaC,SAAiB;IAC5C,MAAMC,UAAU,CAAC,6BAA6B,EAAED,UAAU,IAAI,CAAC;IAE/D,MAAME,YAAYC,0CAAgB,CAACC,QAAQ;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AAK;YAAoB;gBACvB,OAAOC,IAAAA,kDAAgC,EACrCJ,YACArC,WACA8B;YAEJ;QACA;YAAS;gBACPA;YACF;IACF;AACF","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/root-params.ts"],"sourcesContent":["import { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n postponeWithTracking,\n throwToInterruptStaticGeneration,\n} from '../app-render/dynamic-rendering'\nimport {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStoreModernServer,\n type PrerenderStorePPR,\n} from '../app-render/work-unit-async-storage.external'\nimport { makeFallbackParamsHangingPromise } from '../dynamic-rendering-utils'\nimport type { ParamValue } from './params'\nimport { describeStringPropertyAccess } from '../../shared/lib/utils/reflect-utils'\nimport { actionAsyncStorage } from '../app-render/action-async-storage.external'\nimport { accumulateRootVaryParam } from '../app-render/vary-params'\n\n/**\n * Used for the compiler-generated `next/root-params` module.\n * @internal\n */\nexport function getRootParam(paramName: string): Promise<ParamValue> {\n const apiName = `\\`import('next/root-params').${paramName}()\\``\n\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError(`Missing workStore in ${apiName}`)\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (!workUnitStore) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} outside of a Server Component. This is not allowed.`\n )\n }\n\n const actionStore = actionAsyncStorage.getStore()\n if (actionStore) {\n if (actionStore.isAppRoute) {\n // TODO(root-params): add support for route handlers\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.`\n )\n }\n if (actionStore.isAction && workUnitStore.phase === 'action') {\n // Actions are not fundamentally tied to a route (even if they're always submitted from some page),\n // so root params would be inconsistent if an action is called from multiple roots.\n // Make sure we check if the phase is \"action\" - we should not error in the rerender\n // after an action revalidates or updates cookies (which will still have `actionStore.isAction === true`)\n throw new Error(\n `${apiName} was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.`\n )\n }\n }\n\n switch (workUnitStore.type) {\n case 'unstable-cache': {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`unstable_cache\\`. This is not supported. Use \\`\"use cache\"\\` instead.`\n )\n }\n case 'cache': {\n if (!workUnitStore.rootParams) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`\"use cache\"\\` nested within \\`unstable_cache\\`. Root params are not available in this context.`\n )\n }\n workUnitStore.readRootParamNames.add(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n }\n case 'prerender':\n case 'prerender-ppr':\n case 'prerender-legacy': {\n return createPrerenderRootParamPromise(\n paramName,\n workStore,\n workUnitStore,\n apiName\n )\n }\n case 'validation-client':\n case 'prerender-client': {\n throw new InvariantError(\n `${apiName} must not be used within a client component. Next.js should be preventing ${apiName} from being included in client components statically, but did not in this case.`\n )\n }\n case 'request': {\n if (\n process.env.__NEXT_CACHE_COMPONENTS &&\n workUnitStore.validationSamples\n ) {\n const { assertRootParamInSamples } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n // If we error, make sure we return a rejected promise instead of erroring synchronously.\n try {\n assertRootParamInSamples(\n workStore,\n workUnitStore.validationSamples.params,\n paramName\n )\n } catch (err) {\n return Promise.reject(err)\n }\n }\n break\n }\n case 'private-cache': {\n // In dev, private caches are persisted and keyed by root params (like\n // public caches), so we track which ones were read.\n if (workUnitStore.readRootParamNames) {\n workUnitStore.readRootParamNames.add(paramName)\n }\n break\n }\n case 'prerender-runtime': {\n break\n }\n case 'generate-static-params': {\n if (!(paramName in workUnitStore.rootParams)) {\n throw new Error(\n `Route ${workStore.route} used ${apiName} inside \\`generateStaticParams\\`, but the \\`${paramName}\\` parameter was not provided by a parent \\`generateStaticParams\\`. In \\`generateStaticParams\\`, root params are only available for segments nested below the segment that provides them.`\n )\n }\n break\n }\n default: {\n workUnitStore satisfies never\n }\n }\n\n accumulateRootVaryParam(paramName)\n return Promise.resolve(workUnitStore.rootParams[paramName])\n}\n\nfunction createPrerenderRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore:\n | PrerenderStorePPR\n | PrerenderStoreLegacy\n | PrerenderStoreModernServer,\n apiName: string\n): Promise<ParamValue> {\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-legacy':\n case 'prerender-ppr':\n default:\n }\n\n const underlyingParams = prerenderStore.rootParams\n\n switch (prerenderStore.type) {\n case 'prerender': {\n // We are in a cacheComponents prerender.\n // The param is a fallback, so it should be treated as dynamic.\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeFallbackParamsHangingPromise<ParamValue>(\n prerenderStore.renderSignal,\n workStore.route,\n apiName,\n prerenderStore\n )\n }\n break\n }\n case 'prerender-ppr': {\n // We aren't in a cacheComponents prerender, but the param is a fallback,\n // so we need to make an erroring params object which will postpone/error if you access it\n if (\n prerenderStore.fallbackRouteParams &&\n prerenderStore.fallbackRouteParams.has(paramName)\n ) {\n return makeErroringRootParamPromise(\n paramName,\n workStore,\n prerenderStore,\n apiName\n )\n }\n break\n }\n case 'prerender-legacy': {\n // legacy prerenders can't have fallback params\n break\n }\n default: {\n prerenderStore satisfies never\n }\n }\n\n // If the param is not a fallback param, we just return the statically available value.\n accumulateRootVaryParam(paramName)\n return Promise.resolve(underlyingParams[paramName])\n}\n\n/** Deliberately async -- we want to create a rejected promise, not error synchronously. */\nasync function makeErroringRootParamPromise(\n paramName: string,\n workStore: WorkStore,\n prerenderStore: PrerenderStorePPR | PrerenderStoreLegacy,\n apiName: string\n): Promise<ParamValue> {\n const expression = describeStringPropertyAccess(apiName, paramName)\n // In most dynamic APIs, we also throw if `dynamic = \"error\"`.\n // However, root params are only dynamic when we're generating a fallback shell,\n // and even with `dynamic = \"error\"` we still support generating dynamic fallback shells.\n // TODO: remove this comment when cacheComponents is the default since there will be no `dynamic = \"error\"`\n switch (prerenderStore.type) {\n case 'prerender-ppr': {\n return postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n }\n case 'prerender-legacy': {\n return throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n default: {\n prerenderStore satisfies never\n }\n }\n}\n"],"names":["getRootParam","paramName","apiName","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","Error","route","actionStore","actionAsyncStorage","isAppRoute","isAction","phase","type","rootParams","readRootParamNames","add","Promise","resolve","createPrerenderRootParamPromise","process","env","__NEXT_CACHE_COMPONENTS","validationSamples","assertRootParamInSamples","require","params","err","reject","accumulateRootVaryParam","prerenderStore","underlyingParams","fallbackRouteParams","has","makeFallbackParamsHangingPromise","renderSignal","makeErroringRootParamPromise","expression","describeStringPropertyAccess","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration"],"mappings":";;;;+BAyBgBA;;;eAAAA;;;gCAzBe;kCAIxB;0CAIA;8CAMA;uCAC0C;8BAEJ;4CACV;4BACK;AAMjC,SAASA,aAAaC,SAAiB;IAC5C,MAAMC,UAAU,CAAC,6BAA6B,EAAED,UAAU,IAAI,CAAC;IAE/D,MAAME,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAAqD,CAArD,IAAIG,8BAAc,CAAC,CAAC,qBAAqB,EAAEJ,SAAS,GAApD,qBAAA;mBAAA;wBAAA;0BAAA;QAAoD;IAC5D;IAEA,MAAMK,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAI,CAACE,eAAe;QAClB,MAAM,qBAEL,CAFK,IAAIE,MACR,CAAC,MAAM,EAAEN,UAAUO,KAAK,CAAC,MAAM,EAAER,QAAQ,oDAAoD,CAAC,GAD1F,qBAAA;mBAAA;wBAAA;0BAAA;QAEN;IACF;IAEA,MAAMS,cAAcC,8CAAkB,CAACP,QAAQ;IAC/C,IAAIM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YACvC;oBACA,OAAOoC,IAAAA,uDAAgC,EACrCJ,eAAeK,YAAY,EAC3BnC,UAAUO,KAAK,EACfR,SACA+B;gBAEJ;gBACA;YACF;QACA,KAAK;YAAiB;gBACpB,yEAAyE;gBACzE,0FAA0F;gBAC1F,IACEA,eAAeE,mBAAmB,IAClCF,eAAeE,mBAAmB,CAACC,GAAG,CAACnC,YACvC;oBACA,OAAOsC,6BACLtC,WACAE,WACA8B,gBACA/B;gBAEJ;gBACA;YACF;QACA,KAAK;YAAoB;gBAEvB;YACF;QACA;YAAS;gBACP+B;YACF;IACF;IAEA,uFAAuF;IACvFD,IAAAA,mCAAuB,EAAC/B;IACxB,OAAOmB,QAAQC,OAAO,CAACa,gBAAgB,CAACjC,UAAU;AACpD;AAEA,yFAAyF,GACzF,eAAesC,6BACbtC,SAAiB,EACjBE,SAAoB,EACpB8B,cAAwD,EACxD/B,OAAe;IAEf,MAAMsC,aAAaC,IAAAA,0CAA4B,EAACvC,SAASD;IACzD,8DAA8D;IAC9D,gFAAgF;IAChF,yFAAyF;IACzF,2GAA2G;IAC3G,OAAQgC,eAAejB,IAAI;QACzB,KAAK;YAAiB;gBACpB,OAAO0B,IAAAA,sCAAoB,EACzBvC,UAAUO,KAAK,EACf8B,YACAP,eAAeU,eAAe;YAElC;QACA,KAAK;YAAoB;gBACvB,OAAOC,IAAAA,kDAAgC,EACrCJ,YACArC,WACA8B;YAEJ;QACA;YAAS;gBACPA;YACF;IACF;AACF","ignoreList":[0]} |
@@ -170,3 +170,3 @@ "use strict"; | ||
| // the promise to ensure the RSC side is considered dynamic | ||
| return (0, _dynamicrenderingutils.makeHangingPromise)(workUnitStore.renderSignal, workStore.route, '`searchParams`'); | ||
| return (0, _dynamicrenderingutils.makeRuntimeHangingPromise)(workUnitStore.renderSignal, workStore.route, '`searchParams`', workUnitStore); | ||
| case 'validation-client': | ||
@@ -306,3 +306,13 @@ throw Object.defineProperty(new _invarianterror.InvariantError('createPrerenderSearchParamsForClientPage should not be called in a client validation.'), "__NEXT_ERROR_CODE", { | ||
| } | ||
| const promise = (0, _dynamicrenderingutils.makeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`searchParams`'); | ||
| const promise = (0, _dynamicrenderingutils.makeRuntimeHangingPromise)(prerenderStore.renderSignal, workStore.route, '`searchParams`', // This promise is created for every page whether or not it reads search | ||
| // params, so recording the access at creation would mark every render. | ||
| // The access is tracked in the proxy traps below instead. | ||
| null); | ||
| const trackSearchParamsAccessed = ()=>{ | ||
| // Record against the store that's active at access time: the promise is | ||
| // created while the RSC payload is constructed, but typically accessed | ||
| // later, during the render, under a different store. | ||
| const workUnitStore = _workunitasyncstorageexternal.workUnitAsyncStorage.getStore(); | ||
| (0, _dynamicrenderingutils.trackRuntimeDataAccessed)(workUnitStore ?? prerenderStore); | ||
| }; | ||
| const proxyHandler = { | ||
@@ -325,2 +335,3 @@ get (target, prop, receiver) { | ||
| const expression = '`await searchParams`, `searchParams.then`, or similar'; | ||
| trackSearchParamsAccessed(); | ||
| (0, _dynamicrendering.annotateDynamicAccess)(expression, prerenderStore); | ||
@@ -350,2 +361,3 @@ // Mirror `makeHangingParams`: when this never-resolving promise | ||
| const expression = '`use(searchParams)`, `searchParams.status`, or similar'; | ||
| trackSearchParamsAccessed(); | ||
| (0, _dynamicrendering.annotateDynamicAccess)(expression, prerenderStore); | ||
@@ -352,0 +364,0 @@ return _reflect.ReflectAdapter.get(target, prop, receiver); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStorePPR,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeHangingPromise,\n makePromiseFromTrigger,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`'\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`'\n )\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["createPrerenderSearchParamsForClientPage","createSearchParamsFromClient","createServerSearchParamsForMetadata","createServerSearchParamsForServerPage","makeErroringSearchParamsForUseCache","underlyingSearchParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","throwInvariantForMissingStore","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","varyParamsAccumulator","createRuntimePrerenderSearchParams","forceStatic","Promise","resolve","makeHangingPromise","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","createVaryingSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","makePromiseFromTrigger","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","proxyHandler","target","prop","receiver","hasOwn","ReflectAdapter","originalMethod","args","expression","annotateDynamicAccess","dynamicAccessStore","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","throwWithStaticGenerationBailoutErrorWithDynamicError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","wellKnownProperties","has","throwForSearchParamsAccessInUseCache","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","makeDevtoolsIOAwarePromise","describeStringPropertyAccess","describeHasCheckingStringProperty","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createDedupedByCallsiteServerErrorLoggerDev","createSearchAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAkKgBA,wCAAwC;eAAxCA;;IAjHAC,4BAA4B;eAA5BA;;IAqDAC,mCAAmC;eAAnCA;;IAUAC,qCAAqC;eAArCA;;IA4YAC,mCAAmC;eAAnCA;;;0CAzfT;4BAKA;yBAEwB;kCAKxB;mDACmC;8CAYnC;gCACwB;uCAMxB;0DACqD;8BAKrD;uBAIA;AAIA,SAASH,6BACdI,sBAAoC;IAEpC,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOC,kCAAkCP,WAAWI;YACtD,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAID,8BAAc,CACtB,8EADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;YACL,KAAK;YACL,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,yEADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAIA,8BAAc,CACtB,mFADI,qBAAA;2BAAA;gCAAA;kCAAA;gBAEN;YACF,KAAK;gBAAqB;oBACxB,IAAIC,cAAcI,iBAAiB,EAAE;wBACnC,OAAOC,qCACLV,wBACAC,WACAI;oBAEJ;oBACA,OAAOM,0BAA0BX;gBACnC;YACA,KAAK;gBACH,OAAOY,yBACLZ,wBACAC,WACAI;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AAMM,aAAa0B,IAAAA,+CAAiC,EAClD,gBACAhC;oBAEFsC,kBAAkBzG,UAAUsB,KAAK,EAAEmD;gBACrC;YACF;YACA,OAAO2B,QAAQV,GAAG,CAACxB,QAAQC;QAC7B;QACAkC,SAAQnC,MAAM;YACZ,MAAMO,aAAa;YACnBgC,kBAAkBzG,UAAUsB,KAAK,EAAEmD;YACnC,OAAO2B,QAAQC,OAAO,CAACnC;QACzB;IACF;AACF;AAEA,MAAMuC,oBAAoBG,IAAAA,qFAA2C,EACnEC;AAGF,SAASA,wBACPvF,KAAyB,EACzBmD,UAAkB;IAElB,MAAMqC,SAASxF,QAAQ,CAAC,OAAO,EAAEA,MAAM,EAAE,CAAC,GAAG;IAC7C,OAAO,qBAIN,CAJM,IAAIyD,MACT,GAAG+B,OAAO,KAAK,EAAErC,WAAW,EAAE,CAAC,GAC7B,CAAC,uHAAuH,CAAC,GACzH,CAAC,8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF;AAEA,SAAShE,qCACPV,sBAAoC,EACpCC,SAAoB,EACpBI,aAAoC;QAKtBA;IAHd,MAAM,EAAEiD,iCAAiC,EAAE,GACzCC,QAAQ;IACV,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACtD,EAAAA,mCAAAA,cAAcI,iBAAiB,qBAA/BJ,iCAAiCuD,YAAY,KAAI,CAAC;IAEhE5D,yBAAyBsD,kCACvBtD,wBACAwD,cACAvD,UAAUsB,KAAK;IAEjB,OAAOJ,QAAQC,OAAO,CAACpB;AACzB","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/server/request/search-params.ts"],"sourcesContent":["import {\n workAsyncStorage,\n type WorkStore,\n} from '../app-render/work-async-storage.external'\nimport type { VaryParamsAccumulator } from '../app-render/vary-params'\nimport {\n createVaryingSearchParams,\n getMetadataVaryParamsAccumulator,\n} from '../app-render/vary-params'\n\nimport { ReflectAdapter } from '../web/spec-extension/adapters/reflect'\nimport {\n throwToInterruptStaticGeneration,\n postponeWithTracking,\n annotateDynamicAccess,\n} from '../app-render/dynamic-rendering'\nimport { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'\n\nimport {\n workUnitAsyncStorage,\n type PrerenderStoreLegacy,\n type PrerenderStorePPR,\n type PrerenderStoreModern,\n type PrerenderStoreModernRuntime,\n type StaticPrerenderStore,\n throwInvariantForMissingStore,\n type RequestStore,\n type ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport {\n makeDevtoolsIOAwarePromise,\n makeRuntimeHangingPromise,\n makePromiseFromTrigger,\n trackRuntimeDataAccessed,\n RENDER_STAGES_BY_DATA_KIND,\n} from '../dynamic-rendering-utils'\nimport { createDedupedByCallsiteServerErrorLoggerDev } from '../create-deduped-by-callsite-server-error-logger'\nimport {\n describeStringPropertyAccess,\n describeHasCheckingStringProperty,\n wellKnownProperties,\n} from '../../shared/lib/utils/reflect-utils'\nimport {\n throwWithStaticGenerationBailoutErrorWithDynamicError,\n throwForSearchParamsAccessInUseCache,\n} from './utils'\n\nexport type SearchParams = { [key: string]: string | string[] | undefined }\n\nexport function createSearchParamsFromClient(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'prerender-runtime':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createSearchParamsFromClient should not be called inside generateStaticParams.'\n )\n case 'validation-client': {\n if (workUnitStore.validationSamples) {\n return createClientSearchParamsInValidation(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n }\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\n// generateMetadata always runs in RSC context so it is equivalent to a Server Page Component\nexport function createServerSearchParamsForMetadata(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const metadataVaryParamsAccumulator = getMetadataVaryParamsAccumulator()\n return createServerSearchParamsForServerPage(\n underlyingSearchParams,\n metadataVaryParamsAccumulator\n )\n}\n\nexport function createServerSearchParamsForServerPage(\n underlyingSearchParams: SearchParams,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n return createStaticPrerenderSearchParams(workStore, workUnitStore)\n case 'validation-client':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in a client validation.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'\n )\n case 'prerender-runtime':\n return createRuntimePrerenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore,\n varyParamsAccumulator\n )\n case 'request':\n return createRenderSearchParams(\n underlyingSearchParams,\n workStore,\n workUnitStore\n )\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nexport function createPrerenderSearchParamsForClientPage(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We're prerendering in a mode that aborts (cacheComponents) and should stall\n // the promise to ensure the RSC side is considered dynamic\n return makeRuntimeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n '`searchParams`',\n workUnitStore\n )\n case 'validation-client':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a client validation.'\n )\n case 'prerender-runtime':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'\n )\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'\n )\n case 'generate-static-params':\n throw new InvariantError(\n 'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'\n )\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n return Promise.resolve({})\n default:\n workUnitStore satisfies never\n }\n }\n throwInvariantForMissingStore()\n}\n\nfunction createStaticPrerenderSearchParams(\n workStore: WorkStore,\n prerenderStore: StaticPrerenderStore\n): Promise<SearchParams> {\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n switch (prerenderStore.type) {\n case 'prerender':\n case 'prerender-client':\n // We are in a cacheComponents (PPR or otherwise) prerender\n return makeHangingSearchParams(workStore, prerenderStore)\n case 'prerender-ppr':\n case 'prerender-legacy':\n // We are in a legacy static generation and need to interrupt the\n // prerender when search params are accessed.\n return makeErroringSearchParams(workStore, prerenderStore)\n default:\n return prerenderStore satisfies never\n }\n}\n\nfunction createRuntimePrerenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: PrerenderStoreModernRuntime,\n varyParamsAccumulator: VaryParamsAccumulator | null\n): Promise<SearchParams> {\n const userspaceSearchParams =\n varyParamsAccumulator !== null\n ? createVaryingSearchParams(varyParamsAccumulator, underlyingSearchParams)\n : underlyingSearchParams\n\n const result = makeUntrackedSearchParams(userspaceSearchParams)\n const { stagedRendering } = workUnitStore\n if (!stagedRendering) {\n // If there's no staging, we're in a prospective runtime prerender.\n if (workUnitStore.isSessionShell) {\n // If we're warming up for a session shell, search params should hang,\n // because they'll be a hanging input in the final prerender.\n return makeHangingSearchParams(workStore, workUnitStore)\n }\n return result\n }\n // Unlike `createRuntimePrerenderParams`, which uses `delayUntilStage`, we\n // resolve with `waitForStage(...).then(...)` here. Switching search params to\n // `delayUntilStage` drops the source code frame from the instant-validation\n // \"URL data outside of Suspense\" error when a page awaits `searchParams` at\n // the top level (params, read via a nested component, is unaffected). See the\n // `missing suspense around search params` cases in the instant-validation\n // `suspense-boundaries` tests. The underlying reason in React's async I/O\n // await tracking isn't understood yet. TODO: align search params with params\n // on `delayUntilStage` once resolved.\n const searchParamsStage = RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n return stagedRendering.waitForStage(searchParamsStage).then(() => result)\n}\n\nfunction createRenderSearchParams(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const { asyncApiPromises, validationSamples } = requestStore\n\n if (asyncApiPromises) {\n let userspaceSearchParams = underlyingSearchParams\n if (validationSamples) {\n userspaceSearchParams = createSearchParamsProxyForInstantValidation(\n workStore,\n validationSamples,\n underlyingSearchParams\n )\n }\n\n return createStagedRenderSearchParams(\n workStore,\n asyncApiPromises,\n underlyingSearchParams,\n userspaceSearchParams\n )\n }\n\n // No staged rendering = no cacheComponents, or cacheComponents prod without cachedNavigations\n\n if (workStore.forceStatic) {\n // When using forceStatic we override all other logic and always just return an empty\n // dictionary object.\n return Promise.resolve({})\n }\n\n if (process.env.NODE_ENV === 'development') {\n // Semantically we only need the dev tracking when running in `next dev`\n // but since you would never use next dev with production NODE_ENV we use this\n // as a proxy so we can statically exclude this code from production builds.\n return makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n } else {\n return makeUntrackedSearchParams(underlyingSearchParams)\n }\n}\n\nfunction createStagedRenderSearchParams(\n workStore: WorkStore,\n asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,\n underlyingSearchParams: SearchParams,\n userspaceSearchParams: SearchParams\n): Promise<SearchParams> {\n const trigger = asyncApiPromises.sharedSearchParamsParent\n\n if (process.env.NODE_ENV === 'development') {\n // We wrap each instance of searchParams in a `new Promise()`.\n // This is important when all awaits are in third party which would otherwise\n // track all the way to the internal params.\n const promise = new Promise<SearchParams>((resolve, reject) => {\n trigger.then(() => resolve(userspaceSearchParams), reject)\n })\n // @ts-expect-error\n promise.displayName = 'searchParams'\n promise.catch(ignoreReject)\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n } else {\n return makePromiseFromTrigger(trigger, userspaceSearchParams)\n }\n}\n\nfunction createSearchParamsProxyForInstantValidation(\n workStore: WorkStore,\n validationSamples: NonNullable<RequestStore['validationSamples']>,\n underlyingSearchParams: SearchParams\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(validationSamples.searchParams ?? {})\n )\n return createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n}\n\ninterface CacheLifetime {}\nconst CachedSearchParams = new WeakMap<CacheLifetime, Promise<SearchParams>>()\n\nconst CachedSearchParamsForUseCache = new WeakMap<\n CacheLifetime,\n Promise<SearchParams>\n>()\n\nfunction makeHangingSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreModern | PrerenderStoreModernRuntime\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(prerenderStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = makeRuntimeHangingPromise<SearchParams>(\n prerenderStore.renderSignal,\n workStore.route,\n '`searchParams`',\n // This promise is created for every page whether or not it reads search\n // params, so recording the access at creation would mark every render.\n // The access is tracked in the proxy traps below instead.\n null\n )\n\n const trackSearchParamsAccessed = () => {\n // Record against the store that's active at access time: the promise is\n // created while the RSC payload is constructed, but typically accessed\n // later, during the render, under a different store.\n const workUnitStore = workUnitAsyncStorage.getStore()\n trackRuntimeDataAccessed(workUnitStore ?? prerenderStore)\n }\n\n const proxyHandler: ProxyHandler<Promise<SearchParams>> = {\n get(target, prop, receiver) {\n if (Object.hasOwn(target, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n switch (prop) {\n case 'then':\n case 'catch':\n case 'finally': {\n const originalMethod = ReflectAdapter.get(target, prop, receiver)\n return {\n [prop]: (...args: unknown[]) => {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n // Mirror `makeHangingParams`: when this never-resolving promise\n // is awaited while a `use cache` key is being encoded\n // (dynamicAccessAsyncStorage is set), abort so the surrounding\n // cache bails out to a dynamic hole instead of hanging on it.\n // Without this, a private cache that reads `searchParams` would\n // stall the App Shell cache-warming render. Re-wrapping the\n // result propagates the same behavior to promises derived via\n // `.then`/`.catch`/`.finally` that are then passed into a cache.\n const dynamicAccessStore = dynamicAccessAsyncStorage.getStore()\n if (dynamicAccessStore) {\n dynamicAccessStore.abortController.abort(\n new Error('Accessed `searchParams` during prerendering.')\n )\n }\n return new Proxy(originalMethod.apply(target, args), proxyHandler)\n },\n }[prop]\n }\n case 'status': {\n const expression =\n '`use(searchParams)`, `searchParams.status`, or similar'\n trackSearchParamsAccessed()\n annotateDynamicAccess(expression, prerenderStore)\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n default: {\n return ReflectAdapter.get(target, prop, receiver)\n }\n }\n },\n }\n\n const proxiedPromise = new Proxy(promise, proxyHandler)\n\n CachedSearchParams.set(prerenderStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeErroringSearchParams(\n workStore: WorkStore,\n prerenderStore: PrerenderStoreLegacy | PrerenderStorePPR\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const underlyingSearchParams = {}\n // For search params we don't construct a ReactPromise because we want to interrupt\n // rendering on any property access that was not set from outside and so we only want\n // to have properties like value and status if React sets them.\n const promise = Promise.resolve(underlyingSearchParams)\n\n const proxiedPromise = new Proxy(promise, {\n get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it.\n // We know it isn't a dynamic access because it can only be something\n // that was previously written to the promise and thus not an underlying searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (typeof prop === 'string' && prop === 'then') {\n const expression =\n '`await searchParams`, `searchParams.then`, or similar'\n if (workStore.dynamicShouldError) {\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n } else if (prerenderStore.type === 'prerender-ppr') {\n // PPR Prerender (no cacheComponents)\n postponeWithTracking(\n workStore.route,\n expression,\n prerenderStore.dynamicTracking\n )\n } else {\n // Legacy Prerender\n throwToInterruptStaticGeneration(\n expression,\n workStore,\n prerenderStore\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParams.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\n/**\n * This is a variation of `makeErroringSearchParams` that always throws an\n * error on access, because accessing searchParams inside of `\"use cache\"` is\n * not allowed.\n */\nexport function makeErroringSearchParamsForUseCache(): Promise<SearchParams> {\n const workStore = workAsyncStorage.getStore()\n if (!workStore) {\n throw new InvariantError('Expected workStore to be initialized')\n }\n const cachedSearchParams = CachedSearchParamsForUseCache.get(workStore)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve({})\n\n const proxiedPromise = new Proxy(promise, {\n get: function get(target, prop, receiver) {\n if (Object.hasOwn(promise, prop)) {\n // The promise has this property directly. we must return it. We know it\n // isn't a dynamic access because it can only be something that was\n // previously written to the promise and thus not an underlying\n // searchParam value\n return ReflectAdapter.get(target, prop, receiver)\n }\n\n if (\n typeof prop === 'string' &&\n (prop === 'then' || !wellKnownProperties.has(prop))\n ) {\n throwForSearchParamsAccessInUseCache(workStore, get)\n }\n\n return ReflectAdapter.get(target, prop, receiver)\n },\n })\n\n CachedSearchParamsForUseCache.set(workStore, proxiedPromise)\n return proxiedPromise\n}\n\nfunction makeUntrackedSearchParams(\n underlyingSearchParams: SearchParams\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n\n const promise = Promise.resolve(underlyingSearchParams)\n CachedSearchParams.set(underlyingSearchParams, promise)\n\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const cachedSearchParams = CachedSearchParams.get(underlyingSearchParams)\n if (cachedSearchParams) {\n return cachedSearchParams\n }\n const promise = makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams,\n workStore,\n requestStore\n )\n CachedSearchParams.set(requestStore, promise)\n return promise\n}\n\nfunction makeUntrackedSearchParamsWithDevWarningsImpl(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n requestStore: RequestStore\n): Promise<SearchParams> {\n const promiseInitialized = { current: false }\n const proxiedUnderlying = instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams,\n workStore,\n promiseInitialized\n )\n\n const promise = makeDevtoolsIOAwarePromise(\n proxiedUnderlying,\n requestStore,\n RENDER_STAGES_BY_DATA_KIND.runtimeLinkData\n )\n\n promise.then(\n () => {\n promiseInitialized.current = true\n },\n // If we're in staged rendering, this promise will reject if the render\n // is aborted before it can reach the runtime stage.\n // In that case, we have to prevent an unhandled rejection from the promise\n // created by this `.then()` call.\n // This does not affect the `promiseInitialized` logic above,\n // because `proxiedUnderlying` will not be used to resolve the promise,\n // so there's no risk of any of its properties being accessed and triggering\n // an undesireable warning.\n ignoreReject\n )\n\n return instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams,\n promise,\n workStore\n )\n}\n\nfunction ignoreReject() {}\n\nfunction instrumentSearchParamsObjectWithDevWarnings(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n promiseInitialized: { current: boolean }\n) {\n // We have an unfortunate sequence of events that requires this initialization logic. We want to instrument the underlying\n // searchParams object to detect if you are accessing values in dev. This is used for warnings and for things like the static prerender\n // indicator. However when we pass this proxy to our Promise.resolve() below the VM checks if the resolved value is a promise by looking\n // at the `.then` property. To our dynamic tracking logic this is indistinguishable from a `then` searchParam and so we would normally trigger\n // dynamic tracking. However we know that this .then is not real dynamic access, it's just how thenables resolve in sequence. So we introduce\n // this initialization concept so we omit the dynamic check until after we've constructed our resolved promise.\n return new Proxy(underlyingSearchParams, {\n get(target, prop, receiver) {\n if (typeof prop === 'string' && promiseInitialized.current) {\n if (workStore.dynamicShouldError) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (workStore.dynamicShouldError) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n if (workStore.dynamicShouldError) {\n const expression =\n '`{...searchParams}`, `Object.keys(searchParams)`, or similar'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n return Reflect.ownKeys(target)\n },\n })\n}\n\nfunction instrumentSearchParamsPromiseWithDevWarnings(\n underlyingSearchParams: SearchParams,\n promise: Promise<SearchParams>,\n workStore: WorkStore\n) {\n // Track which properties we should warn for.\n const proxiedProperties = new Set<string>()\n\n Object.keys(underlyingSearchParams).forEach((prop) => {\n if (wellKnownProperties.has(prop)) {\n // These properties cannot be shadowed because they need to be the\n // true underlying value for Promises to work correctly at runtime\n } else {\n proxiedProperties.add(prop)\n }\n })\n\n return new Proxy(promise, {\n get(target, prop, receiver) {\n if (prop === 'then' && workStore.dynamicShouldError) {\n const expression = '`searchParams.then`'\n throwWithStaticGenerationBailoutErrorWithDynamicError(\n workStore.route,\n expression\n )\n }\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeStringPropertyAccess('searchParams', prop)\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return ReflectAdapter.get(target, prop, receiver)\n },\n set(target, prop, value, receiver) {\n if (typeof prop === 'string') {\n proxiedProperties.delete(prop)\n }\n return Reflect.set(target, prop, value, receiver)\n },\n has(target, prop) {\n if (typeof prop === 'string') {\n if (\n !wellKnownProperties.has(prop) &&\n (proxiedProperties.has(prop) ||\n // We are accessing a property that doesn't exist on the promise nor\n // the underlying searchParams.\n Reflect.has(target, prop) === false)\n ) {\n const expression = describeHasCheckingStringProperty(\n 'searchParams',\n prop\n )\n warnForSyncAccess(workStore.route, expression)\n }\n }\n return Reflect.has(target, prop)\n },\n ownKeys(target) {\n const expression = '`Object.keys(searchParams)` or similar'\n warnForSyncAccess(workStore.route, expression)\n return Reflect.ownKeys(target)\n },\n })\n}\n\nconst warnForSyncAccess = createDedupedByCallsiteServerErrorLoggerDev(\n createSearchAccessError\n)\n\nfunction createSearchAccessError(\n route: string | undefined,\n expression: string\n) {\n const prefix = route ? `Route \"${route}\" ` : 'This route '\n return new Error(\n `${prefix}used ${expression}. ` +\n `\\`searchParams\\` is a Promise and must be unwrapped with \\`await\\` or \\`React.use()\\` before accessing its properties. ` +\n `Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis`\n )\n}\n\nfunction createClientSearchParamsInValidation(\n underlyingSearchParams: SearchParams,\n workStore: WorkStore,\n workUnitStore: ValidationStoreClient\n) {\n const { createExhaustiveSearchParamsProxy } =\n require('../app-render/instant-validation/instant-samples') as typeof import('../app-render/instant-validation/instant-samples')\n const declaredKeys = new Set(\n Object.keys(workUnitStore.validationSamples?.searchParams ?? {})\n )\n underlyingSearchParams = createExhaustiveSearchParamsProxy(\n underlyingSearchParams,\n declaredKeys,\n workStore.route\n )\n return Promise.resolve(underlyingSearchParams)\n}\n"],"names":["createPrerenderSearchParamsForClientPage","createSearchParamsFromClient","createServerSearchParamsForMetadata","createServerSearchParamsForServerPage","makeErroringSearchParamsForUseCache","underlyingSearchParams","workStore","workAsyncStorage","getStore","InvariantError","workUnitStore","workUnitAsyncStorage","type","createStaticPrerenderSearchParams","validationSamples","createClientSearchParamsInValidation","makeUntrackedSearchParams","createRenderSearchParams","throwInvariantForMissingStore","metadataVaryParamsAccumulator","getMetadataVaryParamsAccumulator","varyParamsAccumulator","createRuntimePrerenderSearchParams","forceStatic","Promise","resolve","makeRuntimeHangingPromise","renderSignal","route","prerenderStore","makeHangingSearchParams","makeErroringSearchParams","userspaceSearchParams","createVaryingSearchParams","result","stagedRendering","isSessionShell","searchParamsStage","RENDER_STAGES_BY_DATA_KIND","runtimeLinkData","waitForStage","then","requestStore","asyncApiPromises","createSearchParamsProxyForInstantValidation","createStagedRenderSearchParams","process","env","NODE_ENV","makeUntrackedSearchParamsWithDevWarnings","trigger","sharedSearchParamsParent","promise","reject","displayName","catch","ignoreReject","instrumentSearchParamsPromiseWithDevWarnings","makePromiseFromTrigger","createExhaustiveSearchParamsProxy","require","declaredKeys","Set","Object","keys","searchParams","CachedSearchParams","WeakMap","CachedSearchParamsForUseCache","cachedSearchParams","get","trackSearchParamsAccessed","trackRuntimeDataAccessed","proxyHandler","target","prop","receiver","hasOwn","ReflectAdapter","originalMethod","args","expression","annotateDynamicAccess","dynamicAccessStore","dynamicAccessAsyncStorage","abortController","abort","Error","Proxy","apply","proxiedPromise","set","dynamicShouldError","throwWithStaticGenerationBailoutErrorWithDynamicError","postponeWithTracking","dynamicTracking","throwToInterruptStaticGeneration","wellKnownProperties","has","throwForSearchParamsAccessInUseCache","makeUntrackedSearchParamsWithDevWarningsImpl","promiseInitialized","current","proxiedUnderlying","instrumentSearchParamsObjectWithDevWarnings","makeDevtoolsIOAwarePromise","describeStringPropertyAccess","describeHasCheckingStringProperty","Reflect","ownKeys","proxiedProperties","forEach","add","warnForSyncAccess","value","delete","createDedupedByCallsiteServerErrorLoggerDev","createSearchAccessError","prefix"],"mappings":";;;;;;;;;;;;;;;;;;IAmKgBA,wCAAwC;eAAxCA;;IAjHAC,4BAA4B;eAA5BA;;IAqDAC,mCAAmC;eAAnCA;;IAUAC,qCAAqC;eAArCA;;IA2ZAC,mCAAmC;eAAnCA;;;0CAzgBT;4BAKA;yBAEwB;kCAKxB;mDACmC;8CAYnC;gCACwB;uCAOxB;0DACqD;8BAKrD;uBAIA;AAIA,SAASH,6BACdI,sBAAoC;IAEpC,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAC3C,IAAI,CAACF,WAAW;QACd,MAAM,qBAA0D,CAA1D,IAAIG,8BAAc,CAAC,yCAAnB,qBAAA;mBAAA;wBAAA;0BAAA;QAAyD;IACjE;IACA,MAAMC,gBAAgBC,kDAAoB,CAACH,QAAQ;IACnD,IAAIE,eAAe;QACjB,OAAQA,cAAcE,IAAI;YACxB,KAAK;YACL,KAAK;YACL,KAAK;YACL,KAAK;gBACH,OAAOC,kCAAkCP,WAAWI;YACtD,KAAK;gBACH,MAAM,qBAEL,CAFK,IAAID,8BAAc,CACtB,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8DAA8D,CAAC,GAH7D,qBAAA;eAAA;oBAAA;sBAAA;IAIP;AACF;AAEA,SAASlE,qCACPV,sBAAoC,EACpCC,SAAoB,EACpBI,aAAoC;QAKtBA;IAHd,MAAM,EAAEiD,iCAAiC,EAAE,GACzCC,QAAQ;IACV,MAAMC,eAAe,IAAIC,IACvBC,OAAOC,IAAI,CAACtD,EAAAA,mCAAAA,cAAcI,iBAAiB,qBAA/BJ,iCAAiCuD,YAAY,KAAI,CAAC;IAEhE5D,yBAAyBsD,kCACvBtD,wBACAwD,cACAvD,UAAUsB,KAAK;IAEjB,OAAOJ,QAAQC,OAAO,CAACpB;AACzB","ignoreList":[0]} |
@@ -312,3 +312,6 @@ "use strict"; | ||
| hmrRefreshHash: undefined, | ||
| varyParamsAccumulator: null | ||
| varyParamsAccumulator: null, | ||
| runtimeDataAccessed: null, | ||
| shouldAttemptStaticPrefetch: null, | ||
| isFallbackUpgradeable: false | ||
| }; | ||
@@ -386,3 +389,6 @@ let prospectiveResult; | ||
| hmrRefreshHash: undefined, | ||
| varyParamsAccumulator: null | ||
| varyParamsAccumulator: null, | ||
| runtimeDataAccessed: null, | ||
| shouldAttemptStaticPrefetch: null, | ||
| isFallbackUpgradeable: false | ||
| }; | ||
@@ -389,0 +395,0 @@ let responseHandled = false; |
@@ -142,3 +142,4 @@ /** | ||
| SubtreeHasEagerPrefetch = 4096, | ||
| SubtreeHasInstantFalse = 8192 | ||
| SubtreeHasInstantFalse = 8192, | ||
| ShouldAttemptStaticPrefetch = 16384 | ||
| } | ||
@@ -280,2 +281,23 @@ /** | ||
| s?: AsyncIterable<number>; | ||
| /** | ||
| * runtimeDataAccessed — whether the render has accessed a data source that | ||
| * hangs during a static prerender but would resolve during a runtime | ||
| * prerender (cookies, headers, fallback params, searchParams, ...). The | ||
| * flag is monotonic (false → true, at most once), so it's encoded as a | ||
| * promise: resolved `true` at the moment of first access — the fulfillment | ||
| * row's position in the stream records the stage the access happened in — | ||
| * or resolved `false` when the prerender completes without one, a row that | ||
| * lands past every stage boundary. A truncated (shell) decode therefore | ||
| * reads the answer as of the shell stage: fulfilled `true` iff the access | ||
| * happened during a stage it includes, pending (⇒ no access) otherwise. | ||
| * Unlike an async iterable, a pending promise costs Flight no abort | ||
| * listener on the render. Used when generating per-segment prefetch | ||
| * responses (forwarded as the response-level `needsRuntimeRequest`). | ||
| * The build-constant `PrefetchHint.ShouldAttemptStaticPrefetch` is | ||
| * tracked directly on the prerender store instead (its | ||
| * `shouldAttemptStaticPrefetch` cell) — it needs neither stream | ||
| * positioning nor this flag's param/non-param blindness. Only present | ||
| * for static prerenders when Cache Components is enabled. | ||
| */ | ||
| u?: Promise<boolean>; | ||
| /** staticStageByteLength - Resolves when the static stage ends. */ | ||
@@ -282,0 +304,0 @@ l?: Promise<number>; |
@@ -93,2 +93,24 @@ /** | ||
| PrefetchHint[PrefetchHint["SubtreeHasInstantFalse"] = 8192] = "SubtreeHasInstantFalse"; | ||
| // The client should attempt a static prefetch for this route: the | ||
| // build-time prerender did not access any runtime data (cookies, headers, | ||
| // searchParams, ...), so a static prefetch is expected to be as complete | ||
| // as a runtime one. A fallback-param access only unsets the bit when the | ||
| // route can never be upgraded from a fallback to a concrete prerender — | ||
| // on an upgradeable route, ISR later produces the concrete prerender a | ||
| // static attempt would hit (until then, the static responses' own | ||
| // signal reports the insufficiency per response). Purely advisory, and | ||
| // both error directions are safe: if set when a runtime request is | ||
| // actually needed, that same response-level signal (the load-bearing | ||
| // `needsRuntimeRequest` promise combined with each segment's `isPartial`) | ||
| // directs the client to follow up — the cost is a wasted static attempt. | ||
| // If unset when static would have sufficed, the client goes straight to a | ||
| // runtime prefetch, which is a superset of the static response — the cost | ||
| // is only reduced cacheability. Like the other bits, this one is computed | ||
| // once per build and stays constant for the build's lifetime; it rides | ||
| // the prefetch-hints manifest into every response that carries hints — | ||
| // `/_tree` prefetch responses and the FlightRouterState of dynamic | ||
| // navigations alike. (Routes missing from the manifest — see the #91407 | ||
| // fallbacks — simply never carry it.) Set on every node of the tree, but | ||
| // does not propagate. | ||
| PrefetchHint[PrefetchHint["ShouldAttemptStaticPrefetch"] = 16384] = "ShouldAttemptStaticPrefetch"; | ||
| return PrefetchHint; | ||
@@ -95,0 +117,0 @@ }({}); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"sources":["../../../src/shared/lib/app-router-types.ts"],"sourcesContent":["/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type { VaryParamsIterable } from './segment-cache/vary-params-decoding'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Cache node used in app-router / layout-router.\n */\n\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n prefetchHead: HeadData | null\n\n head: HeadData\n\n slots: Record<string, CacheNode> | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n\n /**\n * Globally-unique identifier minted from a monotonic counter when the\n * CacheNode is freshly created. Surfaced to user code as a string via\n * `useRouter().bfcacheId` and intended to be used as a React `key` to\n * opt out of Activity-based state preservation on fresh navigations.\n *\n * Preserved when the CacheNode is reused (shared layouts, refresh,\n * search/hash-only navigations) or restored from the BFCache during a\n * back/forward navigation.\n */\n bfcacheId: number\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and runtime prefetch\n * hints. Only set when non-zero.\n */\n prefetchHints?: number,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // This segment has a runtime prefetch enabled (via instant with\n // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.\n HasRuntimePrefetch = 0b00001,\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when a\n // truthy instant config is present, or `prefetch` is 'partial',\n // 'unstable_eager', or 'allow-runtime'. Propagates upward so the root segment\n // reflects the entire subtree.\n SubtreeHasPartialPrefetching = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n IsRootLayoutOrAbove = 0b10000,\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n ParentInlinedIntoSelf = 0b100000,\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // at the end of its SegmentPrefetch[] array.\n HeadInlinedIntoSelf = 0b10000000,\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n HeadOutlined = 0b100000000,\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n InliningHintsStale = 0b1000000000,\n // This segment has instant = false, opting out of all\n // prefetching entirely (neither static nor runtime).\n PrefetchDisabled = 0b10000000000,\n // This segment or one of its descendants has runtime prefetch enabled\n // (HasRuntimePrefetch). Propagates upward so the root reflects the\n // entire subtree.\n SubtreeHasRuntimePrefetch = 0b100000000000,\n // This segment or one of its descendants prefetches \"eagerly\" — i.e. its\n // effective prefetch strategy is anything other than 'partial' or\n // 'allow-runtime'. Used by App Shells: a non-eager subtree relies on the\n // shared app shell and skips its Speculative prefetch. Propagates upward so\n // the root reflects the entire subtree.\n SubtreeHasEagerPrefetch = 0b1000000000000,\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n SubtreeHasInstantFalse = 0b10000000000000,\n}\n\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped. Matches\n * if EITHER bit is set — i.e. the segment uses runtime prefetching\n * (HasRuntimePrefetch) OR prefetching is disabled entirely (PrefetchDisabled,\n * e.g. instant = false). The segment participates in the bundle chain\n * but with null data.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */\nexport const StaticPrefetchDisabled =\n PrefetchHint.HasRuntimePrefetch | PrefetchHint.PrefetchDisabled\n\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */\nexport const SubtreePrefetchHints =\n PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasLoadingBoundary |\n PrefetchHint.SubtreeHasRuntimePrefetch |\n PrefetchHint.SubtreeHasInstantFalse |\n PrefetchHint.SubtreeHasEagerPrefetch\n\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading boundary,\n * or it has a runtime prefetch) becomes the corresponding \"subtree\" flag on the\n * parent, so the root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a prefetch tree (createFlightRouterStateFromLoaderTree) and on the client when\n * merging a navigation patch into the existing tree (convertServerPatchToFullTree).\n * Keep these in sync by routing both through this helper.\n */\nexport function propagateSubtreeBits(\n parentHints: number,\n childHints: number\n): number {\n if (childHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n parentHints |= PrefetchHint.SubtreeHasPartialPrefetching\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (\n childHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)\n ) {\n parentHints |= PrefetchHint.SubtreeHasLoadingBoundary\n }\n // Likewise for runtime prefetch.\n if (\n childHints &\n (PrefetchHint.HasRuntimePrefetch | PrefetchHint.SubtreeHasRuntimePrefetch)\n ) {\n parentHints |= PrefetchHint.SubtreeHasRuntimePrefetch\n }\n // And for eager prefetch. The bit is set directly on each eager segment, so\n // there's no separate segment-local flag — propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasEagerPrefetch) {\n parentHints |= PrefetchHint.SubtreeHasEagerPrefetch\n }\n // And for `instant = false`. Like eager prefetch, the bit is set directly on\n // each opted-out segment, so propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasInstantFalse) {\n parentHints |= PrefetchHint.SubtreeHasInstantFalse\n }\n return parentHints\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n // TODO: This field is no longer used. Remove it.\n loading: null,\n isPartial: boolean,\n /**\n * An AsyncIterable that yields the route params this segment accessed during\n * server rendering (one name per yield, deduped). Used by the client router\n * to determine cache key specificity - segments that only access certain\n * params can be reused across navigations where unaccessed params change.\n *\n * Does NOT include root params; those are emitted once at the top level of\n * the response (see `r` on the payload) and unioned in by the consumer.\n *\n * - null: tracking was not enabled for this render (e.g., not a prerender).\n * Treat conservatively - assume all params vary.\n * - Drains to empty Set: segment accesses no params (e.g., client components,\n * or server components that don't read params). Can be shared across all\n * param values.\n * - Drains to non-empty Set: segment depends on those params. Can only reuse\n * when those specific params match.\n */\n varyParams: VaryParamsIterable | null,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array<FlightDataPath> | string\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record<string, PrefetchHints> | null\n}\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * headVaryParams - vary params for the head (metadata) of the response.\n * Does not include root params (see `r`).\n */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params, rather than the server folding them into each set.\n */\n r?: VaryParamsIterable\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** supportsPerSegmentPrefetching */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** staleTime - Only present in dynamic runtime prefetch responses. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /**\n * shellUsedSessionData - true if resolving session data\n * unblocked new content in the shell.\n * NOTE: only use this in runtime/session prefetch requests\n * where we have a proper session shell.\n * */\n u?: Promise<boolean>\n /** headVaryParams. Does not include root params (see `r`). */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params.\n */\n r?: VaryParamsIterable\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n\nexport type InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n"],"names":["PrefetchHint","StaticPrefetchDisabled","SubtreePrefetchHints","propagateSubtreeBits","parentHints","childHints"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;;;;;;;IAiLiBA,YAAY;eAAZA;;IAoELC,sBAAsB;eAAtBA;;IASAC,oBAAoB;eAApBA;;IAkBGC,oBAAoB;eAApBA;;;AA/FT,IAAA,AAAWH,sCAAAA;IAChB,gEAAgE;IAChE,2EAA2E;;IAE3E,6EAA6E;IAC7E,wEAAwE;IACxE,gEAAgE;IAChE,8EAA8E;IAC9E,+BAA+B;;IAE/B,kDAAkD;;IAElD,sEAAsE;IACtE,6DAA6D;;IAE7D,8EAA8E;IAC9E,2EAA2E;IAC3E,8BAA8B;;IAE9B,sEAAsE;IACtE,0DAA0D;;IAE1D,wEAAwE;IACxE,yEAAyE;;IAEzE,4EAA4E;IAC5E,6CAA6C;;IAE7C,wEAAwE;IACxE,4EAA4E;;IAE5E,oEAAoE;IACpE,0EAA0E;IAC1E,0EAA0E;IAC1E,kEAAkE;IAClE,0EAA0E;IAC1E,oBAAoB;;IAEpB,sDAAsD;IACtD,qDAAqD;;IAErD,sEAAsE;IACtE,mEAAmE;IACnE,kBAAkB;;IAElB,yEAAyE;IACzE,kEAAkE;IAClE,yEAAyE;IACzE,4EAA4E;IAC5E,wCAAwC;;IAExC,oEAAoE;IACpE,8EAA8E;IAC9E,kEAAkE;IAClE,+EAA+E;IAC/E,mCAAmC;;WAvDnBA;;AAoEX,MAAMC,yBACXD;AAQK,MAAME,uBACXF;AAiBK,SAASG,qBACdC,WAAmB,EACnBC,UAAkB;IAElB,IAAIA,gBAAwD;QAC1DD;IACF;IACA,+EAA+E;IAC/E,kDAAkD;IAClD,IACEC,aACCL,CAAAA,KACsC,GACvC;QACAI;IACF;IACA,iCAAiC;IACjC,IACEC,aACCL,CAAAA,QAAuE,GACxE;QACAI;IACF;IACA,4EAA4E;IAC5E,+DAA+D;IAC/D,IAAIC,mBAAmD;QACrDD;IACF;IACA,6EAA6E;IAC7E,iDAAiD;IACjD,IAAIC,mBAAkD;QACpDD;IACF;IACA,OAAOA;AACT","ignoreList":[0]} | ||
| {"version":3,"sources":["../../../src/shared/lib/app-router-types.ts"],"sourcesContent":["/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type { VaryParamsIterable } from './segment-cache/vary-params-decoding'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Cache node used in app-router / layout-router.\n */\n\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n prefetchHead: HeadData | null\n\n head: HeadData\n\n slots: Record<string, CacheNode> | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n\n /**\n * Globally-unique identifier minted from a monotonic counter when the\n * CacheNode is freshly created. Surfaced to user code as a string via\n * `useRouter().bfcacheId` and intended to be used as a React `key` to\n * opt out of Activity-based state preservation on fresh navigations.\n *\n * Preserved when the CacheNode is reused (shared layouts, refresh,\n * search/hash-only navigations) or restored from the BFCache during a\n * back/forward navigation.\n */\n bfcacheId: number\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and runtime prefetch\n * hints. Only set when non-zero.\n */\n prefetchHints?: number,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // This segment has a runtime prefetch enabled (via instant with\n // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.\n HasRuntimePrefetch = 0b00001,\n // This segment or one of its descendants opts into Partial Prefetching, i.e.\n // uses the two-phase (Shell then Speculative) prefetch flow. Set when a\n // truthy instant config is present, or `prefetch` is 'partial',\n // 'unstable_eager', or 'allow-runtime'. Propagates upward so the root segment\n // reflects the entire subtree.\n SubtreeHasPartialPrefetching = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is at or above the application's root layout — the root layout\n // segment itself and all of its ancestors. A dynamic param in one of these\n // segments is a \"root param\".\n IsRootLayoutOrAbove = 0b10000,\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n ParentInlinedIntoSelf = 0b100000,\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // at the end of its SegmentPrefetch[] array.\n HeadInlinedIntoSelf = 0b10000000,\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n HeadOutlined = 0b100000000,\n // The inlining hints in this tree may be stale because the tree was\n // generated before collectPrefetchHints ran (e.g. the initial RSC payload\n // for a fully static page at build time). When writing this tree into the\n // cache, the route entry should be immediately expired so it gets\n // re-fetched with correct hints. Only set during build-time prerendering,\n // never at runtime.\n InliningHintsStale = 0b1000000000,\n // This segment has instant = false, opting out of all\n // prefetching entirely (neither static nor runtime).\n PrefetchDisabled = 0b10000000000,\n // This segment or one of its descendants has runtime prefetch enabled\n // (HasRuntimePrefetch). Propagates upward so the root reflects the\n // entire subtree.\n SubtreeHasRuntimePrefetch = 0b100000000000,\n // This segment or one of its descendants prefetches \"eagerly\" — i.e. its\n // effective prefetch strategy is anything other than 'partial' or\n // 'allow-runtime'. Used by App Shells: a non-eager subtree relies on the\n // shared app shell and skips its Speculative prefetch. Propagates upward so\n // the root reflects the entire subtree.\n SubtreeHasEagerPrefetch = 0b1000000000000,\n // This segment or one of its descendants exports `instant = false`,\n // explicitly opting out of Partial Prefetching. Propagates upward so the root\n // reflects the entire subtree. Used only to suppress the dev-time\n // `<Link prefetch={true}>` warning — unlike PrefetchDisabled, it has no effect\n // on the actual prefetch behavior.\n SubtreeHasInstantFalse = 0b10000000000000,\n // The client should attempt a static prefetch for this route: the\n // build-time prerender did not access any runtime data (cookies, headers,\n // searchParams, ...), so a static prefetch is expected to be as complete\n // as a runtime one. A fallback-param access only unsets the bit when the\n // route can never be upgraded from a fallback to a concrete prerender —\n // on an upgradeable route, ISR later produces the concrete prerender a\n // static attempt would hit (until then, the static responses' own\n // signal reports the insufficiency per response). Purely advisory, and\n // both error directions are safe: if set when a runtime request is\n // actually needed, that same response-level signal (the load-bearing\n // `needsRuntimeRequest` promise combined with each segment's `isPartial`)\n // directs the client to follow up — the cost is a wasted static attempt.\n // If unset when static would have sufficed, the client goes straight to a\n // runtime prefetch, which is a superset of the static response — the cost\n // is only reduced cacheability. Like the other bits, this one is computed\n // once per build and stays constant for the build's lifetime; it rides\n // the prefetch-hints manifest into every response that carries hints —\n // `/_tree` prefetch responses and the FlightRouterState of dynamic\n // navigations alike. (Routes missing from the manifest — see the #91407\n // fallbacks — simply never carry it.) Set on every node of the tree, but\n // does not propagate.\n ShouldAttemptStaticPrefetch = 0b100000000000000,\n}\n\n/**\n * Bitmask for checking whether a segment's static prefetch is skipped. Matches\n * if EITHER bit is set — i.e. the segment uses runtime prefetching\n * (HasRuntimePrefetch) OR prefetching is disabled entirely (PrefetchDisabled,\n * e.g. instant = false). The segment participates in the bundle chain\n * but with null data.\n *\n * Usage: `(hints & StaticPrefetchDisabled) !== 0`\n */\nexport const StaticPrefetchDisabled =\n PrefetchHint.HasRuntimePrefetch | PrefetchHint.PrefetchDisabled\n\n/**\n * The subset of PrefetchHint bits that propagate upward from a child segment to\n * its ancestors (as opposed to segment-local bits like SegmentHasLoadingBoundary\n * or IsRootLayoutOrAbove). Used to clear stale propagated bits before re-deriving them\n * from a node's children.\n */\nexport const SubtreePrefetchHints =\n PrefetchHint.SubtreeHasPartialPrefetching |\n PrefetchHint.SubtreeHasLoadingBoundary |\n PrefetchHint.SubtreeHasRuntimePrefetch |\n PrefetchHint.SubtreeHasInstantFalse |\n PrefetchHint.SubtreeHasEagerPrefetch\n\n/**\n * Folds a child segment's prefetch hints into its parent's, propagating the\n * \"subtree\" flags. A child's segment-local flag (e.g. it has a loading boundary,\n * or it has a runtime prefetch) becomes the corresponding \"subtree\" flag on the\n * parent, so the root segment ends up reflecting the entire subtree.\n *\n * Used wherever a route tree is assembled bottom-up: on the server when building\n * a prefetch tree (createFlightRouterStateFromLoaderTree) and on the client when\n * merging a navigation patch into the existing tree (convertServerPatchToFullTree).\n * Keep these in sync by routing both through this helper.\n */\nexport function propagateSubtreeBits(\n parentHints: number,\n childHints: number\n): number {\n if (childHints & PrefetchHint.SubtreeHasPartialPrefetching) {\n parentHints |= PrefetchHint.SubtreeHasPartialPrefetching\n }\n // A child with a loading boundary (directly, or anywhere in its subtree) makes\n // this a SubtreeHasLoadingBoundary on the parent.\n if (\n childHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)\n ) {\n parentHints |= PrefetchHint.SubtreeHasLoadingBoundary\n }\n // Likewise for runtime prefetch.\n if (\n childHints &\n (PrefetchHint.HasRuntimePrefetch | PrefetchHint.SubtreeHasRuntimePrefetch)\n ) {\n parentHints |= PrefetchHint.SubtreeHasRuntimePrefetch\n }\n // And for eager prefetch. The bit is set directly on each eager segment, so\n // there's no separate segment-local flag — propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasEagerPrefetch) {\n parentHints |= PrefetchHint.SubtreeHasEagerPrefetch\n }\n // And for `instant = false`. Like eager prefetch, the bit is set directly on\n // each opted-out segment, so propagate it as-is.\n if (childHints & PrefetchHint.SubtreeHasInstantFalse) {\n parentHints |= PrefetchHint.SubtreeHasInstantFalse\n }\n return parentHints\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n // TODO: This field is no longer used. Remove it.\n loading: null,\n isPartial: boolean,\n /**\n * An AsyncIterable that yields the route params this segment accessed during\n * server rendering (one name per yield, deduped). Used by the client router\n * to determine cache key specificity - segments that only access certain\n * params can be reused across navigations where unaccessed params change.\n *\n * Does NOT include root params; those are emitted once at the top level of\n * the response (see `r` on the payload) and unioned in by the consumer.\n *\n * - null: tracking was not enabled for this render (e.g., not a prerender).\n * Treat conservatively - assume all params vary.\n * - Drains to empty Set: segment accesses no params (e.g., client components,\n * or server components that don't read params). Can be shared across all\n * param values.\n * - Drains to non-empty Set: segment depends on those params. Can only reuse\n * when those specific params match.\n */\n varyParams: VaryParamsIterable | null,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array<FlightDataPath> | string\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record<string, PrefetchHints> | null\n}\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * headVaryParams - vary params for the head (metadata) of the response.\n * Does not include root params (see `r`).\n */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params, rather than the server folding them into each set.\n */\n r?: VaryParamsIterable\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable<number>\n /**\n * runtimeDataAccessed — whether the render has accessed a data source that\n * hangs during a static prerender but would resolve during a runtime\n * prerender (cookies, headers, fallback params, searchParams, ...). The\n * flag is monotonic (false → true, at most once), so it's encoded as a\n * promise: resolved `true` at the moment of first access — the fulfillment\n * row's position in the stream records the stage the access happened in —\n * or resolved `false` when the prerender completes without one, a row that\n * lands past every stage boundary. A truncated (shell) decode therefore\n * reads the answer as of the shell stage: fulfilled `true` iff the access\n * happened during a stage it includes, pending (⇒ no access) otherwise.\n * Unlike an async iterable, a pending promise costs Flight no abort\n * listener on the render. Used when generating per-segment prefetch\n * responses (forwarded as the response-level `needsRuntimeRequest`).\n * The build-constant `PrefetchHint.ShouldAttemptStaticPrefetch` is\n * tracked directly on the prerender store instead (its\n * `shouldAttemptStaticPrefetch` cell) — it needs neither stream\n * positioning nor this flag's param/non-param blindness. Only present\n * for static prerenders when Cache Components is enabled.\n */\n u?: Promise<boolean>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** supportsPerSegmentPrefetching */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** staleTime - Only present in dynamic runtime prefetch responses. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /**\n * shellByteLength - Resolves when the shell stage ends.\n * If it resolves to null, then the shell is the same as the main response.\n * */\n a?: Promise<number | null>\n /**\n * shellUsedSessionData - true if resolving session data\n * unblocked new content in the shell.\n * NOTE: only use this in runtime/session prefetch requests\n * where we have a proper session shell.\n * */\n u?: Promise<boolean>\n /** headVaryParams. Does not include root params (see `r`). */\n h: VaryParamsIterable | null\n /**\n * rootVaryParams - the root params accessed anywhere in the response, emitted\n * once. The client unions these into the head and every segment's vary\n * params.\n */\n r?: VaryParamsIterable\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n /**\n * revealAfter (dev only). Resolves once the server has flushed the\n * shell-stage content to the stream (static shell, or runtime-prefetchable\n * shell for runtime-prefetch routes), or earlier on a cache miss. The client\n * decodes this from the payload and defers resolving the response's deferred\n * RSCs on it, so a boundary's children aren't revealed before their row has\n * been decoded (which would flush a premature Suspense fallback). Its\n * resolution row follows the children's row in the payload, so the children\n * are decoded by the time the client unblocks. The HTML render gates on the\n * same signal server-side instead of reading this field.\n */\n _revealAfter?: Promise<void>\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n\nexport type InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n"],"names":["PrefetchHint","StaticPrefetchDisabled","SubtreePrefetchHints","propagateSubtreeBits","parentHints","childHints"],"mappings":"AAAA;;;;;CAKC;;;;;;;;;;;;;;;;;IAiLiBA,YAAY;eAAZA;;IA0FLC,sBAAsB;eAAtBA;;IASAC,oBAAoB;eAApBA;;IAkBGC,oBAAoB;eAApBA;;;AArHT,IAAA,AAAWH,sCAAAA;IAChB,gEAAgE;IAChE,2EAA2E;;IAE3E,6EAA6E;IAC7E,wEAAwE;IACxE,gEAAgE;IAChE,8EAA8E;IAC9E,+BAA+B;;IAE/B,kDAAkD;;IAElD,sEAAsE;IACtE,6DAA6D;;IAE7D,8EAA8E;IAC9E,2EAA2E;IAC3E,8BAA8B;;IAE9B,sEAAsE;IACtE,0DAA0D;;IAE1D,wEAAwE;IACxE,yEAAyE;;IAEzE,4EAA4E;IAC5E,6CAA6C;;IAE7C,wEAAwE;IACxE,4EAA4E;;IAE5E,oEAAoE;IACpE,0EAA0E;IAC1E,0EAA0E;IAC1E,kEAAkE;IAClE,0EAA0E;IAC1E,oBAAoB;;IAEpB,sDAAsD;IACtD,qDAAqD;;IAErD,sEAAsE;IACtE,mEAAmE;IACnE,kBAAkB;;IAElB,yEAAyE;IACzE,kEAAkE;IAClE,yEAAyE;IACzE,4EAA4E;IAC5E,wCAAwC;;IAExC,oEAAoE;IACpE,8EAA8E;IAC9E,kEAAkE;IAClE,+EAA+E;IAC/E,mCAAmC;;IAEnC,kEAAkE;IAClE,0EAA0E;IAC1E,yEAAyE;IACzE,yEAAyE;IACzE,wEAAwE;IACxE,uEAAuE;IACvE,kEAAkE;IAClE,uEAAuE;IACvE,mEAAmE;IACnE,qEAAqE;IACrE,0EAA0E;IAC1E,yEAAyE;IACzE,0EAA0E;IAC1E,0EAA0E;IAC1E,0EAA0E;IAC1E,uEAAuE;IACvE,uEAAuE;IACvE,mEAAmE;IACnE,wEAAwE;IACxE,yEAAyE;IACzE,sBAAsB;;WA7ENA;;AA0FX,MAAMC,yBACXD;AAQK,MAAME,uBACXF;AAiBK,SAASG,qBACdC,WAAmB,EACnBC,UAAkB;IAElB,IAAIA,gBAAwD;QAC1DD;IACF;IACA,+EAA+E;IAC/E,kDAAkD;IAClD,IACEC,aACCL,CAAAA,KACsC,GACvC;QACAI;IACF;IACA,iCAAiC;IACjC,IACEC,aACCL,CAAAA,QAAuE,GACxE;QACAI;IACF;IACA,4EAA4E;IAC5E,+DAA+D;IAC/D,IAAIC,mBAAmD;QACrDD;IACF;IACA,6EAA6E;IAC7E,iDAAiD;IACjD,IAAIC,mBAAkD;QACpDD;IACF;IACA,OAAOA;AACT","ignoreList":[0]} |
@@ -24,3 +24,3 @@ "use strict"; | ||
| function isStableBuild() { | ||
| return !"16.3.0-canary.97"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| return !"16.3.0-canary.99"?.includes('canary') && !process.env.__NEXT_TEST_MODE && !process.env.NEXT_PRIVATE_LOCAL_DEV; | ||
| } | ||
@@ -27,0 +27,0 @@ class CanaryOnlyConfigError extends Error { |
@@ -85,3 +85,3 @@ "use strict"; | ||
| ciName: _ciinfo.isCI && _ciinfo.name || null, | ||
| nextVersion: "16.3.0-canary.97", | ||
| nextVersion: "16.3.0-canary.99", | ||
| agentName: await (0, _agentname.getAgentName)() | ||
@@ -88,0 +88,0 @@ }; |
@@ -14,7 +14,7 @@ "use strict"; | ||
| // This should be an invariant, if it fails our build tooling is broken. | ||
| if (typeof "16.3.0-canary.97" !== 'string') { | ||
| if (typeof "16.3.0-canary.99" !== 'string') { | ||
| return []; | ||
| } | ||
| const payload = { | ||
| nextVersion: "16.3.0-canary.97", | ||
| nextVersion: "16.3.0-canary.99", | ||
| nodeVersion: process.version, | ||
@@ -21,0 +21,0 @@ cliCommand: event.cliCommand, |
@@ -41,3 +41,3 @@ "use strict"; | ||
| payload: { | ||
| nextVersion: "16.3.0-canary.97", | ||
| nextVersion: "16.3.0-canary.99", | ||
| glibcVersion, | ||
@@ -44,0 +44,0 @@ installedSwcPackages, |
@@ -15,3 +15,3 @@ "use strict"; | ||
| // This should be an invariant, if it fails our build tooling is broken. | ||
| if (typeof "16.3.0-canary.97" !== 'string') { | ||
| if (typeof "16.3.0-canary.99" !== 'string') { | ||
| return []; | ||
@@ -21,3 +21,3 @@ } | ||
| const payload = { | ||
| nextVersion: "16.3.0-canary.97", | ||
| nextVersion: "16.3.0-canary.99", | ||
| nodeVersion: process.version, | ||
@@ -24,0 +24,0 @@ cliCommand: event.cliCommand, |
+10
-10
| { | ||
| "name": "next", | ||
| "version": "16.3.0-canary.97", | ||
| "version": "16.3.0-canary.99", | ||
| "description": "The React Framework", | ||
@@ -84,3 +84,3 @@ "main": "./dist/server/next.js", | ||
| "dependencies": { | ||
| "@next/env": "16.3.0-canary.97", | ||
| "@next/env": "16.3.0-canary.99", | ||
| "@swc/helpers": "0.5.15", | ||
@@ -116,10 +116,10 @@ "baseline-browser-mapping": "^2.9.19", | ||
| "sharp": "^0.35.3", | ||
| "@next/swc-darwin-arm64": "16.3.0-canary.97", | ||
| "@next/swc-darwin-x64": "16.3.0-canary.97", | ||
| "@next/swc-linux-arm64-gnu": "16.3.0-canary.97", | ||
| "@next/swc-linux-arm64-musl": "16.3.0-canary.97", | ||
| "@next/swc-linux-x64-gnu": "16.3.0-canary.97", | ||
| "@next/swc-linux-x64-musl": "16.3.0-canary.97", | ||
| "@next/swc-win32-arm64-msvc": "16.3.0-canary.97", | ||
| "@next/swc-win32-x64-msvc": "16.3.0-canary.97" | ||
| "@next/swc-darwin-arm64": "16.3.0-canary.99", | ||
| "@next/swc-darwin-x64": "16.3.0-canary.99", | ||
| "@next/swc-linux-arm64-gnu": "16.3.0-canary.99", | ||
| "@next/swc-linux-arm64-musl": "16.3.0-canary.99", | ||
| "@next/swc-linux-x64-gnu": "16.3.0-canary.99", | ||
| "@next/swc-linux-x64-musl": "16.3.0-canary.99", | ||
| "@next/swc-win32-arm64-msvc": "16.3.0-canary.99", | ||
| "@next/swc-win32-x64-msvc": "16.3.0-canary.99" | ||
| }, | ||
@@ -126,0 +126,0 @@ "keywords": [ |
@@ -99,2 +99,4 @@ /// <reference types="node" /> | ||
| base?: string | ||
| /** Whether glob matching is case-sensitive. Default: `true`. */ | ||
| caseSensitive?: boolean | ||
| } | ||
@@ -101,0 +103,0 @@ |
Sorry, the diff of this file is too big to display
| (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,28116,(__turbopack_context__,module,exports)=>{"use strict";var React=__turbopack_context__.r(41048);function formatProdErrorMessage(code){var url="https://react.dev/errors/"+code;if(1<arguments.length){url+="?args[]="+encodeURIComponent(arguments[1]);for(var i=2;i<arguments.length;i++)url+="&args[]="+encodeURIComponent(arguments[i])}return"Minified React error #"+code+"; visit "+url+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function noop(){}var Internals={d:{f:noop,r:function(){throw Error(formatProdErrorMessage(522))},D:noop,C:noop,L:noop,m:noop,X:noop,S:noop,M:noop},p:0,findDOMNode:null},REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_OPTIMISTIC_KEY=Symbol.for("react.optimistic_key");function createPortal$1(children,containerInfo,implementation){var key=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:REACT_PORTAL_TYPE,key:null==key?null:key===REACT_OPTIMISTIC_KEY?REACT_OPTIMISTIC_KEY:""+key,children:children,containerInfo:containerInfo,implementation:implementation}}var ReactSharedInternals=React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function getCrossOriginStringAs(as,input){return"font"===as?"":"string"==typeof input?"use-credentials"===input?input:"":void 0}exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=Internals,exports.createPortal=function(children,container){var key=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!container||1!==container.nodeType&&9!==container.nodeType&&11!==container.nodeType)throw Error(formatProdErrorMessage(299));return createPortal$1(children,container,null,key)},exports.flushSync=function(fn){var previousTransition=ReactSharedInternals.T,previousUpdatePriority=Internals.p;try{if(ReactSharedInternals.T=null,Internals.p=2,fn)return fn()}finally{ReactSharedInternals.T=previousTransition,Internals.p=previousUpdatePriority,Internals.d.f()}},exports.preconnect=function(href,options){"string"==typeof href&&(options=options?"string"==typeof(options=options.crossOrigin)?"use-credentials"===options?options:"":void 0:null,Internals.d.C(href,options))},exports.prefetchDNS=function(href){"string"==typeof href&&Internals.d.D(href)},exports.preinit=function(href,options){if("string"==typeof href&&options&&"string"==typeof options.as){var as=options.as,crossOrigin=getCrossOriginStringAs(as,options.crossOrigin),integrity="string"==typeof options.integrity?options.integrity:void 0,fetchPriority="string"==typeof options.fetchPriority?options.fetchPriority:void 0;"style"===as?Internals.d.S(href,"string"==typeof options.precedence?options.precedence:void 0,{crossOrigin:crossOrigin,integrity:integrity,fetchPriority:fetchPriority}):"script"===as&&Internals.d.X(href,{crossOrigin:crossOrigin,integrity:integrity,fetchPriority:fetchPriority,nonce:"string"==typeof options.nonce?options.nonce:void 0})}},exports.preinitModule=function(href,options){if("string"==typeof href)if("object"==typeof options&&null!==options){if(null==options.as||"script"===options.as){var crossOrigin=getCrossOriginStringAs(options.as,options.crossOrigin);Internals.d.M(href,{crossOrigin:crossOrigin,integrity:"string"==typeof options.integrity?options.integrity:void 0,nonce:"string"==typeof options.nonce?options.nonce:void 0})}}else null==options&&Internals.d.M(href)},exports.preload=function(href,options){if("string"==typeof href&&"object"==typeof options&&null!==options&&"string"==typeof options.as){var as=options.as,crossOrigin=getCrossOriginStringAs(as,options.crossOrigin);Internals.d.L(href,as,{crossOrigin:crossOrigin,integrity:"string"==typeof options.integrity?options.integrity:void 0,nonce:"string"==typeof options.nonce?options.nonce:void 0,type:"string"==typeof options.type?options.type:void 0,fetchPriority:"string"==typeof options.fetchPriority?options.fetchPriority:void 0,referrerPolicy:"string"==typeof options.referrerPolicy?options.referrerPolicy:void 0,imageSrcSet:"string"==typeof options.imageSrcSet?options.imageSrcSet:void 0,imageSizes:"string"==typeof options.imageSizes?options.imageSizes:void 0,media:"string"==typeof options.media?options.media:void 0})}},exports.preloadModule=function(href,options){if("string"==typeof href)if(options){var crossOrigin=getCrossOriginStringAs(options.as,options.crossOrigin);Internals.d.m(href,{as:"string"==typeof options.as&&"script"!==options.as?options.as:void 0,crossOrigin:crossOrigin,integrity:"string"==typeof options.integrity?options.integrity:void 0})}else Internals.d.m(href)},exports.requestFormReset=function(form){Internals.d.r(form)},exports.unstable_batchedUpdates=function(fn,a){return fn(a)},exports.useFormState=function(action,initialState,permalink){return ReactSharedInternals.H.useFormState(action,initialState,permalink)},exports.useFormStatus=function(){return ReactSharedInternals.H.useHostTransitionStatus()},exports.version="19.3.0-canary-3f0b9e61-20260317"},23819,(__turbopack_context__,module,exports)=>{"use strict";function checkDCE(){if("u">typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE)}catch(err){console.error(err)}}checkDCE(),module.exports=__turbopack_context__.r(28116)},72065,(__turbopack_context__,module,exports)=>{var e={229:function(e){var r,n,u,t=e.exports={};function defaultSetTimout(){throw Error("setTimeout has not been defined")}function defaultClearTimeout(){throw Error("clearTimeout has not been defined")}try{r="function"==typeof setTimeout?setTimeout:defaultSetTimout}catch(e){r=defaultSetTimout}try{n="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout}catch(e){n=defaultClearTimeout}function runTimeout(e){if(r===setTimeout)return setTimeout(e,0);if((r===defaultSetTimout||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}function runClearTimeout(e){if(n===clearTimeout)return clearTimeout(e);if((n===defaultClearTimeout||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(e);try{return n(e)}catch(t){try{return n.call(null,e)}catch(t){return n.call(this,e)}}}var i=[],o=!1,a=-1;function cleanUpNextTick(){o&&u&&(o=!1,u.length?i=u.concat(i):a=-1,i.length&&drainQueue())}function drainQueue(){if(!o){var e=runTimeout(cleanUpNextTick);o=!0;for(var t=i.length;t;){for(u=i,i=[];++a<t;)u&&u[a].run();a=-1,t=i.length}u=null,o=!1,runClearTimeout(e)}}function Item(e,t){this.fun=e,this.array=t}function noop(){}t.nextTick=function(e){var t=Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];i.push(new Item(e,t)),1!==i.length||o||runTimeout(drainQueue)},Item.prototype.run=function(){this.fun.apply(null,this.array)},t.title="browser",t.browser=!0,t.env={},t.argv=[],t.version="",t.versions={},t.on=noop,t.addListener=noop,t.once=noop,t.off=noop,t.removeListener=noop,t.removeAllListeners=noop,t.emit=noop,t.prependListener=noop,t.prependOnceListener=noop,t.listeners=function(e){return[]},t.binding=function(e){throw Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(e){throw Error("process.chdir is not supported")},t.umask=function(){return 0}}},t={};function __nccwpck_require__(r){var n=t[r];if(void 0!==n)return n.exports;var i=t[r]={exports:{}},o=!0;try{e[r](i,i.exports,__nccwpck_require__),o=!1}finally{o&&delete t[r]}return i.exports}__nccwpck_require__.ab="/ROOT/node_modules/.pnpm/next@16.2.3_@babel+core@7.26.10_@opentelemetry+api@1.9.0_@playwright+test@1.61.0_babel-_e2543de0520ae2148df4cc15bd046d58/node_modules/next/dist/compiled/process/",module.exports=__nccwpck_require__(229)},33910,(__turbopack_context__,module,exports)=>{"use strict";var _global_process,_global_process1;module.exports=(null==(_global_process=__turbopack_context__.g.process)?void 0:_global_process.env)&&"object"==typeof(null==(_global_process1=__turbopack_context__.g.process)?void 0:_global_process1.env)?__turbopack_context__.g.process:__turbopack_context__.r(72065)},86619,(__turbopack_context__,module,exports)=>{"use strict";var REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element");function jsxProd(type,config,maybeKey){var key=null;if(void 0!==maybeKey&&(key=""+maybeKey),void 0!==config.key&&(key=""+config.key),"key"in config)for(var propName in maybeKey={},config)"key"!==propName&&(maybeKey[propName]=config[propName]);else maybeKey=config;return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:key,ref:void 0!==(config=maybeKey.ref)?config:null,props:maybeKey}}exports.Fragment=Symbol.for("react.fragment"),exports.jsx=jsxProd,exports.jsxs=jsxProd},92047,(__turbopack_context__,module,exports)=>{"use strict";module.exports=__turbopack_context__.r(86619)},84198,(__turbopack_context__,module,exports)=>{"use strict";var __TURBOPACK__imported__module__33910__=__turbopack_context__.i(33910),REACT_ELEMENT_TYPE=Symbol.for("react.transitional.element"),REACT_PORTAL_TYPE=Symbol.for("react.portal"),REACT_FRAGMENT_TYPE=Symbol.for("react.fragment"),REACT_STRICT_MODE_TYPE=Symbol.for("react.strict_mode"),REACT_PROFILER_TYPE=Symbol.for("react.profiler"),REACT_CONSUMER_TYPE=Symbol.for("react.consumer"),REACT_CONTEXT_TYPE=Symbol.for("react.context"),REACT_FORWARD_REF_TYPE=Symbol.for("react.forward_ref"),REACT_SUSPENSE_TYPE=Symbol.for("react.suspense"),REACT_MEMO_TYPE=Symbol.for("react.memo"),REACT_LAZY_TYPE=Symbol.for("react.lazy"),REACT_ACTIVITY_TYPE=Symbol.for("react.activity"),REACT_VIEW_TRANSITION_TYPE=Symbol.for("react.view_transition"),MAYBE_ITERATOR_SYMBOL=Symbol.iterator;function getIteratorFn(maybeIterable){return null===maybeIterable||"object"!=typeof maybeIterable?null:"function"==typeof(maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"])?maybeIterable:null}var ReactNoopUpdateQueue={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},assign=Object.assign,emptyObject={};function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}Component.prototype.isReactComponent={},Component.prototype.setState=function(partialState,callback){if("object"!=typeof partialState&&"function"!=typeof partialState&&null!=partialState)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,partialState,callback,"setState")},Component.prototype.forceUpdate=function(callback){this.updater.enqueueForceUpdate(this,callback,"forceUpdate")},ComponentDummy.prototype=Component.prototype;var pureComponentPrototype=PureComponent.prototype=new ComponentDummy;pureComponentPrototype.constructor=PureComponent,assign(pureComponentPrototype,Component.prototype),pureComponentPrototype.isPureReactComponent=!0;var isArrayImpl=Array.isArray;function noop(){}var ReactSharedInternals={H:null,A:null,T:null,S:null},hasOwnProperty=Object.prototype.hasOwnProperty;function ReactElement(type,key,props){var refProp=props.ref;return{$$typeof:REACT_ELEMENT_TYPE,type:type,key:key,ref:void 0!==refProp?refProp:null,props:props}}function cloneAndReplaceKey(oldElement,newKey){return ReactElement(oldElement.type,newKey,oldElement.props)}function isValidElement(object){return"object"==typeof object&&null!==object&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}var userProvidedKeyEscapeRegex=/\/+/g;function getElementKey(element,index){return"object"==typeof element&&null!==element&&null!=element.key?escape(""+element.key):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch("string"==typeof thenable.status?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){"pending"===thenable.status&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){"pending"===thenable.status&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;("undefined"===type||"boolean"===type)&&(children=null);var invokeCallback=!1;if(null===children)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return mapIntoArray((invokeCallback=children._init)(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback)return callback=callback(children),invokeCallback=""===nameSoFar?"."+getElementKey(children,0):nameSoFar,isArrayImpl(callback)?(escapedPrefix="",null!=invokeCallback&&(escapedPrefix=invokeCallback.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):null!=callback&&(isValidElement(callback)&&(callback=cloneAndReplaceKey(callback,escapedPrefix+(null==callback.key||children&&children.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+invokeCallback)),array.push(callback)),1;invokeCallback=0;var nextNamePrefix=""===nameSoFar?".":nameSoFar+":";if(isArrayImpl(children))for(var i=0;i<children.length;i++)type=nextNamePrefix+getElementKey(nameSoFar=children[i],i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if("function"==typeof(i=getIteratorFn(children)))for(children=i.call(children),i=0;!(nameSoFar=children.next()).done;)type=nextNamePrefix+getElementKey(nameSoFar=nameSoFar.value,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if("object"===type){if("function"==typeof children.then)return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw Error("Objects are not valid as a React child (found: "+("[object Object]"===(array=String(children))?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(null==children)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(-1===payload._status){var thenable=(0,payload._result)();thenable.then(function(moduleObject){(0===payload._status||-1===payload._status)&&(payload._status=1,payload._result=moduleObject,void 0===thenable.status&&(thenable.status="fulfilled",thenable.value=moduleObject))},function(error){(0===payload._status||-1===payload._status)&&(payload._status=2,payload._result=error,void 0===thenable.status&&(thenable.status="rejected",thenable.reason=error))}),-1===payload._status&&(payload._status=0,payload._result=thenable)}if(1===payload._status)return payload._result.default;throw payload._result}var reportGlobalError="function"==typeof reportError?reportError:function(error){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var event=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof error&&null!==error&&"string"==typeof error.message?String(error.message):String(error),error:error});if(!window.dispatchEvent(event))return}else if("object"==typeof __TURBOPACK__imported__module__33910__.default&&"function"==typeof __TURBOPACK__imported__module__33910__.default.emit)return void __TURBOPACK__imported__module__33910__.default.emit("uncaughtException",error);console.error(error)};function startTransition(scope){var prevTransition=ReactSharedInternals.T,currentTransition={};currentTransition.types=null!==prevTransition?prevTransition.types:null,ReactSharedInternals.T=currentTransition;try{var returnValue=scope(),onStartTransitionFinish=ReactSharedInternals.S;null!==onStartTransitionFinish&&onStartTransitionFinish(currentTransition,returnValue),"object"==typeof returnValue&&null!==returnValue&&"function"==typeof returnValue.then&&returnValue.then(noop,reportGlobalError)}catch(error){reportGlobalError(error)}finally{null!==prevTransition&&null!==currentTransition.types&&(prevTransition.types=currentTransition.types),ReactSharedInternals.T=prevTransition}}function addTransitionType(type){var transition=ReactSharedInternals.T;if(null!==transition){var transitionTypes=transition.types;null===transitionTypes?transition.types=[type]:-1===transitionTypes.indexOf(type)&&transitionTypes.push(type)}else startTransition(addTransitionType.bind(null,type))}exports.Activity=REACT_ACTIVITY_TYPE,exports.Children={map:mapChildren,forEach:function(children,forEachFunc,forEachContext){mapChildren(children,function(){forEachFunc.apply(this,arguments)},forEachContext)},count:function(children){var n=0;return mapChildren(children,function(){n++}),n},toArray:function(children){return mapChildren(children,function(child){return child})||[]},only:function(children){if(!isValidElement(children))throw Error("React.Children.only expected to receive a single React element child.");return children}},exports.Component=Component,exports.Fragment=REACT_FRAGMENT_TYPE,exports.Profiler=REACT_PROFILER_TYPE,exports.PureComponent=PureComponent,exports.StrictMode=REACT_STRICT_MODE_TYPE,exports.Suspense=REACT_SUSPENSE_TYPE,exports.ViewTransition=REACT_VIEW_TRANSITION_TYPE,exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=ReactSharedInternals,exports.__COMPILER_RUNTIME={__proto__:null,c:function(size){return ReactSharedInternals.H.useMemoCache(size)}},exports.addTransitionType=addTransitionType,exports.cache=function(fn){return function(){return fn.apply(null,arguments)}},exports.cacheSignal=function(){return null},exports.cloneElement=function(element,config,children){if(null==element)throw Error("The argument must be a React element, but you passed "+element+".");var props=assign({},element.props),key=element.key;if(null!=config)for(propName in void 0!==config.key&&(key=""+config.key),config)hasOwnProperty.call(config,propName)&&"key"!==propName&&"__self"!==propName&&"__source"!==propName&&("ref"!==propName||void 0!==config.ref)&&(props[propName]=config[propName]);var propName=arguments.length-2;if(1===propName)props.children=children;else if(1<propName){for(var childArray=Array(propName),i=0;i<propName;i++)childArray[i]=arguments[i+2];props.children=childArray}return ReactElement(element.type,key,props)},exports.createContext=function(defaultValue){return(defaultValue={$$typeof:REACT_CONTEXT_TYPE,_currentValue:defaultValue,_currentValue2:defaultValue,_threadCount:0,Provider:null,Consumer:null}).Provider=defaultValue,defaultValue.Consumer={$$typeof:REACT_CONSUMER_TYPE,_context:defaultValue},defaultValue},exports.createElement=function(type,config,children){var propName,props={},key=null;if(null!=config)for(propName in void 0!==config.key&&(key=""+config.key),config)hasOwnProperty.call(config,propName)&&"key"!==propName&&"__self"!==propName&&"__source"!==propName&&(props[propName]=config[propName]);var childrenLength=arguments.length-2;if(1===childrenLength)props.children=children;else if(1<childrenLength){for(var childArray=Array(childrenLength),i=0;i<childrenLength;i++)childArray[i]=arguments[i+2];props.children=childArray}if(type&&type.defaultProps)for(propName in childrenLength=type.defaultProps)void 0===props[propName]&&(props[propName]=childrenLength[propName]);return ReactElement(type,key,props)},exports.createRef=function(){return{current:null}},exports.forwardRef=function(render){return{$$typeof:REACT_FORWARD_REF_TYPE,render:render}},exports.isValidElement=isValidElement,exports.lazy=function(ctor){return{$$typeof:REACT_LAZY_TYPE,_payload:{_status:-1,_result:ctor},_init:lazyInitializer}},exports.memo=function(type,compare){return{$$typeof:REACT_MEMO_TYPE,type:type,compare:void 0===compare?null:compare}},exports.startTransition=startTransition,exports.unstable_useCacheRefresh=function(){return ReactSharedInternals.H.useCacheRefresh()},exports.use=function(usable){return ReactSharedInternals.H.use(usable)},exports.useActionState=function(action,initialState,permalink){return ReactSharedInternals.H.useActionState(action,initialState,permalink)},exports.useCallback=function(callback,deps){return ReactSharedInternals.H.useCallback(callback,deps)},exports.useContext=function(Context){return ReactSharedInternals.H.useContext(Context)},exports.useDebugValue=function(){},exports.useDeferredValue=function(value,initialValue){return ReactSharedInternals.H.useDeferredValue(value,initialValue)},exports.useEffect=function(create,deps){return ReactSharedInternals.H.useEffect(create,deps)},exports.useEffectEvent=function(callback){return ReactSharedInternals.H.useEffectEvent(callback)},exports.useId=function(){return ReactSharedInternals.H.useId()},exports.useImperativeHandle=function(ref,create,deps){return ReactSharedInternals.H.useImperativeHandle(ref,create,deps)},exports.useInsertionEffect=function(create,deps){return ReactSharedInternals.H.useInsertionEffect(create,deps)},exports.useLayoutEffect=function(create,deps){return ReactSharedInternals.H.useLayoutEffect(create,deps)},exports.useMemo=function(create,deps){return ReactSharedInternals.H.useMemo(create,deps)},exports.useOptimistic=function(passthrough,reducer){return ReactSharedInternals.H.useOptimistic(passthrough,reducer)},exports.useReducer=function(reducer,initialArg,init){return ReactSharedInternals.H.useReducer(reducer,initialArg,init)},exports.useRef=function(initialValue){return ReactSharedInternals.H.useRef(initialValue)},exports.useState=function(initialState){return ReactSharedInternals.H.useState(initialState)},exports.useSyncExternalStore=function(subscribe,getSnapshot,getServerSnapshot){return ReactSharedInternals.H.useSyncExternalStore(subscribe,getSnapshot,getServerSnapshot)},exports.useTransition=function(){return ReactSharedInternals.H.useTransition()},exports.version="19.3.0-canary-3f0b9e61-20260317"},41048,(__turbopack_context__,module,exports)=>{"use strict";module.exports=__turbopack_context__.r(84198)},81258,(__turbopack_context__,module,exports)=>{"use strict";exports._=function _interop_require_default(obj){return obj&&obj.__esModule?obj:{default:obj}}},82858,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:!0,get:all[name]})}(exports,{bindSnapshot:function(){return bindSnapshot},createAsyncLocalStorage:function(){return createAsyncLocalStorage},createSnapshot:function(){return createSnapshot}});let sharedAsyncLocalStorageNotAvailableError=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class FakeAsyncLocalStorage{disable(){throw sharedAsyncLocalStorageNotAvailableError}getStore(){}run(){throw sharedAsyncLocalStorageNotAvailableError}exit(){throw sharedAsyncLocalStorageNotAvailableError}enterWith(){throw sharedAsyncLocalStorageNotAvailableError}static bind(fn){return fn}}let maybeGlobalAsyncLocalStorage="u">typeof globalThis&&globalThis.AsyncLocalStorage;function createAsyncLocalStorage(){return maybeGlobalAsyncLocalStorage?new maybeGlobalAsyncLocalStorage:new FakeAsyncLocalStorage}function bindSnapshot(fn){return maybeGlobalAsyncLocalStorage?maybeGlobalAsyncLocalStorage.bind(fn):FakeAsyncLocalStorage.bind(fn)}function createSnapshot(){return maybeGlobalAsyncLocalStorage?maybeGlobalAsyncLocalStorage.snapshot():function(fn,...args){return fn(...args)}}},54312,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"workAsyncStorageInstance",{enumerable:!0,get:function(){return workAsyncStorageInstance}});let workAsyncStorageInstance=(0,__turbopack_context__.r(82858).createAsyncLocalStorage)()},19596,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"workAsyncStorage",{enumerable:!0,get:function(){return _workasyncstorageinstance.workAsyncStorageInstance}});let _workasyncstorageinstance=__turbopack_context__.r(54312)},63561,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"handleISRError",{enumerable:!0,get:function(){return handleISRError}});let workAsyncStorage="u"<typeof window?__turbopack_context__.r(19596).workAsyncStorage:void 0;function handleISRError({error}){if(workAsyncStorage){let store=workAsyncStorage.getStore();if(store?.isStaticGeneration)throw error&&console.error(error),error}}("function"==typeof exports.default||"object"==typeof exports.default&&null!==exports.default)&&void 0===exports.default.__esModule&&(Object.defineProperty(exports.default,"__esModule",{value:!0}),Object.assign(exports.default,exports),module.exports=exports.default)},25447,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),function _export(target,all){for(var name in all)Object.defineProperty(target,name,{enumerable:!0,get:all[name]})}(exports,{WarningIcon:function(){return WarningIcon},errorStyles:function(){return errorStyles},errorThemeCss:function(){return errorThemeCss}}),__turbopack_context__.r(81258);let _jsxruntime=__turbopack_context__.r(92047);__turbopack_context__.r(41048);let errorStyles={container:{fontFamily:'system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',height:"100vh",display:"flex",alignItems:"center",justifyContent:"center"},card:{marginTop:"-32px",maxWidth:"325px",padding:"32px 28px",textAlign:"left"},icon:{marginBottom:"24px"},title:{fontSize:"24px",fontWeight:500,letterSpacing:"-0.02em",lineHeight:"32px",margin:"0 0 12px 0",color:"var(--next-error-title)"},message:{fontSize:"14px",fontWeight:400,lineHeight:"21px",margin:"0 0 20px 0",color:"var(--next-error-message)"},form:{margin:0},buttonGroup:{display:"flex",gap:"8px",alignItems:"center"},button:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:"32px",padding:"0 12px",fontSize:"14px",fontWeight:500,lineHeight:"20px",borderRadius:"6px",cursor:"pointer",color:"var(--next-error-btn-text)",background:"var(--next-error-btn-bg)",border:"var(--next-error-btn-border)"},buttonSecondary:{display:"inline-flex",alignItems:"center",justifyContent:"center",height:"32px",padding:"0 12px",fontSize:"14px",fontWeight:500,lineHeight:"20px",borderRadius:"6px",cursor:"pointer",color:"var(--next-error-btn-secondary-text)",background:"var(--next-error-btn-secondary-bg)",border:"var(--next-error-btn-secondary-border)"},digestFooter:{position:"fixed",bottom:"32px",left:"0",right:"0",textAlign:"center",fontFamily:'ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace',fontSize:"12px",lineHeight:"18px",fontWeight:400,margin:"0",color:"var(--next-error-digest)"}},errorThemeCss=` | ||
| :root { | ||
| --next-error-bg: #fff; | ||
| --next-error-text: #171717; | ||
| --next-error-title: #171717; | ||
| --next-error-message: #171717; | ||
| --next-error-digest: #666666; | ||
| --next-error-btn-text: #fff; | ||
| --next-error-btn-bg: #171717; | ||
| --next-error-btn-border: none; | ||
| --next-error-btn-secondary-text: #171717; | ||
| --next-error-btn-secondary-bg: transparent; | ||
| --next-error-btn-secondary-border: 1px solid rgba(0,0,0,0.08); | ||
| } | ||
| @media (prefers-color-scheme: dark) { | ||
| :root { | ||
| --next-error-bg: #0a0a0a; | ||
| --next-error-text: #ededed; | ||
| --next-error-title: #ededed; | ||
| --next-error-message: #ededed; | ||
| --next-error-digest: #a0a0a0; | ||
| --next-error-btn-text: #0a0a0a; | ||
| --next-error-btn-bg: #ededed; | ||
| --next-error-btn-border: none; | ||
| --next-error-btn-secondary-text: #ededed; | ||
| --next-error-btn-secondary-bg: transparent; | ||
| --next-error-btn-secondary-border: 1px solid rgba(255,255,255,0.14); | ||
| } | ||
| } | ||
| body { margin: 0; color: var(--next-error-text); background: var(--next-error-bg); } | ||
| `.replace(/\n\s*/g,"");function WarningIcon(){return(0,_jsxruntime.jsx)("svg",{width:"32",height:"32",viewBox:"-0.2 -1.5 32 32",fill:"none",style:errorStyles.icon,children:(0,_jsxruntime.jsx)("path",{d:"M16.9328 0C18.0839 0.000116771 19.1334 0.658832 19.634 1.69531L31.4299 26.1309C32.0708 27.4588 31.1036 28.9999 29.6291 29H2.00215C0.527541 29 -0.439628 27.4588 0.201371 26.1309L11.9973 1.69531C12.4979 0.658823 13.5474 7.75066e-05 14.6984 0H16.9328ZM3.59493 26H28.0363L16.9328 3H14.6984L3.59493 26ZM15.8156 19C16.9202 19.0001 17.8156 19.8955 17.8156 21C17.8156 22.1045 16.9202 22.9999 15.8156 23C14.7111 23 13.8156 22.1046 13.8156 21C13.8156 19.8954 14.7111 19 15.8156 19ZM17.3156 16.5H14.3156V8.5H17.3156V16.5Z",fill:"var(--next-error-title)"})})}("function"==typeof exports.default||"object"==typeof exports.default&&null!==exports.default)&&void 0===exports.default.__esModule&&(Object.defineProperty(exports.default,"__esModule",{value:!0}),Object.assign(exports.default,exports),module.exports=exports.default)},43334,(__turbopack_context__,module,exports)=>{"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _default}}),__turbopack_context__.r(81258);let _jsxruntime=__turbopack_context__.r(92047);__turbopack_context__.r(41048);let _handleisrerror=__turbopack_context__.r(63561),_errorstyles=__turbopack_context__.r(25447),_default=function DefaultGlobalError({error}){let digest=error?.digest,isServerError=!!digest;return(0,_handleisrerror.handleISRError)({error}),(0,_jsxruntime.jsxs)("html",{id:"__next_error__",children:[(0,_jsxruntime.jsx)("head",{children:(0,_jsxruntime.jsx)("style",{dangerouslySetInnerHTML:{__html:_errorstyles.errorThemeCss}})}),(0,_jsxruntime.jsxs)("body",{children:[(0,_jsxruntime.jsx)("div",{style:_errorstyles.errorStyles.container,children:(0,_jsxruntime.jsxs)("div",{style:_errorstyles.errorStyles.card,children:[(0,_jsxruntime.jsx)(_errorstyles.WarningIcon,{}),(0,_jsxruntime.jsx)("h1",{style:_errorstyles.errorStyles.title,children:"This page couldn’t load"}),(0,_jsxruntime.jsx)("p",{style:_errorstyles.errorStyles.message,children:isServerError?"A server error occurred. Reload to try again.":"Reload to try again, or go back."}),(0,_jsxruntime.jsxs)("div",{style:_errorstyles.errorStyles.buttonGroup,children:[(0,_jsxruntime.jsx)("form",{style:_errorstyles.errorStyles.form,children:(0,_jsxruntime.jsx)("button",{type:"submit",style:_errorstyles.errorStyles.button,children:"Reload"})}),!isServerError&&(0,_jsxruntime.jsx)("button",{type:"button",style:_errorstyles.errorStyles.buttonSecondary,onClick:()=>{window.history.length>1?window.history.back():window.location.href="/"},children:"Back"})]})]})}),digest&&(0,_jsxruntime.jsxs)("p",{style:_errorstyles.errorStyles.digestFooter,children:["ERROR ",digest]})]})]})};("function"==typeof exports.default||"object"==typeof exports.default&&null!==exports.default)&&void 0===exports.default.__esModule&&(Object.defineProperty(exports.default,"__esModule",{value:!0}),Object.assign(exports.default,exports),module.exports=exports.default)}]); |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
| (globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,{otherChunks:["static/chunks/0kp3gz-tar6qr.js","static/chunks/0o8czoqls7u7z.js","static/chunks/0x_ezzus9zvio.js"],runtimeModuleIds:[2315]}]),(()=>{let BACKEND;if(!Array.isArray(globalThis.TURBOPACK))return;let CHUNK_BASE_PATH="/_next/",ASSET_SUFFIX=getAssetSuffixFromScriptSrc(),WORKER_FORWARDED_GLOBALS=["NEXT_DEPLOYMENT_ID","NEXT_CLIENT_ASSET_SUFFIX"];var SourceType,SourceType1=((SourceType=SourceType1||{})[SourceType.Runtime=0]="Runtime",SourceType[SourceType.Parent=1]="Parent",SourceType[SourceType.Update=2]="Update",SourceType);let REEXPORTED_OBJECTS=new WeakMap;function Context(module,exports){this.m=module,this.e=exports}let contextPrototype=Context.prototype,hasOwnProperty=Object.prototype.hasOwnProperty,toStringTag="u">typeof Symbol&&Symbol.toStringTag;function defineProp(obj,name,options){hasOwnProperty.call(obj,name)||Object.defineProperty(obj,name,options)}function getOverwrittenModule(moduleCache,id){let module=moduleCache[id];return module||(module=createModuleObject(id),moduleCache[id]=module),module}function createModuleObject(id){return{exports:{},error:void 0,id,namespaceObject:void 0}}function esm(exports,bindings){defineProp(exports,"__esModule",{value:!0}),toStringTag&&defineProp(exports,toStringTag,{value:"Module"});let i=0;for(;i<bindings.length;){let propName=bindings[i++],tagOrFunction=bindings[i++];if("number"==typeof tagOrFunction)if(0===tagOrFunction)defineProp(exports,propName,{value:bindings[i++],enumerable:!0,writable:!1});else throw Error(`unexpected tag: ${tagOrFunction}`);else"function"==typeof bindings[i]?defineProp(exports,propName,{get:tagOrFunction,set:bindings[i++],enumerable:!0}):defineProp(exports,propName,{get:tagOrFunction,enumerable:!0})}Object.seal(exports)}function ensureDynamicExports(module,exports){let reexportedObjects=REEXPORTED_OBJECTS.get(module);return reexportedObjects||(REEXPORTED_OBJECTS.set(module,reexportedObjects=[]),module.exports=module.namespaceObject=new Proxy(exports,{get(target,prop){if(hasOwnProperty.call(target,prop)||"default"===prop||"__esModule"===prop)return Reflect.get(target,prop);for(let obj of reexportedObjects){let value=Reflect.get(obj,prop);if(void 0!==value)return value}},ownKeys(target){let keys=Reflect.ownKeys(target);for(let obj of reexportedObjects)for(let key of Reflect.ownKeys(obj))"default"===key||keys.includes(key)||keys.push(key);return keys}})),reexportedObjects}function exportValue(value,id){(null!=id?getOverwrittenModule(this.c,id):this.m).exports=value}function createGetter(obj,key){return()=>obj[key]}contextPrototype.s=function esmExport(bindings,id){let module,exports;null!=id?exports=(module=getOverwrittenModule(this.c,id)).exports:(module=this.m,exports=this.e),module.namespaceObject=exports,esm(exports,bindings)},contextPrototype.j=function dynamicExport(object,id){let module,exports;null!=id?exports=(module=getOverwrittenModule(this.c,id)).exports:(module=this.m,exports=this.e);let reexportedObjects=ensureDynamicExports(module,exports);"object"==typeof object&&null!==object&&reexportedObjects.push(object)},contextPrototype.v=exportValue,contextPrototype.n=function exportNamespace(namespace,id){let module;(module=null!=id?getOverwrittenModule(this.c,id):this.m).exports=module.namespaceObject=namespace};let getProto=Object.getPrototypeOf?obj=>Object.getPrototypeOf(obj):obj=>obj.__proto__,LEAF_PROTOTYPES=[null,getProto({}),getProto([]),getProto(getProto)];function interopEsm(raw,ns,allowExportDefault){let bindings=[],defaultLocation=-1;for(let current=raw;("object"==typeof current||"function"==typeof current)&&!LEAF_PROTOTYPES.includes(current);current=getProto(current))for(let key of Object.getOwnPropertyNames(current))bindings.push(key,createGetter(raw,key)),-1===defaultLocation&&"default"===key&&(defaultLocation=bindings.length-1);return allowExportDefault&&defaultLocation>=0||(defaultLocation>=0?bindings.splice(defaultLocation,1,0,raw):bindings.push("default",0,raw)),esm(ns,bindings),ns}function createNS(raw){return"function"==typeof raw?function(...args){return raw.apply(this,args)}:Object.create(null)}function esmImport(id){let module=getOrInstantiateModuleFromParent(id,this.m);if(module.namespaceObject)return module.namespaceObject;let raw=module.exports;return module.namespaceObject=interopEsm(raw,createNS(raw),raw&&raw.__esModule)}function parseRequest(request){let hashIndex=request.indexOf("#");-1!==hashIndex&&(request=request.substring(0,hashIndex));let queryIndex=request.indexOf("?");return -1!==queryIndex&&(request=request.substring(0,queryIndex)),request}function getChunkPath(chunkData){return"string"==typeof chunkData?chunkData:chunkData.path}function isPromise(maybePromise){return null!=maybePromise&&"object"==typeof maybePromise&&"then"in maybePromise&&"function"==typeof maybePromise.then}function isAsyncModuleExt(obj){return turbopackQueues in obj}function createPromise(){let resolve,reject;return{promise:new Promise((res,rej)=>{reject=rej,resolve=res}),resolve:resolve,reject:reject}}function installCompressedModuleFactories(chunkModules,offset,moduleFactories,newModuleId){let i=offset;for(;i<chunkModules.length;){let existingGroupFactory,end=i+1;for(;end<chunkModules.length&&"function"!=typeof chunkModules[end];)end++;if(end===chunkModules.length)throw Error("malformed chunk format, expected a factory function");let moduleFactoryFn=chunkModules[end];for(let j=i;j<end;j++){let id=chunkModules[j],existingFactory=moduleFactories.get(id);if(existingFactory){existingGroupFactory=existingFactory;break}}let factoryToInstall=existingGroupFactory??moduleFactoryFn,didInstallFactory=!1;for(let j=i;j<end;j++){let id=chunkModules[j];moduleFactories.has(id)||(didInstallFactory||(factoryToInstall===moduleFactoryFn&&applyModuleFactoryName(moduleFactoryFn),didInstallFactory=!0),moduleFactories.set(id,factoryToInstall),newModuleId?.(id))}i=end+1}}contextPrototype.i=esmImport,contextPrototype.A=function asyncLoader(moduleId){return this.r(moduleId)(esmImport.bind(this))},contextPrototype.t="function"==typeof require?require:function require1(){throw Error("Unexpected use of runtime require")},contextPrototype.r=function commonJsRequire(id){return getOrInstantiateModuleFromParent(id,this.m).exports},contextPrototype.f=function moduleContext(map){function moduleContext(id){if(id=parseRequest(id),hasOwnProperty.call(map,id))return map[id].module();let e=Error(`Cannot find module '${id}'`);throw e.code="MODULE_NOT_FOUND",e}return moduleContext.keys=()=>Object.keys(map),moduleContext.resolve=id=>{if(id=parseRequest(id),hasOwnProperty.call(map,id))return map[id].id();let e=Error(`Cannot find module '${id}'`);throw e.code="MODULE_NOT_FOUND",e},moduleContext.import=async id=>await moduleContext(id),moduleContext};let turbopackQueues=Symbol("turbopack queues"),turbopackExports=Symbol("turbopack exports"),turbopackError=Symbol("turbopack error");function resolveQueue(queue){queue&&1!==queue.status&&(queue.status=1,queue.forEach(fn=>fn.queueCount--),queue.forEach(fn=>fn.queueCount--?fn.queueCount++:fn()))}function wrapDeps(deps){return deps.map(dep=>{if(null!==dep&&"object"==typeof dep){if(isAsyncModuleExt(dep))return dep;if(isPromise(dep)){let queue=Object.assign([],{status:0}),obj={[turbopackExports]:{},[turbopackQueues]:fn=>fn(queue)};return dep.then(res=>{obj[turbopackExports]=res,resolveQueue(queue)},err=>{obj[turbopackError]=err,resolveQueue(queue)}),obj}}return{[turbopackExports]:dep,[turbopackQueues]:()=>{}}})}contextPrototype.a=function asyncModule(body,hasAwait){let module=this.m,queue=hasAwait?Object.assign([],{status:-1}):void 0,depQueues=new Set,{resolve,reject,promise:rawPromise}=createPromise(),promise=Object.assign(rawPromise,{[turbopackExports]:module.exports,[turbopackQueues]:fn=>{queue&&fn(queue),depQueues.forEach(fn),promise.catch(()=>{})}}),attributes={get:()=>promise,set(v){v!==promise&&(promise[turbopackExports]=v)}};Object.defineProperty(module,"exports",attributes),Object.defineProperty(module,"namespaceObject",attributes),body(function handleAsyncDependencies(deps){let currentDeps=wrapDeps(deps),getResult=()=>currentDeps.map(d=>{if(d[turbopackError])throw d[turbopackError];return d[turbopackExports]}),{promise,resolve}=createPromise(),fn=Object.assign(()=>resolve(getResult),{queueCount:0});function fnQueue(q){q!==queue&&!depQueues.has(q)&&(depQueues.add(q),q&&0===q.status&&(fn.queueCount++,q.push(fn)))}return currentDeps.map(dep=>dep[turbopackQueues](fnQueue)),fn.queueCount?promise:getResult()},function asyncResult(err){err?reject(promise[turbopackError]=err):resolve(promise[turbopackExports]),resolveQueue(queue)}),queue&&-1===queue.status&&(queue.status=0)};let relativeURL=function relativeURL(inputUrl){let realUrl=new URL(inputUrl,"x:/"),values={};for(let key in realUrl)values[key]=realUrl[key];for(let key in values.href=inputUrl,values.pathname=inputUrl.replace(/[?#].*/,""),values.origin=values.protocol="",values.toString=values.toJSON=(..._args)=>inputUrl,values)Object.defineProperty(this,key,{enumerable:!0,configurable:!0,value:values[key]})};function invariant(never,computeMessage){throw Error(`Invariant: ${computeMessage(never)}`)}function factoryNotAvailableMessage(moduleId,sourceType,sourceData){let instantiationReason;switch(sourceType){case 0:instantiationReason=`as a runtime entry of chunk ${sourceData}`;break;case 1:instantiationReason=`because it was required from module ${sourceData}`;break;case 2:instantiationReason="because of an HMR update";break;default:invariant(sourceType,sourceType=>`Unknown source type: ${sourceType}`)}return`Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`}function applyModuleFactoryName(factory){Object.defineProperty(factory,"name",{value:"module evaluation"})}relativeURL.prototype=URL.prototype,contextPrototype.U=relativeURL,contextPrototype.z=function requireStub(_moduleId){throw Error("dynamic usage of require is not supported")},contextPrototype.g=globalThis;let browserContextPrototype=Context.prototype,moduleFactories=new Map;contextPrototype.M=moduleFactories;let availableModules=new Map,availableModuleChunks=new Map;function loadInitialChunk(chunkPath,chunkData){return loadChunkInternal(SourceType1.Runtime,chunkPath,chunkData)}async function loadChunkInternal(sourceType,sourceData,chunkData){let promise;if("string"==typeof chunkData)return loadChunkByUrlInternal(sourceType,sourceData,getChunkRelativeUrl(chunkData));let includedList=chunkData.included||[],modulesPromises=includedList.map(included=>!!moduleFactories.has(included)||availableModules.get(included));if(modulesPromises.length>0&&modulesPromises.every(p=>p))return void await Promise.all(modulesPromises);let includedModuleChunksList=chunkData.moduleChunks||[],moduleChunksPromises=includedModuleChunksList.map(included=>availableModuleChunks.get(included)).filter(p=>p);if(moduleChunksPromises.length>0){if(moduleChunksPromises.length===includedModuleChunksList.length)return void await Promise.all(moduleChunksPromises);let moduleChunksToLoad=new Set;for(let moduleChunk of includedModuleChunksList)availableModuleChunks.has(moduleChunk)||moduleChunksToLoad.add(moduleChunk);for(let moduleChunkToLoad of moduleChunksToLoad){let promise=loadChunkByUrlInternal(sourceType,sourceData,getChunkRelativeUrl(moduleChunkToLoad));availableModuleChunks.set(moduleChunkToLoad,promise),moduleChunksPromises.push(promise)}promise=Promise.all(moduleChunksPromises)}else{for(let includedModuleChunk of(promise=loadChunkByUrlInternal(sourceType,sourceData,getChunkRelativeUrl(chunkData.path)),includedModuleChunksList))availableModuleChunks.has(includedModuleChunk)||availableModuleChunks.set(includedModuleChunk,promise)}for(let included of includedList)availableModules.has(included)||availableModules.set(included,promise);await promise}browserContextPrototype.l=function loadChunk(chunkData){return loadChunkInternal(SourceType1.Parent,this.m.id,chunkData)};let loadedChunk=Promise.resolve(void 0),instrumentedBackendLoadChunks=new WeakMap;function loadChunkByUrlInternal(sourceType,sourceData,chunkUrl){let thenable=BACKEND.loadChunkCached(sourceType,chunkUrl),entry=instrumentedBackendLoadChunks.get(thenable);if(void 0===entry){let resolve=instrumentedBackendLoadChunks.set.bind(instrumentedBackendLoadChunks,thenable,loadedChunk);entry=thenable.then(resolve).catch(cause=>{let loadReason;switch(sourceType){case SourceType1.Runtime:loadReason=`as a runtime dependency of chunk ${sourceData}`;break;case SourceType1.Parent:loadReason=`from module ${sourceData}`;break;case SourceType1.Update:loadReason="from an HMR update";break;default:invariant(sourceType,sourceType=>`Unknown source type: ${sourceType}`)}let error=Error(`Failed to load chunk ${chunkUrl} ${loadReason}${cause?`: ${cause}`:""}`,cause?{cause}:void 0);throw error.name="ChunkLoadError",error}),instrumentedBackendLoadChunks.set(thenable,entry)}return entry}function getChunkRelativeUrl(chunkPath){return`${CHUNK_BASE_PATH}${chunkPath.split("/").map(p=>encodeURIComponent(p)).join("/")}${ASSET_SUFFIX}`}function getPathFromScript(chunkScript){if("string"==typeof chunkScript)return chunkScript;let src=decodeURIComponent(chunkScript.src.replace(/[?#].*$/,""));return src.startsWith(CHUNK_BASE_PATH)?src.slice(CHUNK_BASE_PATH.length):src}function getUrlFromScript(chunk){return"string"==typeof chunk?getChunkRelativeUrl(chunk):chunk.src}function getChunkFromRegistration(chunk){if("string"==typeof chunk)return chunk;if(chunk)return{src:chunk.getAttribute("src")};if("u">typeof TURBOPACK_NEXT_CHUNK_URLS)return{src:TURBOPACK_NEXT_CHUNK_URLS.pop()};throw Error("chunk path empty but not in a worker")}browserContextPrototype.L=function loadChunkByUrl(chunkUrl){return loadChunkByUrlInternal(SourceType1.Parent,this.m.id,chunkUrl)},browserContextPrototype.R=function resolvePathFromModule(moduleId){let exported=this.r(moduleId);return exported?.default??exported},browserContextPrototype.P=function resolveAbsolutePath(modulePath){return`/ROOT/${modulePath??""}`},browserContextPrototype.q=function exportUrl(url,id){exportValue.call(this,`${url}${ASSET_SUFFIX}`,id)},browserContextPrototype.b=function createWorker(WorkerConstructor,entrypoint,moduleChunks,workerOptions){let isSharedWorker="SharedWorker"===WorkerConstructor.name,params=[moduleChunks.map(chunk=>getChunkRelativeUrl(chunk)).reverse(),ASSET_SUFFIX];for(let globalName of WORKER_FORWARDED_GLOBALS)params.push(globalThis[globalName]);let url=new URL(getChunkRelativeUrl(entrypoint),location.origin),paramsJson=JSON.stringify(params);return isSharedWorker?url.searchParams.set("params",paramsJson):url.hash="#params="+encodeURIComponent(paramsJson),new WorkerConstructor(url,workerOptions?{...workerOptions,type:void 0}:void 0)};let regexJsUrl=/\.js(?:\?[^#]*)?(?:#.*)?$/,regexCssUrl=/\.css(?:\?[^#]*)?(?:#.*)?$/;function isCss(chunkUrl){return regexCssUrl.test(chunkUrl)}contextPrototype.w=function loadWebAssembly(chunkPath,edgeModule,importsObj){return BACKEND.loadWebAssembly(SourceType1.Parent,this.m.id,chunkPath,edgeModule,importsObj)},contextPrototype.u=function loadWebAssemblyModule(chunkPath,edgeModule){return BACKEND.loadWebAssemblyModule(SourceType1.Parent,this.m.id,chunkPath,edgeModule)};let moduleCache={};function getOrInstantiateRuntimeModule(chunkPath,moduleId){let module=moduleCache[moduleId];if(module){if(module.error)throw module.error;return module}return instantiateModule(moduleId,SourceType1.Runtime,chunkPath)}contextPrototype.c=moduleCache;let getOrInstantiateModuleFromParent=(id,sourceModule)=>{let module=moduleCache[id];if(module){if(module.error)throw module.error;return module}return instantiateModule(id,SourceType1.Parent,sourceModule.id)};function instantiateModule(id,sourceType,sourceData){let moduleFactory=moduleFactories.get(id);if("function"!=typeof moduleFactory)throw Error(factoryNotAvailableMessage(id,sourceType,sourceData));let module=createModuleObject(id),exports=module.exports;moduleCache[id]=module;let context=new Context(module,exports);try{moduleFactory(context,module,exports)}catch(error){throw module.error=error,error}return module.namespaceObject&&module.exports!==module.namespaceObject&&interopEsm(module.exports,module.namespaceObject),module}function registerChunk(registration){let runtimeParams,chunk=getChunkFromRegistration(registration[0]);return 2===registration.length?runtimeParams=registration[1]:(runtimeParams=void 0,installCompressedModuleFactories(registration,1,moduleFactories)),BACKEND.registerChunk(chunk,runtimeParams)}function getAssetSuffixFromScriptSrc(){if(null!=self.TURBOPACK_ASSET_SUFFIX)return self.TURBOPACK_ASSET_SUFFIX;let src=document?.currentScript?.getAttribute?.("src")??"",qi=src.indexOf("?");return qi>=0?src.slice(qi):""}let chunkResolvers=new Map;function getOrCreateResolver(chunkUrl){let resolver=chunkResolvers.get(chunkUrl);if(!resolver){let resolve,reject;resolver={resolved:!1,loadingStarted:!1,promise:new Promise((innerResolve,innerReject)=>{resolve=innerResolve,reject=innerReject}),resolve:()=>{resolver.resolved=!0,resolve()},reject:reject},chunkResolvers.set(chunkUrl,resolver)}return resolver}function doLoadChunk(sourceType,chunkUrl){let resolver=getOrCreateResolver(chunkUrl);if(resolver.loadingStarted)return resolver.promise;if(sourceType===SourceType1.Runtime)return resolver.loadingStarted=!0,isCss(chunkUrl)&&resolver.resolve(),resolver.promise;if("function"==typeof importScripts)if(isCss(chunkUrl));else if(regexJsUrl.test(chunkUrl))self.TURBOPACK_NEXT_CHUNK_URLS.push(chunkUrl),importScripts(chunkUrl);else throw Error(`can't infer type of chunk from URL ${chunkUrl} in worker`);else{let decodedChunkUrl=decodeURI(chunkUrl);if(isCss(chunkUrl))if(document.querySelectorAll(`link[rel=stylesheet][href="${chunkUrl}"],link[rel=stylesheet][href^="${chunkUrl}?"],link[rel=stylesheet][href="${decodedChunkUrl}"],link[rel=stylesheet][href^="${decodedChunkUrl}?"]`).length>0)resolver.resolve();else{let link=document.createElement("link");link.rel="stylesheet",link.href=chunkUrl,link.onerror=()=>{resolver.reject()},link.onload=()=>{resolver.resolve()},document.head.appendChild(link)}else if(regexJsUrl.test(chunkUrl)){let previousScripts=document.querySelectorAll(`script[src="${chunkUrl}"],script[src^="${chunkUrl}?"],script[src="${decodedChunkUrl}"],script[src^="${decodedChunkUrl}?"]`);if(previousScripts.length>0)for(let script of Array.from(previousScripts))script.addEventListener("error",()=>{resolver.reject()});else{let script=document.createElement("script");script.src=chunkUrl,script.onerror=()=>{resolver.reject()},document.head.appendChild(script)}}else throw Error(`can't infer type of chunk from URL ${chunkUrl}`)}return resolver.loadingStarted=!0,resolver.promise}BACKEND={async registerChunk(chunk,params){let chunkPath=getPathFromScript(chunk);if(getOrCreateResolver(getUrlFromScript(chunk)).resolve(),null!=params){for(let otherChunkData of params.otherChunks)getOrCreateResolver(getChunkRelativeUrl(getChunkPath(otherChunkData)));if(await Promise.all(params.otherChunks.map(otherChunkData=>loadInitialChunk(chunkPath,otherChunkData))),params.runtimeModuleIds.length>0)for(let moduleId of params.runtimeModuleIds)getOrInstantiateRuntimeModule(chunkPath,moduleId)}},loadChunkCached:(sourceType,chunkUrl)=>doLoadChunk(sourceType,chunkUrl),async loadWebAssembly(_sourceType,_sourceData,wasmChunkPath,_edgeModule,importsObj){let req=fetch(getChunkRelativeUrl(wasmChunkPath)),{instance}=await WebAssembly.instantiateStreaming(req,importsObj);return instance.exports},async loadWebAssemblyModule(_sourceType,_sourceData,wasmChunkPath,_edgeModule){let req=fetch(getChunkRelativeUrl(wasmChunkPath));return await WebAssembly.compileStreaming(req)}};let chunksToRegister=globalThis.TURBOPACK;globalThis.TURBOPACK={push:registerChunk},chunksToRegister.forEach(registerChunk)})(); |
| self.__BUILD_MANIFEST = { | ||
| "__rewrites": { | ||
| "afterFiles": [], | ||
| "beforeFiles": [], | ||
| "fallback": [] | ||
| }, | ||
| "sortedPages": [ | ||
| "/_app", | ||
| "/_error" | ||
| ] | ||
| };self.__BUILD_MANIFEST_CB && self.__BUILD_MANIFEST_CB() |
| self.__MIDDLEWARE_MATCHERS = [];self.__MIDDLEWARE_MATCHERS_CB && self.__MIDDLEWARE_MATCHERS_CB() |
| self.__SSG_MANIFEST=new Set([]);self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB() |
| (()=>{var e={234:e=>{"use strict";var t=Object.prototype.hasOwnProperty,r="~";function Events(){}if(Object.create){Events.prototype=Object.create(null);if(!(new Events).__proto__)r=false}function EE(e,t,r){this.fn=e;this.context=t;this.once=r||false}function addListener(e,t,o,s,n){if(typeof o!=="function"){throw new TypeError("The listener must be a function")}var i=new EE(o,s||e,n),a=r?r+t:t;if(!e._events[a])e._events[a]=i,e._eventsCount++;else if(!e._events[a].fn)e._events[a].push(i);else e._events[a]=[e._events[a],i];return e}function clearEvent(e,t){if(--e._eventsCount===0)e._events=new Events;else delete e._events[t]}function EventEmitter(){this._events=new Events;this._eventsCount=0}EventEmitter.prototype.eventNames=function eventNames(){var e=[],o,s;if(this._eventsCount===0)return e;for(s in o=this._events){if(t.call(o,s))e.push(r?s.slice(1):s)}if(Object.getOwnPropertySymbols){return e.concat(Object.getOwnPropertySymbols(o))}return e};EventEmitter.prototype.listeners=function listeners(e){var t=r?r+e:e,o=this._events[t];if(!o)return[];if(o.fn)return[o.fn];for(var s=0,n=o.length,i=new Array(n);s<n;s++){i[s]=o[s].fn}return i};EventEmitter.prototype.listenerCount=function listenerCount(e){var t=r?r+e:e,o=this._events[t];if(!o)return 0;if(o.fn)return 1;return o.length};EventEmitter.prototype.emit=function emit(e,t,o,s,n,i){var a=r?r+e:e;if(!this._events[a])return false;var c=this._events[a],u=arguments.length,f,h;if(c.fn){if(c.once)this.removeListener(e,c.fn,undefined,true);switch(u){case 1:return c.fn.call(c.context),true;case 2:return c.fn.call(c.context,t),true;case 3:return c.fn.call(c.context,t,o),true;case 4:return c.fn.call(c.context,t,o,s),true;case 5:return c.fn.call(c.context,t,o,s,n),true;case 6:return c.fn.call(c.context,t,o,s,n,i),true}for(h=1,f=new Array(u-1);h<u;h++){f[h-1]=arguments[h]}c.fn.apply(c.context,f)}else{var p=c.length,d;for(h=0;h<p;h++){if(c[h].once)this.removeListener(e,c[h].fn,undefined,true);switch(u){case 1:c[h].fn.call(c[h].context);break;case 2:c[h].fn.call(c[h].context,t);break;case 3:c[h].fn.call(c[h].context,t,o);break;case 4:c[h].fn.call(c[h].context,t,o,s);break;default:if(!f)for(d=1,f=new Array(u-1);d<u;d++){f[d-1]=arguments[d]}c[h].fn.apply(c[h].context,f)}}}return true};EventEmitter.prototype.on=function on(e,t,r){return addListener(this,e,t,r,false)};EventEmitter.prototype.once=function once(e,t,r){return addListener(this,e,t,r,true)};EventEmitter.prototype.removeListener=function removeListener(e,t,o,s){var n=r?r+e:e;if(!this._events[n])return this;if(!t){clearEvent(this,n);return this}var i=this._events[n];if(i.fn){if(i.fn===t&&(!s||i.once)&&(!o||i.context===o)){clearEvent(this,n)}}else{for(var a=0,c=[],u=i.length;a<u;a++){if(i[a].fn!==t||s&&!i[a].once||o&&i[a].context!==o){c.push(i[a])}}if(c.length)this._events[n]=c.length===1?c[0]:c;else clearEvent(this,n)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(e){var t;if(e){t=r?r+e:e;if(this._events[t])clearEvent(this,t)}else{this._events=new Events;this._eventsCount=0}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=r;EventEmitter.EventEmitter=EventEmitter;if(true){e.exports=EventEmitter}},215:(e,t,r)=>{var o=r(16);var s=o.URL;var n=r(611);var i=r(692);var a=r(613);var c=r(203).Writable;var u=r(527)("follow-redirects");var f={GET:true,HEAD:true,OPTIONS:true,TRACE:true};var h=Object.create(null);["abort","aborted","connect","error","socket","timeout"].forEach((function(e){h[e]=function(t,r,o){this._redirectable.emit(e,t,r,o)}}));function RedirectableRequest(e,t){c.call(this);this._sanitizeOptions(e);this._options=e;this._ended=false;this._ending=false;this._redirectCount=0;this._redirects=[];this._requestBodyLength=0;this._requestBodyBuffers=[];if(t){this.on("response",t)}var r=this;this._onNativeResponse=function(e){r._processResponse(e)};this._performRequest()}RedirectableRequest.prototype=Object.create(c.prototype);RedirectableRequest.prototype.write=function(e,t,r){if(this._ending){throw new Error("write after end")}if(!(typeof e==="string"||typeof e==="object"&&"length"in e)){throw new Error("data should be a string, Buffer or Uint8Array")}if(typeof t==="function"){r=t;t=null}if(e.length===0){if(r){r()}return}if(this._requestBodyLength+e.length<=this._options.maxBodyLength){this._requestBodyLength+=e.length;this._requestBodyBuffers.push({data:e,encoding:t});this._currentRequest.write(e,t,r)}else{this.emit("error",new Error("Request body larger than maxBodyLength limit"));this.abort()}};RedirectableRequest.prototype.end=function(e,t,r){if(typeof e==="function"){r=e;e=t=null}else if(typeof t==="function"){r=t;t=null}if(!e){this._ended=this._ending=true;this._currentRequest.end(null,null,r)}else{var o=this;var s=this._currentRequest;this.write(e,t,(function(){o._ended=true;s.end(null,null,r)}));this._ending=true}};RedirectableRequest.prototype.setHeader=function(e,t){this._options.headers[e]=t;this._currentRequest.setHeader(e,t)};RedirectableRequest.prototype.removeHeader=function(e){delete this._options.headers[e];this._currentRequest.removeHeader(e)};RedirectableRequest.prototype.setTimeout=function(e,t){if(t){this.once("timeout",t)}if(this.socket){startTimer(this,e)}else{var r=this;this._currentRequest.once("socket",(function(){startTimer(r,e)}))}this.once("response",clearTimer);this.once("error",clearTimer);return this};function startTimer(e,t){clearTimeout(e._timeout);e._timeout=setTimeout((function(){e.emit("timeout")}),t)}function clearTimer(){clearTimeout(this._timeout)}["abort","flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach((function(e){RedirectableRequest.prototype[e]=function(t,r){return this._currentRequest[e](t,r)}}));["aborted","connection","socket"].forEach((function(e){Object.defineProperty(RedirectableRequest.prototype,e,{get:function(){return this._currentRequest[e]}})}));RedirectableRequest.prototype._sanitizeOptions=function(e){if(!e.headers){e.headers={}}if(e.host){if(!e.hostname){e.hostname=e.host}delete e.host}if(!e.pathname&&e.path){var t=e.path.indexOf("?");if(t<0){e.pathname=e.path}else{e.pathname=e.path.substring(0,t);e.search=e.path.substring(t)}}};RedirectableRequest.prototype._performRequest=function(){var e=this._options.protocol;var t=this._options.nativeProtocols[e];if(!t){this.emit("error",new Error("Unsupported protocol "+e));return}if(this._options.agents){var r=e.substr(0,e.length-1);this._options.agent=this._options.agents[r]}var s=this._currentRequest=t.request(this._options,this._onNativeResponse);this._currentUrl=o.format(this._options);s._redirectable=this;for(var n in h){if(n){s.on(n,h[n])}}if(this._isRedirect){var i=0;var a=this;var c=this._requestBodyBuffers;(function writeNext(e){if(s===a._currentRequest){if(e){a.emit("error",e)}else if(i<c.length){var t=c[i++];if(!s.finished){s.write(t.data,t.encoding,writeNext)}}else if(a._ended){s.end()}}})()}};RedirectableRequest.prototype._processResponse=function(e){var t=e.statusCode;if(this._options.trackRedirects){this._redirects.push({url:this._currentUrl,headers:e.headers,statusCode:t})}var r=e.headers.location;if(r&&this._options.followRedirects!==false&&t>=300&&t<400){this._currentRequest.removeAllListeners();this._currentRequest.on("error",noop);this._currentRequest.abort();e.destroy();if(++this._redirectCount>this._options.maxRedirects){this.emit("error",new Error("Max redirects exceeded."));return}var s;var n=this._options.headers;if(t!==307&&!(this._options.method in f)){this._options.method="GET";this._requestBodyBuffers=[];for(s in n){if(/^content-/i.test(s)){delete n[s]}}}if(!this._isRedirect){for(s in n){if(/^host$/i.test(s)){delete n[s]}}}var i=o.resolve(this._currentUrl,r);u("redirecting to",i);Object.assign(this._options,o.parse(i));if(typeof this._options.beforeRedirect==="function"){try{this._options.beforeRedirect.call(null,this._options)}catch(e){this.emit("error",e);return}this._sanitizeOptions(this._options)}this._isRedirect=true;this._performRequest()}else{e.responseUrl=this._currentUrl;e.redirects=this._redirects;this.emit("response",e);this._requestBodyBuffers=[]}};function wrap(e){var t={maxRedirects:21,maxBodyLength:10*1024*1024};var r={};Object.keys(e).forEach((function(n){var i=n+":";var c=r[i]=e[n];var f=t[n]=Object.create(c);f.request=function(e,n,c){if(typeof e==="string"){var f=e;try{e=urlToOptions(new s(f))}catch(t){e=o.parse(f)}}else if(s&&e instanceof s){e=urlToOptions(e)}else{c=n;n=e;e={protocol:i}}if(typeof n==="function"){c=n;n=null}n=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},e,n);n.nativeProtocols=r;a.equal(n.protocol,i,"protocol mismatch");u("options",n);return new RedirectableRequest(n,c)};f.get=function(e,t,r){var o=f.request(e,t,r);o.end();return o}}));return t}function noop(){}function urlToOptions(e){var t={protocol:e.protocol,hostname:e.hostname.startsWith("[")?e.hostname.slice(1,-1):e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:e.pathname+e.search,href:e.href};if(e.port!==""){t.port=Number(e.port)}return t}e.exports=wrap({http:n,https:i});e.exports.wrap=wrap},598:(e,t,r)=>{ | ||
| /*! | ||
| * Caron dimonio, con occhi di bragia | ||
| * loro accennando, tutte le raccoglie; | ||
| * batte col remo qualunque s’adagia | ||
| * | ||
| * Charon the demon, with the eyes of glede, | ||
| * Beckoning to them, collects them all together, | ||
| * Beats with his oar whoever lags behind | ||
| * | ||
| * Dante - The Divine Comedy (Canto III) | ||
| */ | ||
| e.exports=r(73)},73:(e,t,r)=>{var o=r(250).Server;function createProxyServer(e){return new o(e)}o.createProxyServer=createProxyServer;o.createServer=createProxyServer;o.createProxy=createProxyServer;e.exports=o},285:(e,t,r)=>{var o=t,s=r(213).parseUrl,n=r(866);var i=/(^|,)\s*upgrade\s*($|,)/i,a=/(^|,)\s*transfer-encoding\s*($|,)/i,c=/^https|wss/;o.isSSL=c;o.parseUrl=function(e){var t=s(e);var r=t.hostname;return Object.assign(t,{host:r?r+(t.port?":"+t.port:""):r,hostname:r&&r.startsWith("[")?r.slice(1,-1):r,path:t.pathname+t.search})};o.setupOutgoing=function(e,t,r,s){e.port=t[s||"target"].port||(c.test(t[s||"target"].protocol)?443:80);["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach((function(r){e[r]=t[s||"target"][r]}));e.method=t.method||r.method;e.headers=Object.assign({},r.headers);if(t.headers){Object.assign(e.headers,t.headers)}if(t.auth){e.auth=t.auth}if(t.ca){e.ca=t.ca}if(c.test(t[s||"target"].protocol)){e.rejectUnauthorized=typeof t.secure==="undefined"?true:t.secure}e.agent=t.agent||false;e.localAddress=t.localAddress;e.headers=e.headers||{};var u=Object.keys(e.headers).some((function(t){return t.toLowerCase()==="transfer-encoding"&&typeof e.headers[t]!=="undefined"}));if(u||typeof e.headers.connection==="string"&&a.test(e.headers.connection)){e.headers.connection="close"}if(!e.agent){if(typeof e.headers.connection!=="string"||!i.test(e.headers.connection)){e.headers.connection="close"}}var f=t[s||"target"];var h=f&&t.prependPath!==false?f.path||"":"";var p=!t.toProxy?o.parseUrl(r.url).path||"":r.url;p=!t.ignorePath?p:"";e.path=o.urlJoin(h,p);if(t.changeOrigin){e.headers.host=n(e.port,t[s||"target"].protocol)&&!hasPort(e.host)?e.host+":"+e.port:e.host}return e};o.setupSocket=function(e){e.setTimeout(0);e.setNoDelay(true);e.setKeepAlive(true,0);return e};o.getPort=function(e){var t=e.headers.host?e.headers.host.match(/:(\d+)/):"";return t?t[1]:o.hasEncryptedConnection(e)?"443":"80"};o.hasEncryptedConnection=function(e){return Boolean(e.connection.encrypted||e.connection.pair)};o.urlJoin=function(){var e=Array.prototype.slice.call(arguments),t=e.length-1,r=e[t],o=r.split("?"),s;e[t]=o.shift();s=[e.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://")];s.push.apply(s,o);return s.join("?")};o.rewriteCookieProperty=function rewriteCookieProperty(e,t,r){if(Array.isArray(e)){return e.map((function(e){return rewriteCookieProperty(e,t,r)}))}return e.replace(new RegExp("(;\\s*"+r+"=)([^;]+)","i"),(function(e,r,o){var s;if(o in t){s=t[o]}else if("*"in t){s=t["*"]}else{return e}if(s){return r+s}else{return""}}))};function hasPort(e){return!!~e.indexOf(":")}},250:(e,t,r)=>{var o=e.exports,s=r(285).parseUrl,n=r(234),i=r(611),a=r(692),c=r(5),u=r(683);o.Server=ProxyServer;function createRightProxy(e){return function(t){return function(r,o){var n=e==="ws"?this.wsPasses:this.webPasses,i=[].slice.call(arguments),a=i.length-1,c,u;if(typeof i[a]==="function"){u=i[a];a--}var f=t;if(!(i[a]instanceof Buffer)&&i[a]!==o){f=Object.assign({},t);Object.assign(f,i[a]);a--}if(i[a]instanceof Buffer){c=i[a]}["target","forward"].forEach((function(e){if(typeof f[e]==="string")f[e]=s(f[e])}));if(!f.target&&!f.forward){return this.emit("error",new Error("Must provide a proper URL as target"))}for(var h=0;h<n.length;h++){if(n[h](r,o,f,c,this,u)){break}}}}}o.createRightProxy=createRightProxy;function ProxyServer(e){n.call(this);e=e||{};e.prependPath=e.prependPath===false?false:true;this.web=this.proxyRequest=createRightProxy("web")(e);this.ws=this.proxyWebsocketRequest=createRightProxy("ws")(e);this.options=e;this.webPasses=Object.keys(c).map((function(e){return c[e]}));this.wsPasses=Object.keys(u).map((function(e){return u[e]}));this.on("error",this.onError,this)}r(23).inherits(ProxyServer,n);ProxyServer.prototype.onError=function(e){if(this.listeners("error").length===1){throw e}};ProxyServer.prototype.listen=function(e,t){var r=this,closure=function(e,t){r.web(e,t)};this._server=this.options.ssl?a.createServer(this.options.ssl,closure):i.createServer(closure);if(this.options.ws){this._server.on("upgrade",(function(e,t,o){r.ws(e,t,o)}))}this._server.listen(e,t);return this};ProxyServer.prototype.close=function(e){var t=this;if(this._server){this._server.close(done)}function done(){t._server=null;if(e){e.apply(null,arguments)}}};ProxyServer.prototype.before=function(e,t,r){if(e!=="ws"&&e!=="web"){throw new Error("type must be `web` or `ws`")}var o=e==="ws"?this.wsPasses:this.webPasses,s=false;o.forEach((function(e,r){if(e.name===t)s=r}));if(s===false)throw new Error("No such pass");o.splice(s,0,r)};ProxyServer.prototype.after=function(e,t,r){if(e!=="ws"&&e!=="web"){throw new Error("type must be `web` or `ws`")}var o=e==="ws"?this.wsPasses:this.webPasses,s=false;o.forEach((function(e,r){if(e.name===t)s=r}));if(s===false)throw new Error("No such pass");o.splice(s++,0,r)}},5:(e,t,r)=>{var o=r(611),s=r(692),n=r(91),i=r(285),a=r(215);n=Object.keys(n).map((function(e){return n[e]}));var c={http:o,https:s}; | ||
| /*! | ||
| * Array of passes. | ||
| * | ||
| * A `pass` is just a function that is executed on `req, res, options` | ||
| * so that you can easily add new checks while still keeping the base | ||
| * flexible. | ||
| */e.exports={deleteLength:function deleteLength(e,t,r){if((e.method==="DELETE"||e.method==="OPTIONS")&&typeof e.headers["content-length"]==="undefined"&&typeof e.headers["transfer-encoding"]==="undefined"){e.headers["content-length"]="0"}},timeout:function timeout(e,t,r){if(r.timeout){e.socket.setTimeout(r.timeout)}},XHeaders:function XHeaders(e,t,r){if(!r.xfwd)return;var o=e.isSpdy||i.hasEncryptedConnection(e);var s={for:e.connection.remoteAddress||e.socket.remoteAddress,port:i.getPort(e),proto:o?"https":"http"};["for","port","proto"].forEach((function(t){e.headers["x-forwarded-"+t]=(e.headers["x-forwarded-"+t]||"")+(e.headers["x-forwarded-"+t]?",":"")+s[t]}));e.headers["x-forwarded-host"]=e.headers["x-forwarded-host"]||e.headers["host"]||""},stream:function stream(e,t,r,o,s,u){s.emit("start",e,t,r.target||r.forward);var f=r.followRedirects?a:c;var h=f.http;var p=f.https;if(r.forward){var d=(r.forward.protocol==="https:"?p:h).request(i.setupOutgoing(r.ssl||{},r,e,"forward"));var l=createErrorHandler(d,r.forward);e.on("error",l);d.on("error",l);(r.buffer||e).pipe(d);if(!r.target){return t.end()}}var v=(r.target.protocol==="https:"?p:h).request(i.setupOutgoing(r.ssl||{},r,e));v.on("socket",(function(o){if(s&&!v.getHeader("expect")){s.emit("proxyReq",v,e,t,r)}}));if(r.proxyTimeout){v.setTimeout(r.proxyTimeout,(function(){v.abort()}))}e.on("aborted",(function(){v.abort()}));var m=createErrorHandler(v,r.target);e.on("error",m);v.on("error",m);function createErrorHandler(r,o){return function proxyError(n){if(e.socket.destroyed&&n.code==="ECONNRESET"){s.emit("econnreset",n,e,t,o);return r.abort()}if(u){u(n,e,t,o)}else{s.emit("error",n,e,t,o)}}}(r.buffer||e).pipe(v);v.on("response",(function(o){if(s){s.emit("proxyRes",o,e,t)}if(!t.headersSent&&!r.selfHandleResponse){for(var i=0;i<n.length;i++){if(n[i](e,t,o,r)){break}}}if(!t.finished){o.on("end",(function(){if(s)s.emit("end",e,t,o)}));if(!r.selfHandleResponse)o.pipe(t)}else{if(s)s.emit("end",e,t,o)}}))}}},91:(e,t,r)=>{var o=r(16),s=r(285);var n=/^201|30(1|2|7|8)$/; | ||
| /*! | ||
| * Array of passes. | ||
| * | ||
| * A `pass` is just a function that is executed on `req, res, options` | ||
| * so that you can easily add new checks while still keeping the base | ||
| * flexible. | ||
| */e.exports={removeChunked:function removeChunked(e,t,r){if(e.httpVersion==="1.0"){delete r.headers["transfer-encoding"]}},setConnection:function setConnection(e,t,r){if(e.httpVersion==="1.0"){r.headers.connection=e.headers.connection||"close"}else if(e.httpVersion!=="2.0"&&!r.headers.connection){r.headers.connection=e.headers.connection||"keep-alive"}},setRedirectHostRewrite:function setRedirectHostRewrite(e,t,r,i){if((i.hostRewrite||i.autoRewrite||i.protocolRewrite)&&r.headers["location"]&&n.test(r.statusCode)){var a=s.parseUrl(i.target);var c=s.parseUrl(r.headers["location"]);if(a.host!=c.host){return}if(i.hostRewrite){c.host=i.hostRewrite}else if(i.autoRewrite){c.host=e.headers["host"]}if(i.protocolRewrite){c.protocol=i.protocolRewrite}r.headers["location"]=o.format(c)}},writeHeaders:function writeHeaders(e,t,r,o){var n=o.cookieDomainRewrite,i=o.cookiePathRewrite,a=o.preserveHeaderKeyCase,c,setHeader=function(e,r){if(r==undefined)return;if(n&&e.toLowerCase()==="set-cookie"){r=s.rewriteCookieProperty(r,n,"domain")}if(i&&e.toLowerCase()==="set-cookie"){r=s.rewriteCookieProperty(r,i,"path")}t.setHeader(String(e).trim(),r)};if(typeof n==="string"){n={"*":n}}if(typeof i==="string"){i={"*":i}}if(a&&r.rawHeaders!=undefined){c={};for(var u=0;u<r.rawHeaders.length;u+=2){var f=r.rawHeaders[u];c[f.toLowerCase()]=f}}Object.keys(r.headers).forEach((function(e){var t=r.headers[e];if(a&&c){e=c[e]||e}setHeader(e,t)}))},writeStatusCode:function writeStatusCode(e,t,r){if(r.statusMessage){t.statusCode=r.statusCode;t.statusMessage=r.statusMessage}else{t.statusCode=r.statusCode}}}},683:(e,t,r)=>{var o=r(611),s=r(692),n=r(285); | ||
| /*! | ||
| * Array of passes. | ||
| * | ||
| * A `pass` is just a function that is executed on `req, socket, options` | ||
| * so that you can easily add new checks while still keeping the base | ||
| * flexible. | ||
| */e.exports={checkMethodAndHeader:function checkMethodAndHeader(e,t){if(e.method!=="GET"||!e.headers.upgrade){t.destroy();return true}if(e.headers.upgrade.toLowerCase()!=="websocket"){t.destroy();return true}},XHeaders:function XHeaders(e,t,r){if(!r.xfwd)return;var o={for:e.connection.remoteAddress||e.socket.remoteAddress,port:n.getPort(e),proto:n.hasEncryptedConnection(e)?"wss":"ws"};["for","port","proto"].forEach((function(t){e.headers["x-forwarded-"+t]=(e.headers["x-forwarded-"+t]||"")+(e.headers["x-forwarded-"+t]?",":"")+o[t]}))},stream:function stream(e,t,r,i,a,c){var createHttpHeader=function(e,t){return Object.keys(t).reduce((function(e,r){var o=t[r];if(!Array.isArray(o)){e.push(r+": "+o);return e}for(var s=0;s<o.length;s++){e.push(r+": "+o[s])}return e}),[e]).join("\r\n")+"\r\n\r\n"};n.setupSocket(t);if(i&&i.length)t.unshift(i);var u=(n.isSSL.test(r.target.protocol)?s:o).request(n.setupOutgoing(r.ssl||{},r,e));if(a){a.emit("proxyReqWs",u,e,t,r,i)}u.on("error",onOutgoingError);u.on("response",(function(e){if(!e.upgrade){t.write(createHttpHeader("HTTP/"+e.httpVersion+" "+e.statusCode+" "+e.statusMessage,e.headers));e.pipe(t)}}));u.on("upgrade",(function(e,r,o){r.on("error",onOutgoingError);r.on("end",(function(){a.emit("close",e,r,o)}));t.on("error",(function(){r.end()}));n.setupSocket(r);if(o&&o.length)r.unshift(o);t.write(createHttpHeader("HTTP/1.1 101 Switching Protocols",e.headers));r.pipe(t).pipe(r);a.emit("open",r);a.emit("proxySocket",r)}));return u.end();function onOutgoingError(r){if(c){c(r,e,t)}else{a.emit("error",r,e,t)}t.end()}}}},866:e=>{"use strict";e.exports=function required(e,t){t=t.split(":")[0];e=+e;if(!e)return false;switch(t){case"http":case"ws":return e!==80;case"https":case"wss":return e!==443;case"ftp":return e!==21;case"gopher":return e!==70;case"file":return false}return e!==0}},613:e=>{"use strict";e.exports=require("assert")},611:e=>{"use strict";e.exports=require("http")},692:e=>{"use strict";e.exports=require("https")},527:e=>{"use strict";e.exports=require("next/dist/compiled/debug")},213:e=>{"use strict";e.exports=require("next/dist/shared/lib/router/utils/parse-url")},203:e=>{"use strict";e.exports=require("stream")},16:e=>{"use strict";e.exports=require("url")},23:e=>{"use strict";e.exports=require("util")}};var t={};function __nccwpck_require__(r){var o=t[r];if(o!==undefined){return o.exports}var s=t[r]={exports:{}};var n=true;try{e[r](s,s.exports,__nccwpck_require__);n=false}finally{if(n)delete t[r]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(598);module.exports=r})(); |
| node-http-proxy | ||
| Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the 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. |
| {"name":"http-proxy","main":"index.js","author":"Charlie Robbins <charlie.robbins@gmail.com>","license":"MIT"} |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 6 instances
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Potential vulnerability
Supply chain riskInitial human review suggests the presence of a vulnerability in this package. It is pending further analysis and confirmation.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 7 instances
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
182888564
0.66%8506
0.07%1305104
0.24%4525
0.11%734
0.55%+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated