Initial commit

This commit is contained in:
bilulib
2025-04-13 00:18:57 +02:00
parent cff009bb7c
commit d894249e61
18301 changed files with 2905442 additions and 3845 deletions

View File

@@ -0,0 +1 @@
export declare function addBasePath(path: string, required?: boolean): string;

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "addBasePath", {
enumerable: true,
get: function() {
return addBasePath;
}
});
const _addpathprefix = require("../shared/lib/router/utils/add-path-prefix");
const _normalizetrailingslash = require("./normalize-trailing-slash");
const basePath = process.env.__NEXT_ROUTER_BASEPATH || '';
function addBasePath(path, required) {
return (0, _normalizetrailingslash.normalizePathTrailingSlash)(process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required ? path : (0, _addpathprefix.addPathPrefix)(path, basePath));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=add-base-path.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/add-base-path.ts"],"sourcesContent":["import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function addBasePath(path: string, required?: boolean): string {\n return normalizePathTrailingSlash(\n process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required\n ? path\n : addPathPrefix(path, basePath)\n )\n}\n"],"names":["addBasePath","basePath","process","env","__NEXT_ROUTER_BASEPATH","path","required","normalizePathTrailingSlash","__NEXT_MANUAL_CLIENT_BASE_PATH","addPathPrefix"],"mappings":";;;;+BAKgBA;;;eAAAA;;;+BALc;wCACa;AAE3C,MAAMC,WAAW,AAACC,QAAQC,GAAG,CAACC,sBAAsB,IAAe;AAE5D,SAASJ,YAAYK,IAAY,EAAEC,QAAkB;IAC1D,OAAOC,IAAAA,kDAA0B,EAC/BL,QAAQC,GAAG,CAACK,8BAA8B,IAAI,CAACF,WAC3CD,OACAI,IAAAA,4BAAa,EAACJ,MAAMJ;AAE5B"}

View File

@@ -0,0 +1,2 @@
import type { addLocale as Fn } from '../shared/lib/router/utils/add-locale';
export declare const addLocale: typeof Fn;

View File

@@ -0,0 +1,28 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "addLocale", {
enumerable: true,
get: function() {
return addLocale;
}
});
const _normalizetrailingslash = require("./normalize-trailing-slash");
const addLocale = function(path) {
for(var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++){
args[_key - 1] = arguments[_key];
}
if (process.env.__NEXT_I18N_SUPPORT) {
return (0, _normalizetrailingslash.normalizePathTrailingSlash)(require('../shared/lib/router/utils/add-locale').addLocale(path, ...args));
}
return path;
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=add-locale.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/add-locale.ts"],"sourcesContent":["import type { addLocale as Fn } from '../shared/lib/router/utils/add-locale'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nexport const addLocale: typeof Fn = (path, ...args) => {\n if (process.env.__NEXT_I18N_SUPPORT) {\n return normalizePathTrailingSlash(\n require('../shared/lib/router/utils/add-locale').addLocale(path, ...args)\n )\n }\n return path\n}\n"],"names":["addLocale","path","args","process","env","__NEXT_I18N_SUPPORT","normalizePathTrailingSlash","require"],"mappings":";;;;+BAGaA;;;eAAAA;;;wCAF8B;AAEpC,MAAMA,YAAuB,SAACC;qCAASC;QAAAA;;IAC5C,IAAIC,QAAQC,GAAG,CAACC,mBAAmB,EAAE;QACnC,OAAOC,IAAAA,kDAA0B,EAC/BC,QAAQ,yCAAyCP,SAAS,CAACC,SAASC;IAExE;IACA,OAAOD;AACT"}

View File

@@ -0,0 +1,7 @@
/**
* Before starting the Next.js runtime and requiring any module, we need to make
* sure the following scripts are executed in the correct order:
* - Polyfills
* - next/script with `beforeInteractive` strategy
*/
export declare function appBootstrap(hydrate: () => void): void;

View File

@@ -0,0 +1,78 @@
/**
* Before starting the Next.js runtime and requiring any module, we need to make
* sure the following scripts are executed in the correct order:
* - Polyfills
* - next/script with `beforeInteractive` strategy
*/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "appBootstrap", {
enumerable: true,
get: function() {
return appBootstrap;
}
});
const version = "15.3.0";
window.next = {
version,
appDir: true
};
function loadScriptsInSequence(scripts, hydrate) {
if (!scripts || !scripts.length) {
return hydrate();
}
return scripts.reduce((promise, param)=>{
let [src, props] = param;
return promise.then(()=>{
return new Promise((resolve, reject)=>{
const el = document.createElement('script');
if (props) {
for(const key in props){
if (key !== 'children') {
el.setAttribute(key, props[key]);
}
}
}
if (src) {
el.src = src;
el.onload = ()=>resolve();
el.onerror = reject;
} else if (props) {
el.innerHTML = props.children;
setTimeout(resolve);
}
document.head.appendChild(el);
});
});
}, Promise.resolve()).catch((err)=>{
console.error(err);
// Still try to hydrate even if there's an error.
}).then(()=>{
hydrate();
});
}
function appBootstrap(hydrate) {
loadScriptsInSequence(self.__next_s, ()=>{
// If the static shell is being debugged, skip hydration if the
// `__nextppronly` query is present. This is only enabled when the
// environment variable `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` is
// set to `1`. Otherwise the following is optimized out.
if (process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1') {
const search = new URLSearchParams(window.location.search);
if (search.get('__nextppronly') === 'fallback' || search.get('__nextppronly') === '1') {
console.warn("Skipping hydration due to __nextppronly=" + search.get('__nextppronly'));
return;
}
}
hydrate();
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-bootstrap.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-bootstrap.ts"],"sourcesContent":["/**\n * Before starting the Next.js runtime and requiring any module, we need to make\n * sure the following scripts are executed in the correct order:\n * - Polyfills\n * - next/script with `beforeInteractive` strategy\n */\n\nconst version = process.env.__NEXT_VERSION\n\nwindow.next = {\n version,\n appDir: true,\n}\n\nfunction loadScriptsInSequence(\n scripts: [src: string, props: { [prop: string]: any }][],\n hydrate: () => void\n) {\n if (!scripts || !scripts.length) {\n return hydrate()\n }\n\n return scripts\n .reduce((promise, [src, props]) => {\n return promise.then(() => {\n return new Promise<void>((resolve, reject) => {\n const el = document.createElement('script')\n\n if (props) {\n for (const key in props) {\n if (key !== 'children') {\n el.setAttribute(key, props[key])\n }\n }\n }\n\n if (src) {\n el.src = src\n el.onload = () => resolve()\n el.onerror = reject\n } else if (props) {\n el.innerHTML = props.children\n setTimeout(resolve)\n }\n\n document.head.appendChild(el)\n })\n })\n }, Promise.resolve())\n .catch((err: Error) => {\n console.error(err)\n // Still try to hydrate even if there's an error.\n })\n .then(() => {\n hydrate()\n })\n}\n\nexport function appBootstrap(hydrate: () => void) {\n loadScriptsInSequence((self as any).__next_s, () => {\n // If the static shell is being debugged, skip hydration if the\n // `__nextppronly` query is present. This is only enabled when the\n // environment variable `__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING` is\n // set to `1`. Otherwise the following is optimized out.\n if (process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1') {\n const search = new URLSearchParams(window.location.search)\n if (\n search.get('__nextppronly') === 'fallback' ||\n search.get('__nextppronly') === '1'\n ) {\n console.warn(\n `Skipping hydration due to __nextppronly=${search.get('__nextppronly')}`\n )\n return\n }\n }\n\n hydrate()\n })\n}\n"],"names":["appBootstrap","version","process","env","__NEXT_VERSION","window","next","appDir","loadScriptsInSequence","scripts","hydrate","length","reduce","promise","src","props","then","Promise","resolve","reject","el","document","createElement","key","setAttribute","onload","onerror","innerHTML","children","setTimeout","head","appendChild","catch","err","console","error","self","__next_s","__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING","search","URLSearchParams","location","get","warn"],"mappings":"AAAA;;;;;CAKC;;;;+BAqDeA;;;eAAAA;;;AAnDhB,MAAMC,UAAUC,QAAQC,GAAG,CAACC,cAAc;AAE1CC,OAAOC,IAAI,GAAG;IACZL;IACAM,QAAQ;AACV;AAEA,SAASC,sBACPC,OAAwD,EACxDC,OAAmB;IAEnB,IAAI,CAACD,WAAW,CAACA,QAAQE,MAAM,EAAE;QAC/B,OAAOD;IACT;IAEA,OAAOD,QACJG,MAAM,CAAC,CAACC;YAAS,CAACC,KAAKC,MAAM;QAC5B,OAAOF,QAAQG,IAAI,CAAC;YAClB,OAAO,IAAIC,QAAc,CAACC,SAASC;gBACjC,MAAMC,KAAKC,SAASC,aAAa,CAAC;gBAElC,IAAIP,OAAO;oBACT,IAAK,MAAMQ,OAAOR,MAAO;wBACvB,IAAIQ,QAAQ,YAAY;4BACtBH,GAAGI,YAAY,CAACD,KAAKR,KAAK,CAACQ,IAAI;wBACjC;oBACF;gBACF;gBAEA,IAAIT,KAAK;oBACPM,GAAGN,GAAG,GAAGA;oBACTM,GAAGK,MAAM,GAAG,IAAMP;oBAClBE,GAAGM,OAAO,GAAGP;gBACf,OAAO,IAAIJ,OAAO;oBAChBK,GAAGO,SAAS,GAAGZ,MAAMa,QAAQ;oBAC7BC,WAAWX;gBACb;gBAEAG,SAASS,IAAI,CAACC,WAAW,CAACX;YAC5B;QACF;IACF,GAAGH,QAAQC,OAAO,IACjBc,KAAK,CAAC,CAACC;QACNC,QAAQC,KAAK,CAACF;IACd,iDAAiD;IACnD,GACCjB,IAAI,CAAC;QACJN;IACF;AACJ;AAEO,SAASV,aAAaU,OAAmB;IAC9CF,sBAAsB,AAAC4B,KAAaC,QAAQ,EAAE;QAC5C,+DAA+D;QAC/D,kEAAkE;QAClE,uEAAuE;QACvE,wDAAwD;QACxD,IAAInC,QAAQC,GAAG,CAACmC,0CAA0C,KAAK,KAAK;YAClE,MAAMC,SAAS,IAAIC,gBAAgBnC,OAAOoC,QAAQ,CAACF,MAAM;YACzD,IACEA,OAAOG,GAAG,CAAC,qBAAqB,cAChCH,OAAOG,GAAG,CAAC,qBAAqB,KAChC;gBACAR,QAAQS,IAAI,CACV,AAAC,6CAA0CJ,OAAOG,GAAG,CAAC;gBAExD;YACF;QACF;QAEAhC;IACF;AACF"}

View File

@@ -0,0 +1,2 @@
export declare function setAppBuildId(buildId: string): void;
export declare function getAppBuildId(): string;

View File

@@ -0,0 +1,49 @@
// This gets assigned as a side-effect during app initialization. Because it
// represents the build used to create the JS bundle, it should never change
// after being set, so we store it in a global variable.
//
// When performing RSC requests, if the incoming data has a different build ID,
// we perform an MPA navigation/refresh to load the updated build and ensure
// that the client and server in sync.
// Starts as an empty string. In practice, because setAppBuildId is called
// during initialization before hydration starts, this will always get
// reassigned to the actual build ID before it's ever needed by a navigation.
// If for some reasons it didn't, due to a bug or race condition, then on
// navigation the build comparision would fail and trigger an MPA navigation.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getAppBuildId: null,
setAppBuildId: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getAppBuildId: function() {
return getAppBuildId;
},
setAppBuildId: function() {
return setAppBuildId;
}
});
let globalBuildId = '';
function setAppBuildId(buildId) {
globalBuildId = buildId;
}
function getAppBuildId() {
return globalBuildId;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-build-id.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-build-id.ts"],"sourcesContent":["// This gets assigned as a side-effect during app initialization. Because it\n// represents the build used to create the JS bundle, it should never change\n// after being set, so we store it in a global variable.\n//\n// When performing RSC requests, if the incoming data has a different build ID,\n// we perform an MPA navigation/refresh to load the updated build and ensure\n// that the client and server in sync.\n\n// Starts as an empty string. In practice, because setAppBuildId is called\n// during initialization before hydration starts, this will always get\n// reassigned to the actual build ID before it's ever needed by a navigation.\n// If for some reasons it didn't, due to a bug or race condition, then on\n// navigation the build comparision would fail and trigger an MPA navigation.\nlet globalBuildId: string = ''\n\nexport function setAppBuildId(buildId: string) {\n globalBuildId = buildId\n}\n\nexport function getAppBuildId(): string {\n return globalBuildId\n}\n"],"names":["getAppBuildId","setAppBuildId","globalBuildId","buildId"],"mappings":"AAAA,4EAA4E;AAC5E,4EAA4E;AAC5E,wDAAwD;AACxD,EAAE;AACF,+EAA+E;AAC/E,4EAA4E;AAC5E,sCAAsC;AAEtC,0EAA0E;AAC1E,sEAAsE;AACtE,6EAA6E;AAC7E,yEAAyE;AACzE,6EAA6E;;;;;;;;;;;;;;;;IAO7DA,aAAa;eAAbA;;IAJAC,aAAa;eAAbA;;;AAFhB,IAAIC,gBAAwB;AAErB,SAASD,cAAcE,OAAe;IAC3CD,gBAAgBC;AAClB;AAEO,SAASH;IACd,OAAOE;AACT"}

View File

@@ -0,0 +1 @@
export declare function callServer(actionId: string, actionArgs: any[]): Promise<unknown>;

View File

@@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "callServer", {
enumerable: true,
get: function() {
return callServer;
}
});
const _react = require("react");
const _routerreducertypes = require("./components/router-reducer/router-reducer-types");
const _useactionqueue = require("./components/use-action-queue");
async function callServer(actionId, actionArgs) {
return new Promise((resolve, reject)=>{
(0, _react.startTransition)(()=>{
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_SERVER_ACTION,
actionId,
actionArgs,
resolve,
reject
});
});
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-call-server.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-call-server.ts"],"sourcesContent":["import { startTransition } from 'react'\nimport { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'\nimport { dispatchAppRouterAction } from './components/use-action-queue'\n\nexport async function callServer(actionId: string, actionArgs: any[]) {\n return new Promise((resolve, reject) => {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_SERVER_ACTION,\n actionId,\n actionArgs,\n resolve,\n reject,\n })\n })\n })\n}\n"],"names":["callServer","actionId","actionArgs","Promise","resolve","reject","startTransition","dispatchAppRouterAction","type","ACTION_SERVER_ACTION"],"mappings":";;;;+BAIsBA;;;eAAAA;;;uBAJU;oCACK;gCACG;AAEjC,eAAeA,WAAWC,QAAgB,EAAEC,UAAiB;IAClE,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3BC,IAAAA,sBAAe,EAAC;YACdC,IAAAA,uCAAuB,EAAC;gBACtBC,MAAMC,wCAAoB;gBAC1BR;gBACAC;gBACAE;gBACAC;YACF;QACF;IACF;AACF"}

View File

@@ -0,0 +1,3 @@
import { type FormProps } from '../form-shared';
export type { FormProps };
export default function Form({ replace, scroll, prefetch: prefetchProp, ref: externalRef, ...props }: FormProps): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,158 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return Form;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _addbasepath = require("../add-base-path");
const _usemergedref = require("../use-merged-ref");
const _approutercontextsharedruntime = require("../../shared/lib/app-router-context.shared-runtime");
const _routerreducertypes = require("../components/router-reducer/router-reducer-types");
const _formshared = require("../form-shared");
const _links = require("../components/links");
function Form(param) {
let { replace, scroll, prefetch: prefetchProp, ref: externalRef, ...props } = param;
const router = (0, _react.useContext)(_approutercontextsharedruntime.AppRouterContext);
const actionProp = props.action;
const isNavigatingForm = typeof actionProp === 'string';
// Validate `action`
if (process.env.NODE_ENV === 'development') {
if (isNavigatingForm) {
(0, _formshared.checkFormActionUrl)(actionProp, 'action');
}
}
// Validate `prefetch`
if (process.env.NODE_ENV === 'development') {
if (!(prefetchProp === undefined || prefetchProp === false || prefetchProp === null)) {
console.error('The `prefetch` prop of <Form> must be `false` or `null`');
}
if (prefetchProp !== undefined && !isNavigatingForm) {
console.error('Passing `prefetch` to a <Form> whose `action` is a function has no effect.');
}
}
const prefetch = prefetchProp === false || prefetchProp === null ? prefetchProp : null;
// Validate `scroll` and `replace`
if (process.env.NODE_ENV === 'development') {
if (!isNavigatingForm && (replace !== undefined || scroll !== undefined)) {
console.error('Passing `replace` or `scroll` to a <Form> whose `action` is a function has no effect.\n' + 'See the relevant docs to learn how to control this behavior for navigations triggered from actions:\n' + ' `redirect()` - https://nextjs.org/docs/app/api-reference/functions/redirect#parameters\n' + ' `router.replace()` - https://nextjs.org/docs/app/api-reference/functions/use-router#userouter\n');
}
}
// Clean up any unsupported form props (and warn if present)
for (const key of _formshared.DISALLOWED_FORM_PROPS){
if (key in props) {
if (process.env.NODE_ENV === 'development') {
console.error("<Form> does not support changing `" + key + "`. " + (isNavigatingForm ? "If you'd like to use it to perform a mutation, consider making `action` a function instead.\n" + "Learn more: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations" : ''));
}
delete props[key];
}
}
const isPrefetchEnabled = // if we don't have an action path, we can't prefetch anything.
!!router && isNavigatingForm && prefetch === null;
const observeFormVisibilityOnMount = (0, _react.useCallback)((element)=>{
if (isPrefetchEnabled && router !== null) {
(0, _links.mountFormInstance)(element, actionProp, router, _routerreducertypes.PrefetchKind.AUTO);
}
return ()=>{
(0, _links.unmountPrefetchableInstance)(element);
};
}, [
isPrefetchEnabled,
actionProp,
router
]);
const mergedRef = (0, _usemergedref.useMergedRef)(observeFormVisibilityOnMount, externalRef != null ? externalRef : null);
if (!isNavigatingForm) {
return /*#__PURE__*/ (0, _jsxruntime.jsx)("form", {
...props,
ref: mergedRef
});
}
const actionHref = (0, _addbasepath.addBasePath)(actionProp);
return /*#__PURE__*/ (0, _jsxruntime.jsx)("form", {
...props,
ref: mergedRef,
action: actionHref,
onSubmit: (event)=>onFormSubmit(event, {
router,
actionHref,
replace,
scroll,
onSubmit: props.onSubmit
})
});
}
function onFormSubmit(event, param) {
let { actionHref, onSubmit, replace, scroll, router } = param;
if (typeof onSubmit === 'function') {
onSubmit(event);
// if the user called event.preventDefault(), do nothing.
// (this matches what Link does for `onClick`)
if (event.defaultPrevented) {
return;
}
}
if (!router) {
// Form was somehow used outside of the router (but not in pages, the implementation is forked!).
// We can't perform a soft navigation, so let the native submit handling do its thing.
return;
}
const formElement = event.currentTarget;
const submitter = event.nativeEvent.submitter;
let action = actionHref;
if (submitter) {
if (process.env.NODE_ENV === 'development') {
// the way server actions are encoded (e.g. `formMethod="post")
// causes some unnecessary dev-mode warnings from `hasUnsupportedSubmitterAttributes`.
// we'd bail out anyway, but we just do it silently.
if (hasReactServerActionAttributes(submitter)) {
return;
}
}
if ((0, _formshared.hasUnsupportedSubmitterAttributes)(submitter)) {
return;
}
// client actions have `formAction="javascript:..."`. We obviously can't prefetch/navigate to that.
if ((0, _formshared.hasReactClientActionAttributes)(submitter)) {
return;
}
// If the submitter specified an alternate formAction,
// use that URL instead -- this is what a native form would do.
// NOTE: `submitter.formAction` is unreliable, because it will give us `location.href` if it *wasn't* set
// NOTE: this should not have `basePath` added, because we can't add it before hydration
const submitterFormAction = submitter.getAttribute('formAction');
if (submitterFormAction !== null) {
if (process.env.NODE_ENV === 'development') {
(0, _formshared.checkFormActionUrl)(submitterFormAction, 'formAction');
}
action = submitterFormAction;
}
}
const targetUrl = (0, _formshared.createFormSubmitDestinationUrl)(action, formElement);
// Finally, no more reasons for bailing out.
event.preventDefault();
const method = replace ? 'replace' : 'push';
const targetHref = targetUrl.href;
router[method](targetHref, {
scroll
});
}
function hasReactServerActionAttributes(submitter) {
// https://github.com/facebook/react/blob/942eb80381b96f8410eab1bef1c539bed1ab0eb1/packages/react-client/src/ReactFlightReplyClient.js#L931-L934
const name = submitter.getAttribute('name');
return name && (name.startsWith('$ACTION_ID_') || name.startsWith('$ACTION_REF_'));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=form.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,193 @@
import React from 'react';
import type { UrlObject } from 'url';
type Url = string | UrlObject;
type OnNavigateEventHandler = (event: {
preventDefault: () => void;
}) => void;
type InternalLinkProps = {
/**
* **Required**. The path or URL to navigate to. It can also be an object (similar to `URL`).
*
* @example
* ```tsx
* // Navigate to /dashboard:
* <Link href="/dashboard">Dashboard</Link>
*
* // Navigate to /about?name=test:
* <Link href={{ pathname: '/about', query: { name: 'test' } }}>
* About
* </Link>
* ```
*
* @remarks
* - For external URLs, use a fully qualified URL such as `https://...`.
* - In the App Router, dynamic routes must not include bracketed segments in `href`.
*/
href: Url;
/**
* @deprecated v10.0.0: `href` props pointing to a dynamic route are
* automatically resolved and no longer require the `as` prop.
*/
as?: Url;
/**
* Replace the current `history` state instead of adding a new URL into the stack.
*
* @defaultValue `false`
*
* @example
* ```tsx
* <Link href="/about" replace>
* About (replaces the history state)
* </Link>
* ```
*/
replace?: boolean;
/**
* Whether to override the default scroll behavior. If `true`, Next.js attempts to maintain
* the scroll position if the newly navigated page is still visible. If not, it scrolls to the top.
*
* If `false`, Next.js will not modify the scroll behavior at all.
*
* @defaultValue `true`
*
* @example
* ```tsx
* <Link href="/dashboard" scroll={false}>
* No auto scroll
* </Link>
* ```
*/
scroll?: boolean;
/**
* Update the path of the current page without rerunning data fetching methods
* like `getStaticProps`, `getServerSideProps`, or `getInitialProps`.
*
* @remarks
* `shallow` only applies to the Pages Router. For the App Router, see the
* [following documentation](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#using-the-native-history-api).
*
* @defaultValue `false`
*
* @example
* ```tsx
* <Link href="/blog" shallow>
* Shallow navigation
* </Link>
* ```
*/
shallow?: boolean;
/**
* Forces `Link` to pass its `href` to the child component. Useful if the child is a custom
* component that wraps an `<a>` tag, or if you're using certain styling libraries.
*
* @defaultValue `false`
*
* @example
* ```tsx
* <Link href="/dashboard" passHref>
* <MyStyledAnchor>Dashboard</MyStyledAnchor>
* </Link>
* ```
*/
passHref?: boolean;
/**
* Prefetch the page in the background.
* Any `<Link />` that is in the viewport (initially or through scroll) will be prefetched.
* Prefetch can be disabled by passing `prefetch={false}`.
*
* @remarks
* Prefetching is only enabled in production.
*
* - In the **App Router**:
* - `null` (default): Prefetch behavior depends on static vs dynamic routes:
* - Static routes: fully prefetched
* - Dynamic routes: partial prefetch to the nearest segment with a `loading.js`
* - `true`: Always prefetch the full route and data.
* - `false`: Disable prefetching on both viewport and hover.
* - In the **Pages Router**:
* - `true` (default): Prefetches the route and data in the background on viewport or hover.
* - `false`: Prefetch only on hover, not on viewport.
*
* @defaultValue `true` (Pages Router) or `null` (App Router)
*
* @example
* ```tsx
* <Link href="/dashboard" prefetch={false}>
* Dashboard
* </Link>
* ```
*/
prefetch?: boolean | null;
/**
* (unstable) Switch to a dynamic prefetch on hover. Effectively the same as
* updating the prefetch prop to `true` in a mouse event.
*/
unstable_dynamicOnHover?: boolean;
/**
* The active locale is automatically prepended in the Pages Router. `locale` allows for providing
* a different locale, or can be set to `false` to opt out of automatic locale behavior.
*
* @remarks
* Note: locale only applies in the Pages Router and is ignored in the App Router.
*
* @example
* ```tsx
* // Use the 'fr' locale:
* <Link href="/about" locale="fr">
* About (French)
* </Link>
*
* // Disable locale prefix:
* <Link href="/about" locale={false}>
* About (no locale prefix)
* </Link>
* ```
*/
locale?: string | false;
/**
* Enable legacy link behavior, requiring an `<a>` tag to wrap the child content
* if the child is a string or number.
*
* @deprecated This will be removed in v16
* @defaultValue `false`
* @see https://github.com/vercel/next.js/commit/489e65ed98544e69b0afd7e0cfc3f9f6c2b803b7
*/
legacyBehavior?: boolean;
/**
* Optional event handler for when the mouse pointer is moved onto the `<Link>`.
*/
onMouseEnter?: React.MouseEventHandler<HTMLAnchorElement>;
/**
* Optional event handler for when the `<Link>` is touched.
*/
onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>;
/**
* Optional event handler for when the `<Link>` is clicked.
*/
onClick?: React.MouseEventHandler<HTMLAnchorElement>;
/**
* Optional event handler for when the `<Link>` is navigated.
*/
onNavigate?: OnNavigateEventHandler;
};
export type LinkProps<RouteInferType = any> = InternalLinkProps;
/**
* A React component that extends the HTML `<a>` element to provide
* [prefetching](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching)
* and client-side navigation. This is the primary way to navigate between routes in Next.js.
*
* @remarks
* - Prefetching is only enabled in production.
*
* @see https://nextjs.org/docs/app/api-reference/components/link
*/
export default function LinkComponent(props: LinkProps & {
children: React.ReactNode;
ref: React.Ref<HTMLAnchorElement>;
}): import("react/jsx-runtime").JSX.Element;
export declare const useLinkStatus: () => {
pending: boolean;
} | {
pending: boolean;
};
export {};

View File

@@ -0,0 +1,384 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
default: null,
useLinkStatus: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
/**
* A React component that extends the HTML `<a>` element to provide
* [prefetching](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching)
* and client-side navigation. This is the primary way to navigate between routes in Next.js.
*
* @remarks
* - Prefetching is only enabled in production.
*
* @see https://nextjs.org/docs/app/api-reference/components/link
*/ default: function() {
return LinkComponent;
},
useLinkStatus: function() {
return useLinkStatus;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _formaturl = require("../../shared/lib/router/utils/format-url");
const _approutercontextsharedruntime = require("../../shared/lib/app-router-context.shared-runtime");
const _routerreducertypes = require("../components/router-reducer/router-reducer-types");
const _usemergedref = require("../use-merged-ref");
const _utils = require("../../shared/lib/utils");
const _addbasepath = require("../add-base-path");
const _warnonce = require("../../shared/lib/utils/warn-once");
const _links = require("../components/links");
const _islocalurl = require("../../shared/lib/router/utils/is-local-url");
const _approuterinstance = require("../components/app-router-instance");
const _erroronce = require("../../shared/lib/utils/error-once");
function isModifiedEvent(event) {
const eventTarget = event.currentTarget;
const target = eventTarget.getAttribute('target');
return target && target !== '_self' || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || // triggers resource download
event.nativeEvent && event.nativeEvent.which === 2;
}
function linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate) {
const { nodeName } = e.currentTarget;
// anchors inside an svg have a lowercase nodeName
const isAnchorNodeName = nodeName.toUpperCase() === 'A';
if (isAnchorNodeName && isModifiedEvent(e) || e.currentTarget.hasAttribute('download')) {
// ignore click for browsers default behavior
return;
}
if (!(0, _islocalurl.isLocalURL)(href)) {
if (replace) {
// browser default behavior does not replace the history state
// so we need to do it manually
e.preventDefault();
location.replace(href);
}
// ignore click for browsers default behavior
return;
}
e.preventDefault();
const navigate = ()=>{
if (onNavigate) {
let isDefaultPrevented = false;
onNavigate({
preventDefault: ()=>{
isDefaultPrevented = true;
}
});
if (isDefaultPrevented) {
return;
}
}
(0, _approuterinstance.dispatchNavigateAction)(as || href, replace ? 'replace' : 'push', scroll != null ? scroll : true, linkInstanceRef.current);
};
_react.default.startTransition(navigate);
}
function formatStringOrUrl(urlObjOrString) {
if (typeof urlObjOrString === 'string') {
return urlObjOrString;
}
return (0, _formaturl.formatUrl)(urlObjOrString);
}
function LinkComponent(props) {
const [linkStatus, setOptimisticLinkStatus] = (0, _react.useOptimistic)(_links.IDLE_LINK_STATUS);
let children;
const linkInstanceRef = (0, _react.useRef)(null);
const { href: hrefProp, as: asProp, children: childrenProp, prefetch: prefetchProp = null, passHref, replace, shallow, scroll, onClick, onMouseEnter: onMouseEnterProp, onTouchStart: onTouchStartProp, legacyBehavior = false, onNavigate, ref: forwardedRef, unstable_dynamicOnHover, ...restProps } = props;
children = childrenProp;
if (legacyBehavior && (typeof children === 'string' || typeof children === 'number')) {
children = /*#__PURE__*/ (0, _jsxruntime.jsx)("a", {
children: children
});
}
const router = _react.default.useContext(_approutercontextsharedruntime.AppRouterContext);
const prefetchEnabled = prefetchProp !== false;
/**
* The possible states for prefetch are:
* - null: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport
* - true: we will prefetch if the link is visible and prefetch the full page, not just partially
* - false: we will not prefetch if in the viewport at all
* - 'unstable_dynamicOnHover': this starts in "auto" mode, but switches to "full" when the link is hovered
*/ const appPrefetchKind = prefetchProp === null ? _routerreducertypes.PrefetchKind.AUTO : _routerreducertypes.PrefetchKind.FULL;
if (process.env.NODE_ENV !== 'production') {
function createPropError(args) {
return Object.defineProperty(new Error("Failed prop type: The prop `" + args.key + "` expects a " + args.expected + " in `<Link>`, but got `" + args.actual + "` instead." + (typeof window !== 'undefined' ? "\nOpen your browser's console to view the Component stack trace." : '')), "__NEXT_ERROR_CODE", {
value: "E319",
enumerable: false,
configurable: true
});
}
// TypeScript trick for type-guarding:
const requiredPropsGuard = {
href: true
};
const requiredProps = Object.keys(requiredPropsGuard);
requiredProps.forEach((key)=>{
if (key === 'href') {
if (props[key] == null || typeof props[key] !== 'string' && typeof props[key] !== 'object') {
throw createPropError({
key,
expected: '`string` or `object`',
actual: props[key] === null ? 'null' : typeof props[key]
});
}
} else {
// TypeScript trick for type-guarding:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _ = key;
}
});
// TypeScript trick for type-guarding:
const optionalPropsGuard = {
as: true,
replace: true,
scroll: true,
shallow: true,
passHref: true,
prefetch: true,
unstable_dynamicOnHover: true,
onClick: true,
onMouseEnter: true,
onTouchStart: true,
legacyBehavior: true,
onNavigate: true
};
const optionalProps = Object.keys(optionalPropsGuard);
optionalProps.forEach((key)=>{
const valType = typeof props[key];
if (key === 'as') {
if (props[key] && valType !== 'string' && valType !== 'object') {
throw createPropError({
key,
expected: '`string` or `object`',
actual: valType
});
}
} else if (key === 'onClick' || key === 'onMouseEnter' || key === 'onTouchStart' || key === 'onNavigate') {
if (props[key] && valType !== 'function') {
throw createPropError({
key,
expected: '`function`',
actual: valType
});
}
} else if (key === 'replace' || key === 'scroll' || key === 'shallow' || key === 'passHref' || key === 'prefetch' || key === 'legacyBehavior' || key === 'unstable_dynamicOnHover') {
if (props[key] != null && valType !== 'boolean') {
throw createPropError({
key,
expected: '`boolean`',
actual: valType
});
}
} else {
// TypeScript trick for type-guarding:
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _ = key;
}
});
}
if (process.env.NODE_ENV !== 'production') {
if (props.locale) {
(0, _warnonce.warnOnce)('The `locale` prop is not supported in `next/link` while using the `app` router. Read more about app router internalization: https://nextjs.org/docs/app/building-your-application/routing/internationalization');
}
if (!asProp) {
let href;
if (typeof hrefProp === 'string') {
href = hrefProp;
} else if (typeof hrefProp === 'object' && typeof hrefProp.pathname === 'string') {
href = hrefProp.pathname;
}
if (href) {
const hasDynamicSegment = href.split('/').some((segment)=>segment.startsWith('[') && segment.endsWith(']'));
if (hasDynamicSegment) {
throw Object.defineProperty(new Error("Dynamic href `" + href + "` found in <Link> while using the `/app` router, this is not supported. Read more: https://nextjs.org/docs/messages/app-dir-dynamic-href"), "__NEXT_ERROR_CODE", {
value: "E267",
enumerable: false,
configurable: true
});
}
}
}
}
const { href, as } = _react.default.useMemo(()=>{
const resolvedHref = formatStringOrUrl(hrefProp);
return {
href: resolvedHref,
as: asProp ? formatStringOrUrl(asProp) : resolvedHref
};
}, [
hrefProp,
asProp
]);
// This will return the first child, if multiple are provided it will throw an error
let child;
if (legacyBehavior) {
if (process.env.NODE_ENV === 'development') {
if (onClick) {
console.warn('"onClick" was passed to <Link> with `href` of `' + hrefProp + '` but "legacyBehavior" was set. The legacy behavior requires onClick be set on the child of next/link');
}
if (onMouseEnterProp) {
console.warn('"onMouseEnter" was passed to <Link> with `href` of `' + hrefProp + '` but "legacyBehavior" was set. The legacy behavior requires onMouseEnter be set on the child of next/link');
}
try {
child = _react.default.Children.only(children);
} catch (err) {
if (!children) {
throw Object.defineProperty(new Error("No children were passed to <Link> with `href` of `" + hrefProp + "` but one child is required https://nextjs.org/docs/messages/link-no-children"), "__NEXT_ERROR_CODE", {
value: "E320",
enumerable: false,
configurable: true
});
}
throw Object.defineProperty(new Error("Multiple children were passed to <Link> with `href` of `" + hrefProp + "` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children" + (typeof window !== 'undefined' ? " \nOpen your browser's console to view the Component stack trace." : '')), "__NEXT_ERROR_CODE", {
value: "E266",
enumerable: false,
configurable: true
});
}
} else {
child = _react.default.Children.only(children);
}
} else {
if (process.env.NODE_ENV === 'development') {
if ((children == null ? void 0 : children.type) === 'a') {
throw Object.defineProperty(new Error('Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'), "__NEXT_ERROR_CODE", {
value: "E209",
enumerable: false,
configurable: true
});
}
}
}
const childRef = legacyBehavior ? child && typeof child === 'object' && child.ref : forwardedRef;
// Use a callback ref to attach an IntersectionObserver to the anchor tag on
// mount. In the future we will also use this to keep track of all the
// currently mounted <Link> instances, e.g. so we can re-prefetch them after
// a revalidation or refresh.
const observeLinkVisibilityOnMount = _react.default.useCallback((element)=>{
if (router !== null) {
linkInstanceRef.current = (0, _links.mountLinkInstance)(element, href, router, appPrefetchKind, prefetchEnabled, setOptimisticLinkStatus);
}
return ()=>{
if (linkInstanceRef.current) {
(0, _links.unmountLinkForCurrentNavigation)(linkInstanceRef.current);
linkInstanceRef.current = null;
}
(0, _links.unmountPrefetchableInstance)(element);
};
}, [
prefetchEnabled,
href,
router,
appPrefetchKind,
setOptimisticLinkStatus
]);
const mergedRef = (0, _usemergedref.useMergedRef)(observeLinkVisibilityOnMount, childRef);
const childProps = {
ref: mergedRef,
onClick (e) {
if (process.env.NODE_ENV !== 'production') {
if (!e) {
throw Object.defineProperty(new Error('Component rendered inside next/link has to pass click event to "onClick" prop.'), "__NEXT_ERROR_CODE", {
value: "E312",
enumerable: false,
configurable: true
});
}
}
if (!legacyBehavior && typeof onClick === 'function') {
onClick(e);
}
if (legacyBehavior && child.props && typeof child.props.onClick === 'function') {
child.props.onClick(e);
}
if (!router) {
return;
}
if (e.defaultPrevented) {
return;
}
linkClicked(e, href, as, linkInstanceRef, replace, scroll, onNavigate);
},
onMouseEnter (e) {
if (!legacyBehavior && typeof onMouseEnterProp === 'function') {
onMouseEnterProp(e);
}
if (legacyBehavior && child.props && typeof child.props.onMouseEnter === 'function') {
child.props.onMouseEnter(e);
}
if (!router) {
return;
}
if (!prefetchEnabled || process.env.NODE_ENV === 'development') {
return;
}
const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true;
(0, _links.onNavigationIntent)(e.currentTarget, upgradeToDynamicPrefetch);
},
onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START ? undefined : function onTouchStart(e) {
if (!legacyBehavior && typeof onTouchStartProp === 'function') {
onTouchStartProp(e);
}
if (legacyBehavior && child.props && typeof child.props.onTouchStart === 'function') {
child.props.onTouchStart(e);
}
if (!router) {
return;
}
if (!prefetchEnabled) {
return;
}
const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true;
(0, _links.onNavigationIntent)(e.currentTarget, upgradeToDynamicPrefetch);
}
};
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
// defined, we specify the current 'href', so that repetition is not needed by the user.
// If the url is absolute, we can bypass the logic to prepend the basePath.
if ((0, _utils.isAbsoluteUrl)(as)) {
childProps.href = as;
} else if (!legacyBehavior || passHref || child.type === 'a' && !('href' in child.props)) {
childProps.href = (0, _addbasepath.addBasePath)(as);
}
let link;
if (legacyBehavior) {
if (process.env.NODE_ENV === 'development') {
(0, _erroronce.errorOnce)('`legacyBehavior` is deprecated and will be removed in a future ' + 'release. A codemod is available to upgrade your components:\n\n' + 'npx @next/codemod@latest new-link .\n\n' + 'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components');
}
link = /*#__PURE__*/ _react.default.cloneElement(child, childProps);
} else {
link = /*#__PURE__*/ (0, _jsxruntime.jsx)("a", {
...restProps,
...childProps,
children: children
});
}
return /*#__PURE__*/ (0, _jsxruntime.jsx)(LinkStatusContext.Provider, {
value: linkStatus,
children: link
});
}
const LinkStatusContext = /*#__PURE__*/ (0, _react.createContext)(_links.IDLE_LINK_STATUS);
const useLinkStatus = ()=>{
return (0, _react.useContext)(LinkStatusContext);
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=link.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare const findSourceMapURL: ((filename: string) => string | null) | undefined;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "findSourceMapURL", {
enumerable: true,
get: function() {
return findSourceMapURL;
}
});
const basePath = process.env.__NEXT_ROUTER_BASEPATH || '';
const pathname = "" + basePath + "/__nextjs_source-map";
const findSourceMapURL = process.env.NODE_ENV === 'development' ? function findSourceMapURL(filename) {
if (filename === '') {
return null;
}
if (filename.startsWith(document.location.origin) && filename.includes('/_next/static')) {
// This is a request for a client chunk. This can only happen when
// using Turbopack. In this case, since we control how those source
// maps are generated, we can safely assume that the sourceMappingURL
// is relative to the filename, with an added `.map` extension. The
// browser can just request this file, and it gets served through the
// normal dev server, without the need to route this through
// the `/__nextjs_source-map` dev middleware.
return "" + filename + ".map";
}
const url = new URL(pathname, document.location.origin);
url.searchParams.set('filename', filename);
return url.href;
} : undefined;
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-find-source-map-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-find-source-map-url.ts"],"sourcesContent":["const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''\nconst pathname = `${basePath}/__nextjs_source-map`\n\nexport const findSourceMapURL =\n process.env.NODE_ENV === 'development'\n ? function findSourceMapURL(filename: string): string | null {\n if (filename === '') {\n return null\n }\n\n if (\n filename.startsWith(document.location.origin) &&\n filename.includes('/_next/static')\n ) {\n // This is a request for a client chunk. This can only happen when\n // using Turbopack. In this case, since we control how those source\n // maps are generated, we can safely assume that the sourceMappingURL\n // is relative to the filename, with an added `.map` extension. The\n // browser can just request this file, and it gets served through the\n // normal dev server, without the need to route this through\n // the `/__nextjs_source-map` dev middleware.\n return `${filename}.map`\n }\n\n const url = new URL(pathname, document.location.origin)\n url.searchParams.set('filename', filename)\n\n return url.href\n }\n : undefined\n"],"names":["findSourceMapURL","basePath","process","env","__NEXT_ROUTER_BASEPATH","pathname","NODE_ENV","filename","startsWith","document","location","origin","includes","url","URL","searchParams","set","href","undefined"],"mappings":";;;;+BAGaA;;;eAAAA;;;AAHb,MAAMC,WAAWC,QAAQC,GAAG,CAACC,sBAAsB,IAAI;AACvD,MAAMC,WAAW,AAAC,KAAEJ,WAAS;AAEtB,MAAMD,mBACXE,QAAQC,GAAG,CAACG,QAAQ,KAAK,gBACrB,SAASN,iBAAiBO,QAAgB;IACxC,IAAIA,aAAa,IAAI;QACnB,OAAO;IACT;IAEA,IACEA,SAASC,UAAU,CAACC,SAASC,QAAQ,CAACC,MAAM,KAC5CJ,SAASK,QAAQ,CAAC,kBAClB;QACA,kEAAkE;QAClE,mEAAmE;QACnE,qEAAqE;QACrE,mEAAmE;QACnE,qEAAqE;QACrE,4DAA4D;QAC5D,6CAA6C;QAC7C,OAAO,AAAC,KAAEL,WAAS;IACrB;IAEA,MAAMM,MAAM,IAAIC,IAAIT,UAAUI,SAASC,QAAQ,CAACC,MAAM;IACtDE,IAAIE,YAAY,CAACC,GAAG,CAAC,YAAYT;IAEjC,OAAOM,IAAII,IAAI;AACjB,IACAC"}

View File

@@ -0,0 +1,17 @@
import '../build/polyfills/polyfill-module';
import './components/globals/patch-console';
import './components/globals/handle-global-errors';
type FlightSegment = [isBootStrap: 0] | [isNotBootstrap: 1, responsePartial: string] | [isFormState: 2, formState: any] | [isBinary: 3, responseBase64Partial: string];
type NextFlight = Omit<Array<FlightSegment>, 'push'> & {
push: (seg: FlightSegment) => void;
};
declare global {
interface Window {
__next_f: NextFlight;
}
}
export type ClientInstrumentationHooks = {
onRouterTransitionStart?: (url: string, navigationType: 'push' | 'replace' | 'traverse') => void;
};
export declare function hydrate(instrumentationHooks: ClientInstrumentationHooks | null): void;
export {};

View File

@@ -0,0 +1,237 @@
// imports polyfill from `@next/polyfill-module` after build.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "hydrate", {
enumerable: true,
get: function() {
return hydrate;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
require("../build/polyfills/polyfill-module");
require("./components/globals/patch-console");
require("./components/globals/handle-global-errors");
const _client = /*#__PURE__*/ _interop_require_default._(require("react-dom/client"));
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _client1 = require("react-server-dom-webpack/client");
const _headmanagercontextsharedruntime = require("../shared/lib/head-manager-context.shared-runtime");
const _onrecoverableerror = require("./react-client-callbacks/on-recoverable-error");
const _errorboundarycallbacks = require("./react-client-callbacks/error-boundary-callbacks");
const _appcallserver = require("./app-call-server");
const _appfindsourcemapurl = require("./app-find-source-map-url");
const _approuterinstance = require("./components/app-router-instance");
const _approuter = /*#__PURE__*/ _interop_require_default._(require("./components/app-router"));
const _createinitialrouterstate = require("./components/router-reducer/create-initial-router-state");
const _approutercontextsharedruntime = require("../shared/lib/app-router-context.shared-runtime");
const _appbuildid = require("./app-build-id");
/// <reference types="react-dom/experimental" />
const appElement = document;
const encoder = new TextEncoder();
let initialServerDataBuffer = undefined;
let initialServerDataWriter = undefined;
let initialServerDataLoaded = false;
let initialServerDataFlushed = false;
let initialFormStateData = null;
function nextServerDataCallback(seg) {
if (seg[0] === 0) {
initialServerDataBuffer = [];
} else if (seg[0] === 1) {
if (!initialServerDataBuffer) throw Object.defineProperty(new Error('Unexpected server data: missing bootstrap script.'), "__NEXT_ERROR_CODE", {
value: "E18",
enumerable: false,
configurable: true
});
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(encoder.encode(seg[1]));
} else {
initialServerDataBuffer.push(seg[1]);
}
} else if (seg[0] === 2) {
initialFormStateData = seg[1];
} else if (seg[0] === 3) {
if (!initialServerDataBuffer) throw Object.defineProperty(new Error('Unexpected server data: missing bootstrap script.'), "__NEXT_ERROR_CODE", {
value: "E18",
enumerable: false,
configurable: true
});
// Decode the base64 string back to binary data.
const binaryString = atob(seg[1]);
const decodedChunk = new Uint8Array(binaryString.length);
for(var i = 0; i < binaryString.length; i++){
decodedChunk[i] = binaryString.charCodeAt(i);
}
if (initialServerDataWriter) {
initialServerDataWriter.enqueue(decodedChunk);
} else {
initialServerDataBuffer.push(decodedChunk);
}
}
}
function isStreamErrorOrUnfinished(ctr) {
// If `desiredSize` is null, it means the stream is closed or errored. If it is lower than 0, the stream is still unfinished.
return ctr.desiredSize === null || ctr.desiredSize < 0;
}
// There might be race conditions between `nextServerDataRegisterWriter` and
// `DOMContentLoaded`. The former will be called when React starts to hydrate
// the root, the latter will be called when the DOM is fully loaded.
// For streaming, the former is called first due to partial hydration.
// For non-streaming, the latter can be called first.
// Hence, we use two variables `initialServerDataLoaded` and
// `initialServerDataFlushed` to make sure the writer will be closed and
// `initialServerDataBuffer` will be cleared in the right time.
function nextServerDataRegisterWriter(ctr) {
if (initialServerDataBuffer) {
initialServerDataBuffer.forEach((val)=>{
ctr.enqueue(typeof val === 'string' ? encoder.encode(val) : val);
});
if (initialServerDataLoaded && !initialServerDataFlushed) {
if (isStreamErrorOrUnfinished(ctr)) {
ctr.error(Object.defineProperty(new Error('The connection to the page was unexpectedly closed, possibly due to the stop button being clicked, loss of Wi-Fi, or an unstable internet connection.'), "__NEXT_ERROR_CODE", {
value: "E117",
enumerable: false,
configurable: true
}));
} else {
ctr.close();
}
initialServerDataFlushed = true;
initialServerDataBuffer = undefined;
}
}
initialServerDataWriter = ctr;
}
// When `DOMContentLoaded`, we can close all pending writers to finish hydration.
const DOMContentLoaded = function() {
if (initialServerDataWriter && !initialServerDataFlushed) {
initialServerDataWriter.close();
initialServerDataFlushed = true;
initialServerDataBuffer = undefined;
}
initialServerDataLoaded = true;
};
// It's possible that the DOM is already loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', DOMContentLoaded, false);
} else {
// Delayed in marco task to ensure it's executed later than hydration
setTimeout(DOMContentLoaded);
}
const nextServerDataLoadingGlobal = self.__next_f = self.__next_f || [];
nextServerDataLoadingGlobal.forEach(nextServerDataCallback);
nextServerDataLoadingGlobal.push = nextServerDataCallback;
const readable = new ReadableStream({
start (controller) {
nextServerDataRegisterWriter(controller);
}
});
const initialServerResponse = (0, _client1.createFromReadableStream)(readable, {
callServer: _appcallserver.callServer,
findSourceMapURL: _appfindsourcemapurl.findSourceMapURL
});
function ServerRoot(param) {
let { pendingActionQueue } = param;
const initialRSCPayload = (0, _react.use)(initialServerResponse);
const actionQueue = (0, _react.use)(pendingActionQueue);
const router = /*#__PURE__*/ (0, _jsxruntime.jsx)(_approuter.default, {
actionQueue: actionQueue,
globalErrorComponentAndStyles: initialRSCPayload.G,
assetPrefix: initialRSCPayload.p
});
if (process.env.NODE_ENV === 'development' && initialRSCPayload.m) {
// We provide missing slot information in a context provider only during development
// as we log some additional information about the missing slots in the console.
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_approutercontextsharedruntime.MissingSlotContext, {
value: initialRSCPayload.m,
children: router
});
}
return router;
}
const StrictModeIfEnabled = process.env.__NEXT_STRICT_MODE_APP ? _react.default.StrictMode : _react.default.Fragment;
function Root(param) {
let { children } = param;
if (process.env.__NEXT_TEST_MODE) {
// eslint-disable-next-line react-hooks/rules-of-hooks
_react.default.useEffect(()=>{
window.__NEXT_HYDRATED = true;
window.__NEXT_HYDRATED_AT = performance.now();
window.__NEXT_HYDRATED_CB == null ? void 0 : window.__NEXT_HYDRATED_CB.call(window);
}, []);
}
return children;
}
const reactRootOptions = {
onRecoverableError: _onrecoverableerror.onRecoverableError,
onCaughtError: _errorboundarycallbacks.onCaughtError,
onUncaughtError: _errorboundarycallbacks.onUncaughtError
};
function hydrate(instrumentationHooks) {
// React overrides `.then` and doesn't return a new promise chain,
// so we wrap the action queue in a promise to ensure that its value
// is defined when the promise resolves.
// https://github.com/facebook/react/blob/163365a07872337e04826c4f501565d43dbd2fd4/packages/react-client/src/ReactFlightClient.js#L189-L190
const pendingActionQueue = new Promise((resolve, reject)=>{
initialServerResponse.then((initialRSCPayload)=>{
// setAppBuildId should be called only once, during JS initialization
// and before any components have hydrated.
(0, _appbuildid.setAppBuildId)(initialRSCPayload.b);
const initialTimestamp = Date.now();
resolve((0, _approuterinstance.createMutableActionQueue)((0, _createinitialrouterstate.createInitialRouterState)({
navigatedAt: initialTimestamp,
initialFlightData: initialRSCPayload.f,
initialCanonicalUrlParts: initialRSCPayload.c,
initialParallelRoutes: new Map(),
location: window.location,
couldBeIntercepted: initialRSCPayload.i,
postponed: initialRSCPayload.s,
prerendered: initialRSCPayload.S
}), instrumentationHooks));
}, (err)=>reject(err));
});
const reactEl = /*#__PURE__*/ (0, _jsxruntime.jsx)(StrictModeIfEnabled, {
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_headmanagercontextsharedruntime.HeadManagerContext.Provider, {
value: {
appDir: true
},
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(Root, {
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(ServerRoot, {
pendingActionQueue: pendingActionQueue
})
})
})
});
if (document.documentElement.id === '__next_error__') {
let element = reactEl;
// Server rendering failed, fall back to client-side rendering
if (process.env.NODE_ENV !== 'production') {
const { createRootLevelDevOverlayElement } = require('./components/react-dev-overlay/app/client-entry');
// Note this won't cause hydration mismatch because we are doing CSR w/o hydration
element = createRootLevelDevOverlayElement(element);
}
_client.default.createRoot(appElement, reactRootOptions).render(element);
} else {
_react.default.startTransition(()=>{
_client.default.hydrateRoot(appElement, reactEl, {
...reactRootOptions,
formState: initialFormStateData
});
});
}
// TODO-APP: Remove this logic when Float has GC built-in in development.
if (process.env.NODE_ENV !== 'production') {
const { linkGc } = require('./app-link-gc');
linkGc();
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function linkGc(): void;

View File

@@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "linkGc", {
enumerable: true,
get: function() {
return linkGc;
}
});
function linkGc() {
// TODO-APP: Remove this logic when Float has GC built-in in development.
if (process.env.NODE_ENV !== 'production') {
const callback = (mutationList)=>{
for (const mutation of mutationList){
if (mutation.type === 'childList') {
for (const node of mutation.addedNodes){
if ('tagName' in node && node.tagName === 'LINK') {
var _link_dataset_precedence;
const link = node;
if ((_link_dataset_precedence = link.dataset.precedence) == null ? void 0 : _link_dataset_precedence.startsWith('next')) {
const href = link.getAttribute('href');
if (href) {
const [resource, version] = href.split('?v=', 2);
if (version) {
const currentOrigin = window.location.origin;
const allLinks = [
...document.querySelectorAll('link[href^="' + resource + '"]'),
// It's possible that the resource is a full URL or only pathname,
// so we need to remove the alternative href as well.
...document.querySelectorAll('link[href^="' + (resource.startsWith(currentOrigin) ? resource.slice(currentOrigin.length) : currentOrigin + resource) + '"]')
];
for (const otherLink of allLinks){
var _otherLink_dataset_precedence;
if ((_otherLink_dataset_precedence = otherLink.dataset.precedence) == null ? void 0 : _otherLink_dataset_precedence.startsWith('next')) {
const otherHref = otherLink.getAttribute('href');
if (otherHref) {
const [, otherVersion] = otherHref.split('?v=', 2);
if (!otherVersion || +otherVersion < +version) {
// Delay the removal of the stylesheet to avoid FOUC
// caused by `@font-face` rules, as they seem to be
// a couple of ticks delayed between the old and new
// styles being swapped even if the font is cached.
setTimeout(()=>{
otherLink.remove();
}, 5);
const preloadLink = document.querySelector('link[rel="preload"][as="style"][href="' + otherHref + '"]');
if (preloadLink) {
preloadLink.remove();
}
}
}
}
}
}
}
}
}
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
observer.observe(document.head, {
childList: true
});
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-link-gc.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
import './app-webpack';

View File

@@ -0,0 +1,22 @@
// TODO-APP: hydration warning
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
require("./app-webpack");
const _appbootstrap = require("./app-bootstrap");
const _initializeforapprouter = require("./dev/dev-build-indicator/initialize-for-app-router");
const instrumentationHooks = require('../lib/require-instrumentation-client');
(0, _appbootstrap.appBootstrap)(()=>{
const { hydrate } = require('./app-index');
hydrate(instrumentationHooks);
(0, _initializeforapprouter.initializeDevBuildIndicatorForAppRouter)();
});
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-next-dev.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-next-dev.ts"],"sourcesContent":["// TODO-APP: hydration warning\n\nimport './app-webpack'\n\nimport { appBootstrap } from './app-bootstrap'\nimport { initializeDevBuildIndicatorForAppRouter } from './dev/dev-build-indicator/initialize-for-app-router'\n\nconst instrumentationHooks = require('../lib/require-instrumentation-client')\n\nappBootstrap(() => {\n const { hydrate } = require('./app-index')\n hydrate(instrumentationHooks)\n initializeDevBuildIndicatorForAppRouter()\n})\n"],"names":["instrumentationHooks","require","appBootstrap","hydrate","initializeDevBuildIndicatorForAppRouter"],"mappings":"AAAA,8BAA8B;;;;;QAEvB;8BAEsB;wCAC2B;AAExD,MAAMA,uBAAuBC,QAAQ;AAErCC,IAAAA,0BAAY,EAAC;IACX,MAAM,EAAEC,OAAO,EAAE,GAAGF,QAAQ;IAC5BE,QAAQH;IACRI,IAAAA,+DAAuC;AACzC"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,25 @@
// TODO-APP: hydration warning
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
const _appbootstrap = require("./app-bootstrap");
window.next.version += '-turbo';
self.__webpack_hash__ = '';
const instrumentationHooks = require('../lib/require-instrumentation-client');
(0, _appbootstrap.appBootstrap)(()=>{
const { hydrate } = require('./app-index');
hydrate(instrumentationHooks);
if (process.env.NODE_ENV !== 'production') {
const { initializeDevBuildIndicatorForAppRouter } = require('./dev/dev-build-indicator/initialize-for-app-router');
initializeDevBuildIndicatorForAppRouter();
}
});
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-next-turbopack.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-next-turbopack.ts"],"sourcesContent":["// TODO-APP: hydration warning\n\nimport { appBootstrap } from './app-bootstrap'\n\nwindow.next.version += '-turbo'\n;(self as any).__webpack_hash__ = ''\n\nconst instrumentationHooks = require('../lib/require-instrumentation-client')\n\nappBootstrap(() => {\n const { hydrate } = require('./app-index')\n hydrate(instrumentationHooks)\n\n if (process.env.NODE_ENV !== 'production') {\n const { initializeDevBuildIndicatorForAppRouter } =\n require('./dev/dev-build-indicator/initialize-for-app-router') as typeof import('./dev/dev-build-indicator/initialize-for-app-router')\n initializeDevBuildIndicatorForAppRouter()\n }\n})\n"],"names":["window","next","version","self","__webpack_hash__","instrumentationHooks","require","appBootstrap","hydrate","process","env","NODE_ENV","initializeDevBuildIndicatorForAppRouter"],"mappings":"AAAA,8BAA8B;;;;;8BAED;AAE7BA,OAAOC,IAAI,CAACC,OAAO,IAAI;AACrBC,KAAaC,gBAAgB,GAAG;AAElC,MAAMC,uBAAuBC,QAAQ;AAErCC,IAAAA,0BAAY,EAAC;IACX,MAAM,EAAEC,OAAO,EAAE,GAAGF,QAAQ;IAC5BE,QAAQH;IAER,IAAII,QAAQC,GAAG,CAACC,QAAQ,KAAK,cAAc;QACzC,MAAM,EAAEC,uCAAuC,EAAE,GAC/CN,QAAQ;QACVM;IACF;AACF"}

View File

@@ -0,0 +1 @@
import './app-webpack';

View File

@@ -0,0 +1,24 @@
// This import must go first because it needs to patch webpack chunk loading
// before React patches chunk loading.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
require("./app-webpack");
const _appbootstrap = require("./app-bootstrap");
const instrumentationHooks = require('../lib/require-instrumentation-client');
(0, _appbootstrap.appBootstrap)(()=>{
const { hydrate } = require('./app-index');
// Include app-router and layout-router in the main chunk
require('next/dist/client/components/app-router');
require('next/dist/client/components/layout-router');
hydrate(instrumentationHooks);
});
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-next.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-next.ts"],"sourcesContent":["// This import must go first because it needs to patch webpack chunk loading\n// before React patches chunk loading.\nimport './app-webpack'\nimport { appBootstrap } from './app-bootstrap'\n\nconst instrumentationHooks = require('../lib/require-instrumentation-client')\n\nappBootstrap(() => {\n const { hydrate } = require('./app-index')\n // Include app-router and layout-router in the main chunk\n require('next/dist/client/components/app-router')\n require('next/dist/client/components/layout-router')\n hydrate(instrumentationHooks)\n})\n"],"names":["instrumentationHooks","require","appBootstrap","hydrate"],"mappings":"AAAA,4EAA4E;AAC5E,sCAAsC;;;;;QAC/B;8BACsB;AAE7B,MAAMA,uBAAuBC,QAAQ;AAErCC,IAAAA,0BAAY,EAAC;IACX,MAAM,EAAEC,OAAO,EAAE,GAAGF,QAAQ;IAC5B,yDAAyD;IACzDA,QAAQ;IACRA,QAAQ;IACRE,QAAQH;AACV"}

View File

@@ -0,0 +1 @@
export {};

View File

@@ -0,0 +1,66 @@
// Override chunk URL mapping in the webpack runtime
// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
const _deploymentid = require("../build/deployment-id");
const _encodeuripath = require("../shared/lib/encode-uri-path");
// If we have a deployment ID, we need to append it to the webpack chunk names
// I am keeping the process check explicit so this can be statically optimized
if (process.env.NEXT_DEPLOYMENT_ID) {
const suffix = (0, _deploymentid.getDeploymentIdQueryOrEmptyString)();
// eslint-disable-next-line no-undef
const getChunkScriptFilename = __webpack_require__.u;
// eslint-disable-next-line no-undef
__webpack_require__.u = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return(// We encode the chunk filename because our static server matches against and encoded
// filename path.
(0, _encodeuripath.encodeURIPath)(getChunkScriptFilename(...args)) + suffix);
};
// eslint-disable-next-line no-undef
const getChunkCssFilename = __webpack_require__.k;
// eslint-disable-next-line no-undef
__webpack_require__.k = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return getChunkCssFilename(...args) + suffix;
};
// eslint-disable-next-line no-undef
const getMiniCssFilename = __webpack_require__.miniCssF;
// eslint-disable-next-line no-undef
__webpack_require__.miniCssF = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return getMiniCssFilename(...args) + suffix;
};
} else {
// eslint-disable-next-line no-undef
const getChunkScriptFilename = __webpack_require__.u;
// eslint-disable-next-line no-undef
__webpack_require__.u = function() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
return(// We encode the chunk filename because our static server matches against and encoded
// filename path.
(0, _encodeuripath.encodeURIPath)(getChunkScriptFilename(...args)));
};
// We don't need to override __webpack_require__.k because we don't modify
// the css chunk name when not using deployment id suffixes
// WE don't need to override __webpack_require__.miniCssF because we don't modify
// the mini css chunk name when not using deployment id suffixes
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-webpack.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/app-webpack.ts"],"sourcesContent":["// Override chunk URL mapping in the webpack runtime\n// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204\n\nimport { getDeploymentIdQueryOrEmptyString } from '../build/deployment-id'\nimport { encodeURIPath } from '../shared/lib/encode-uri-path'\n\ndeclare const __webpack_require__: any\n\n// If we have a deployment ID, we need to append it to the webpack chunk names\n// I am keeping the process check explicit so this can be statically optimized\nif (process.env.NEXT_DEPLOYMENT_ID) {\n const suffix = getDeploymentIdQueryOrEmptyString()\n // eslint-disable-next-line no-undef\n const getChunkScriptFilename = __webpack_require__.u\n // eslint-disable-next-line no-undef\n __webpack_require__.u = (...args: any[]) =>\n // We encode the chunk filename because our static server matches against and encoded\n // filename path.\n encodeURIPath(getChunkScriptFilename(...args)) + suffix\n\n // eslint-disable-next-line no-undef\n const getChunkCssFilename = __webpack_require__.k\n // eslint-disable-next-line no-undef\n __webpack_require__.k = (...args: any[]) =>\n getChunkCssFilename(...args) + suffix\n\n // eslint-disable-next-line no-undef\n const getMiniCssFilename = __webpack_require__.miniCssF\n // eslint-disable-next-line no-undef\n __webpack_require__.miniCssF = (...args: any[]) =>\n getMiniCssFilename(...args) + suffix\n} else {\n // eslint-disable-next-line no-undef\n const getChunkScriptFilename = __webpack_require__.u\n // eslint-disable-next-line no-undef\n __webpack_require__.u = (...args: any[]) =>\n // We encode the chunk filename because our static server matches against and encoded\n // filename path.\n encodeURIPath(getChunkScriptFilename(...args))\n\n // We don't need to override __webpack_require__.k because we don't modify\n // the css chunk name when not using deployment id suffixes\n\n // WE don't need to override __webpack_require__.miniCssF because we don't modify\n // the mini css chunk name when not using deployment id suffixes\n}\n\nexport {}\n"],"names":["process","env","NEXT_DEPLOYMENT_ID","suffix","getDeploymentIdQueryOrEmptyString","getChunkScriptFilename","__webpack_require__","u","args","encodeURIPath","getChunkCssFilename","k","getMiniCssFilename","miniCssF"],"mappings":"AAAA,oDAAoD;AACpD,8GAA8G;;;;;8BAE5D;+BACpB;AAI9B,8EAA8E;AAC9E,8EAA8E;AAC9E,IAAIA,QAAQC,GAAG,CAACC,kBAAkB,EAAE;IAClC,MAAMC,SAASC,IAAAA,+CAAiC;IAChD,oCAAoC;IACpC,MAAMC,yBAAyBC,oBAAoBC,CAAC;IACpD,oCAAoC;IACpCD,oBAAoBC,CAAC,GAAG;yCAAIC;YAAAA;;eAC1B,qFAAqF;QACrF,iBAAiB;QACjBC,IAAAA,4BAAa,EAACJ,0BAA0BG,SAASL;;IAEnD,oCAAoC;IACpC,MAAMO,sBAAsBJ,oBAAoBK,CAAC;IACjD,oCAAoC;IACpCL,oBAAoBK,CAAC,GAAG;yCAAIH;YAAAA;;eAC1BE,uBAAuBF,QAAQL;;IAEjC,oCAAoC;IACpC,MAAMS,qBAAqBN,oBAAoBO,QAAQ;IACvD,oCAAoC;IACpCP,oBAAoBO,QAAQ,GAAG;yCAAIL;YAAAA;;eACjCI,sBAAsBJ,QAAQL;;AAClC,OAAO;IACL,oCAAoC;IACpC,MAAME,yBAAyBC,oBAAoBC,CAAC;IACpD,oCAAoC;IACpCD,oBAAoBC,CAAC,GAAG;yCAAIC;YAAAA;;eAC1B,qFAAqF;QACrF,iBAAiB;QACjBC,IAAAA,4BAAa,EAACJ,0BAA0BG;;AAE1C,0EAA0E;AAC1E,2DAA2D;AAE3D,iFAAiF;AACjF,gEAAgE;AAClE"}

View File

@@ -0,0 +1,8 @@
/**
* Function to correctly assign location to URL
*
* The method will add basePath, and will also correctly add location (including if it is a relative path)
* @param location Location that should be added to the url
* @param url Base URL to which the location should be assigned
*/
export declare function assignLocation(location: string, url: URL): URL;

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "assignLocation", {
enumerable: true,
get: function() {
return assignLocation;
}
});
const _addbasepath = require("./add-base-path");
function assignLocation(location, url) {
if (location.startsWith('.')) {
const urlBase = url.origin + url.pathname;
return new URL(// In order for a relative path to be added to the current url correctly, the current url must end with a slash
// new URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'
// new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'
(urlBase.endsWith('/') ? urlBase : urlBase + '/') + location);
}
return new URL((0, _addbasepath.addBasePath)(location), url.href);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=assign-location.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/client/assign-location.ts"],"sourcesContent":["import { addBasePath } from './add-base-path'\n\n/**\n * Function to correctly assign location to URL\n *\n * The method will add basePath, and will also correctly add location (including if it is a relative path)\n * @param location Location that should be added to the url\n * @param url Base URL to which the location should be assigned\n */\nexport function assignLocation(location: string, url: URL): URL {\n if (location.startsWith('.')) {\n const urlBase = url.origin + url.pathname\n return new URL(\n // In order for a relative path to be added to the current url correctly, the current url must end with a slash\n // new URL('./relative', 'https://example.com/subdir').href -> 'https://example.com/relative'\n // new URL('./relative', 'https://example.com/subdir/').href -> 'https://example.com/subdir/relative'\n (urlBase.endsWith('/') ? urlBase : urlBase + '/') + location\n )\n }\n\n return new URL(addBasePath(location), url.href)\n}\n"],"names":["assignLocation","location","url","startsWith","urlBase","origin","pathname","URL","endsWith","addBasePath","href"],"mappings":";;;;+BASgBA;;;eAAAA;;;6BATY;AASrB,SAASA,eAAeC,QAAgB,EAAEC,GAAQ;IACvD,IAAID,SAASE,UAAU,CAAC,MAAM;QAC5B,MAAMC,UAAUF,IAAIG,MAAM,GAAGH,IAAII,QAAQ;QACzC,OAAO,IAAIC,IAIT,AAHA,+GAA+G;QAC/G,6FAA6F;QAC7F,qGAAqG;QACpGH,CAAAA,QAAQI,QAAQ,CAAC,OAAOJ,UAAUA,UAAU,GAAE,IAAKH;IAExD;IAEA,OAAO,IAAIM,IAAIE,IAAAA,wBAAW,EAACR,WAAWC,IAAIQ,IAAI;AAChD"}

View File

@@ -0,0 +1,12 @@
import type { NextRouter } from '../router';
/**
* useRouter from `next/compat/router` is designed to assist developers
* migrating from `pages/` to `app/`. Unlike `next/router`, this hook does not
* throw when the `NextRouter` is not mounted, and instead returns `null`. The
* more concrete return type here lets developers use this hook within
* components that could be shared between both `app/` and `pages/` and handle
* to the case where the router is not mounted.
*
* @returns The `NextRouter` instance if it's available, otherwise `null`.
*/
export declare function useRouter(): NextRouter | null;

View File

@@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "useRouter", {
enumerable: true,
get: function() {
return useRouter;
}
});
const _react = require("react");
const _routercontextsharedruntime = require("../../shared/lib/router-context.shared-runtime");
function useRouter() {
return (0, _react.useContext)(_routercontextsharedruntime.RouterContext);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=router.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/compat/router.ts"],"sourcesContent":["import { useContext } from 'react'\nimport { RouterContext } from '../../shared/lib/router-context.shared-runtime'\nimport type { NextRouter } from '../router'\n\n/**\n * useRouter from `next/compat/router` is designed to assist developers\n * migrating from `pages/` to `app/`. Unlike `next/router`, this hook does not\n * throw when the `NextRouter` is not mounted, and instead returns `null`. The\n * more concrete return type here lets developers use this hook within\n * components that could be shared between both `app/` and `pages/` and handle\n * to the case where the router is not mounted.\n *\n * @returns The `NextRouter` instance if it's available, otherwise `null`.\n */\nexport function useRouter(): NextRouter | null {\n return useContext(RouterContext)\n}\n"],"names":["useRouter","useContext","RouterContext"],"mappings":";;;;+BAcgBA;;;eAAAA;;;uBAdW;4CACG;AAavB,SAASA;IACd,OAAOC,IAAAA,iBAAU,EAACC,yCAAa;AACjC"}

View File

@@ -0,0 +1,4 @@
import type { FlightRouterState } from '../../server/app-render/types';
export declare function AppRouterAnnouncer({ tree }: {
tree: FlightRouterState;
}): import("react").ReactPortal | null;

View File

@@ -0,0 +1,80 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "AppRouterAnnouncer", {
enumerable: true,
get: function() {
return AppRouterAnnouncer;
}
});
const _react = require("react");
const _reactdom = require("react-dom");
const ANNOUNCER_TYPE = 'next-route-announcer';
const ANNOUNCER_ID = '__next-route-announcer__';
function getAnnouncerNode() {
var _existingAnnouncer_shadowRoot;
const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0];
if (existingAnnouncer == null ? void 0 : (_existingAnnouncer_shadowRoot = existingAnnouncer.shadowRoot) == null ? void 0 : _existingAnnouncer_shadowRoot.childNodes[0]) {
return existingAnnouncer.shadowRoot.childNodes[0];
} else {
const container = document.createElement(ANNOUNCER_TYPE);
container.style.cssText = 'position:absolute';
const announcer = document.createElement('div');
announcer.ariaLive = 'assertive';
announcer.id = ANNOUNCER_ID;
announcer.role = 'alert';
announcer.style.cssText = 'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal';
// Use shadow DOM here to avoid any potential CSS bleed
const shadow = container.attachShadow({
mode: 'open'
});
shadow.appendChild(announcer);
document.body.appendChild(container);
return announcer;
}
}
function AppRouterAnnouncer(param) {
let { tree } = param;
const [portalNode, setPortalNode] = (0, _react.useState)(null);
(0, _react.useEffect)(()=>{
const announcer = getAnnouncerNode();
setPortalNode(announcer);
return ()=>{
const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0];
if (container == null ? void 0 : container.isConnected) {
document.body.removeChild(container);
}
};
}, []);
const [routeAnnouncement, setRouteAnnouncement] = (0, _react.useState)('');
const previousTitle = (0, _react.useRef)(undefined);
(0, _react.useEffect)(()=>{
let currentTitle = '';
if (document.title) {
currentTitle = document.title;
} else {
const pageHeader = document.querySelector('h1');
if (pageHeader) {
currentTitle = pageHeader.innerText || pageHeader.textContent || '';
}
}
// Only announce the title change, but not for the first load because screen
// readers do that automatically.
if (previousTitle.current !== undefined && previousTitle.current !== currentTitle) {
setRouteAnnouncement(currentTitle);
}
previousTitle.current = currentTitle;
}, [
tree
]);
return portalNode ? /*#__PURE__*/ (0, _reactdom.createPortal)(routeAnnouncement, portalNode) : null;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-router-announcer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/app-router-announcer.tsx"],"sourcesContent":["import { useEffect, useRef, useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport type { FlightRouterState } from '../../server/app-render/types'\n\nconst ANNOUNCER_TYPE = 'next-route-announcer'\nconst ANNOUNCER_ID = '__next-route-announcer__'\n\nfunction getAnnouncerNode() {\n const existingAnnouncer = document.getElementsByName(ANNOUNCER_TYPE)[0]\n if (existingAnnouncer?.shadowRoot?.childNodes[0]) {\n return existingAnnouncer.shadowRoot.childNodes[0] as HTMLElement\n } else {\n const container = document.createElement(ANNOUNCER_TYPE)\n container.style.cssText = 'position:absolute'\n const announcer = document.createElement('div')\n announcer.ariaLive = 'assertive'\n announcer.id = ANNOUNCER_ID\n announcer.role = 'alert'\n announcer.style.cssText =\n 'position:absolute;border:0;height:1px;margin:-1px;padding:0;width:1px;clip:rect(0 0 0 0);overflow:hidden;white-space:nowrap;word-wrap:normal'\n\n // Use shadow DOM here to avoid any potential CSS bleed\n const shadow = container.attachShadow({ mode: 'open' })\n shadow.appendChild(announcer)\n document.body.appendChild(container)\n return announcer\n }\n}\n\nexport function AppRouterAnnouncer({ tree }: { tree: FlightRouterState }) {\n const [portalNode, setPortalNode] = useState<HTMLElement | null>(null)\n\n useEffect(() => {\n const announcer = getAnnouncerNode()\n setPortalNode(announcer)\n return () => {\n const container = document.getElementsByTagName(ANNOUNCER_TYPE)[0]\n if (container?.isConnected) {\n document.body.removeChild(container)\n }\n }\n }, [])\n\n const [routeAnnouncement, setRouteAnnouncement] = useState('')\n const previousTitle = useRef<string | undefined>(undefined)\n\n useEffect(() => {\n let currentTitle = ''\n if (document.title) {\n currentTitle = document.title\n } else {\n const pageHeader = document.querySelector('h1')\n if (pageHeader) {\n currentTitle = pageHeader.innerText || pageHeader.textContent || ''\n }\n }\n\n // Only announce the title change, but not for the first load because screen\n // readers do that automatically.\n if (\n previousTitle.current !== undefined &&\n previousTitle.current !== currentTitle\n ) {\n setRouteAnnouncement(currentTitle)\n }\n previousTitle.current = currentTitle\n }, [tree])\n\n return portalNode ? createPortal(routeAnnouncement, portalNode) : null\n}\n"],"names":["AppRouterAnnouncer","ANNOUNCER_TYPE","ANNOUNCER_ID","getAnnouncerNode","existingAnnouncer","document","getElementsByName","shadowRoot","childNodes","container","createElement","style","cssText","announcer","ariaLive","id","role","shadow","attachShadow","mode","appendChild","body","tree","portalNode","setPortalNode","useState","useEffect","getElementsByTagName","isConnected","removeChild","routeAnnouncement","setRouteAnnouncement","previousTitle","useRef","undefined","currentTitle","title","pageHeader","querySelector","innerText","textContent","current","createPortal"],"mappings":";;;;+BA6BgBA;;;eAAAA;;;uBA7B4B;0BACf;AAG7B,MAAMC,iBAAiB;AACvB,MAAMC,eAAe;AAErB,SAASC;QAEHC;IADJ,MAAMA,oBAAoBC,SAASC,iBAAiB,CAACL,eAAe,CAAC,EAAE;IACvE,IAAIG,sCAAAA,gCAAAA,kBAAmBG,UAAU,qBAA7BH,8BAA+BI,UAAU,CAAC,EAAE,EAAE;QAChD,OAAOJ,kBAAkBG,UAAU,CAACC,UAAU,CAAC,EAAE;IACnD,OAAO;QACL,MAAMC,YAAYJ,SAASK,aAAa,CAACT;QACzCQ,UAAUE,KAAK,CAACC,OAAO,GAAG;QAC1B,MAAMC,YAAYR,SAASK,aAAa,CAAC;QACzCG,UAAUC,QAAQ,GAAG;QACrBD,UAAUE,EAAE,GAAGb;QACfW,UAAUG,IAAI,GAAG;QACjBH,UAAUF,KAAK,CAACC,OAAO,GACrB;QAEF,uDAAuD;QACvD,MAAMK,SAASR,UAAUS,YAAY,CAAC;YAAEC,MAAM;QAAO;QACrDF,OAAOG,WAAW,CAACP;QACnBR,SAASgB,IAAI,CAACD,WAAW,CAACX;QAC1B,OAAOI;IACT;AACF;AAEO,SAASb,mBAAmB,KAAqC;IAArC,IAAA,EAAEsB,IAAI,EAA+B,GAArC;IACjC,MAAM,CAACC,YAAYC,cAAc,GAAGC,IAAAA,eAAQ,EAAqB;IAEjEC,IAAAA,gBAAS,EAAC;QACR,MAAMb,YAAYV;QAClBqB,cAAcX;QACd,OAAO;YACL,MAAMJ,YAAYJ,SAASsB,oBAAoB,CAAC1B,eAAe,CAAC,EAAE;YAClE,IAAIQ,6BAAAA,UAAWmB,WAAW,EAAE;gBAC1BvB,SAASgB,IAAI,CAACQ,WAAW,CAACpB;YAC5B;QACF;IACF,GAAG,EAAE;IAEL,MAAM,CAACqB,mBAAmBC,qBAAqB,GAAGN,IAAAA,eAAQ,EAAC;IAC3D,MAAMO,gBAAgBC,IAAAA,aAAM,EAAqBC;IAEjDR,IAAAA,gBAAS,EAAC;QACR,IAAIS,eAAe;QACnB,IAAI9B,SAAS+B,KAAK,EAAE;YAClBD,eAAe9B,SAAS+B,KAAK;QAC/B,OAAO;YACL,MAAMC,aAAahC,SAASiC,aAAa,CAAC;YAC1C,IAAID,YAAY;gBACdF,eAAeE,WAAWE,SAAS,IAAIF,WAAWG,WAAW,IAAI;YACnE;QACF;QAEA,4EAA4E;QAC5E,iCAAiC;QACjC,IACER,cAAcS,OAAO,KAAKP,aAC1BF,cAAcS,OAAO,KAAKN,cAC1B;YACAJ,qBAAqBI;QACvB;QACAH,cAAcS,OAAO,GAAGN;IAC1B,GAAG;QAACb;KAAK;IAET,OAAOC,2BAAamB,IAAAA,sBAAY,EAACZ,mBAAmBP,cAAc;AACpE"}

View File

@@ -0,0 +1,16 @@
export declare const RSC_HEADER: "RSC";
export declare const ACTION_HEADER: "Next-Action";
export declare const NEXT_ROUTER_STATE_TREE_HEADER: "Next-Router-State-Tree";
export declare const NEXT_ROUTER_PREFETCH_HEADER: "Next-Router-Prefetch";
export declare const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER: "Next-Router-Segment-Prefetch";
export declare const NEXT_HMR_REFRESH_HEADER: "Next-HMR-Refresh";
export declare const NEXT_HMR_REFRESH_HASH_COOKIE: "__next_hmr_refresh_hash__";
export declare const NEXT_URL: "Next-Url";
export declare const RSC_CONTENT_TYPE_HEADER: "text/x-component";
export declare const FLIGHT_HEADERS: readonly ["RSC", "Next-Router-State-Tree", "Next-Router-Prefetch", "Next-HMR-Refresh", "Next-Router-Segment-Prefetch"];
export declare const NEXT_RSC_UNION_QUERY: "_rsc";
export declare const NEXT_ROUTER_STALE_TIME_HEADER: "x-nextjs-stale-time";
export declare const NEXT_DID_POSTPONE_HEADER: "x-nextjs-postponed";
export declare const NEXT_REWRITTEN_PATH_HEADER: "x-nextjs-rewritten-path";
export declare const NEXT_REWRITTEN_QUERY_HEADER: "x-nextjs-rewritten-query";
export declare const NEXT_IS_PRERENDER_HEADER: "x-nextjs-prerender";

View File

@@ -0,0 +1,108 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ACTION_HEADER: null,
FLIGHT_HEADERS: null,
NEXT_DID_POSTPONE_HEADER: null,
NEXT_HMR_REFRESH_HASH_COOKIE: null,
NEXT_HMR_REFRESH_HEADER: null,
NEXT_IS_PRERENDER_HEADER: null,
NEXT_REWRITTEN_PATH_HEADER: null,
NEXT_REWRITTEN_QUERY_HEADER: null,
NEXT_ROUTER_PREFETCH_HEADER: null,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER: null,
NEXT_ROUTER_STALE_TIME_HEADER: null,
NEXT_ROUTER_STATE_TREE_HEADER: null,
NEXT_RSC_UNION_QUERY: null,
NEXT_URL: null,
RSC_CONTENT_TYPE_HEADER: null,
RSC_HEADER: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ACTION_HEADER: function() {
return ACTION_HEADER;
},
FLIGHT_HEADERS: function() {
return FLIGHT_HEADERS;
},
NEXT_DID_POSTPONE_HEADER: function() {
return NEXT_DID_POSTPONE_HEADER;
},
NEXT_HMR_REFRESH_HASH_COOKIE: function() {
return NEXT_HMR_REFRESH_HASH_COOKIE;
},
NEXT_HMR_REFRESH_HEADER: function() {
return NEXT_HMR_REFRESH_HEADER;
},
NEXT_IS_PRERENDER_HEADER: function() {
return NEXT_IS_PRERENDER_HEADER;
},
NEXT_REWRITTEN_PATH_HEADER: function() {
return NEXT_REWRITTEN_PATH_HEADER;
},
NEXT_REWRITTEN_QUERY_HEADER: function() {
return NEXT_REWRITTEN_QUERY_HEADER;
},
NEXT_ROUTER_PREFETCH_HEADER: function() {
return NEXT_ROUTER_PREFETCH_HEADER;
},
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER: function() {
return NEXT_ROUTER_SEGMENT_PREFETCH_HEADER;
},
NEXT_ROUTER_STALE_TIME_HEADER: function() {
return NEXT_ROUTER_STALE_TIME_HEADER;
},
NEXT_ROUTER_STATE_TREE_HEADER: function() {
return NEXT_ROUTER_STATE_TREE_HEADER;
},
NEXT_RSC_UNION_QUERY: function() {
return NEXT_RSC_UNION_QUERY;
},
NEXT_URL: function() {
return NEXT_URL;
},
RSC_CONTENT_TYPE_HEADER: function() {
return RSC_CONTENT_TYPE_HEADER;
},
RSC_HEADER: function() {
return RSC_HEADER;
}
});
const RSC_HEADER = 'RSC';
const ACTION_HEADER = 'Next-Action';
const NEXT_ROUTER_STATE_TREE_HEADER = 'Next-Router-State-Tree';
const NEXT_ROUTER_PREFETCH_HEADER = 'Next-Router-Prefetch';
const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'Next-Router-Segment-Prefetch';
const NEXT_HMR_REFRESH_HEADER = 'Next-HMR-Refresh';
const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__';
const NEXT_URL = 'Next-Url';
const RSC_CONTENT_TYPE_HEADER = 'text/x-component';
const FLIGHT_HEADERS = [
RSC_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_HMR_REFRESH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER
];
const NEXT_RSC_UNION_QUERY = '_rsc';
const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time';
const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed';
const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path';
const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query';
const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender';
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-router-headers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/app-router-headers.ts"],"sourcesContent":["export const RSC_HEADER = 'RSC' as const\nexport const ACTION_HEADER = 'Next-Action' as const\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'Next-Router-State-Tree' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'Next-Router-Prefetch' as const\n// This contains the path to the segment being prefetched.\n// TODO: If we change Next-Router-State-Tree to be a segment path, we can use\n// that instead. Then Next-Router-Prefetch and Next-Router-Segment-Prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =\n 'Next-Router-Segment-Prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'Next-HMR-Refresh' as const\nexport const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const\nexport const NEXT_URL = 'Next-Url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\nexport const FLIGHT_HEADERS = [\n RSC_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n] as const\n\nexport const NEXT_RSC_UNION_QUERY = '_rsc' as const\n\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time' as const\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' as const\nexport const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path' as const\nexport const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query' as const\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender' as const\n"],"names":["ACTION_HEADER","FLIGHT_HEADERS","NEXT_DID_POSTPONE_HEADER","NEXT_HMR_REFRESH_HASH_COOKIE","NEXT_HMR_REFRESH_HEADER","NEXT_IS_PRERENDER_HEADER","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_RSC_UNION_QUERY","NEXT_URL","RSC_CONTENT_TYPE_HEADER","RSC_HEADER"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;IACaA,aAAa;eAAbA;;IAiBAC,cAAc;eAAdA;;IAWAC,wBAAwB;eAAxBA;;IAfAC,4BAA4B;eAA5BA;;IADAC,uBAAuB;eAAvBA;;IAmBAC,wBAAwB;eAAxBA;;IAFAC,0BAA0B;eAA1BA;;IACAC,2BAA2B;eAA3BA;;IAzBAC,2BAA2B;eAA3BA;;IAKAC,mCAAmC;eAAnCA;;IAiBAC,6BAA6B;eAA7BA;;IAvBAC,6BAA6B;eAA7BA;;IAqBAC,oBAAoB;eAApBA;;IAXAC,QAAQ;eAARA;;IACAC,uBAAuB;eAAvBA;;IAhBAC,UAAU;eAAVA;;;AAAN,MAAMA,aAAa;AACnB,MAAMf,gBAAgB;AAItB,MAAMW,gCAAgC;AACtC,MAAMH,8BAA8B;AAKpC,MAAMC,sCACX;AACK,MAAML,0BAA0B;AAChC,MAAMD,+BAA+B;AACrC,MAAMU,WAAW;AACjB,MAAMC,0BAA0B;AAEhC,MAAMb,iBAAiB;IAC5Bc;IACAJ;IACAH;IACAJ;IACAK;CACD;AAEM,MAAMG,uBAAuB;AAE7B,MAAMF,gCAAgC;AACtC,MAAMR,2BAA2B;AACjC,MAAMI,6BAA6B;AACnC,MAAMC,8BAA8B;AACpC,MAAMF,2BAA2B"}

View File

@@ -0,0 +1,32 @@
import { type AppRouterState, type ReducerActions, type ReducerState, type NavigateAction } from './router-reducer/router-reducer-types';
import type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime';
import { type LinkInstance } from './links';
import type { FlightRouterState } from '../../server/app-render/types';
import type { ClientInstrumentationHooks } from '../app-index';
export type DispatchStatePromise = React.Dispatch<ReducerState>;
export type AppRouterActionQueue = {
state: AppRouterState;
dispatch: (payload: ReducerActions, setState: DispatchStatePromise) => void;
action: (state: AppRouterState, action: ReducerActions) => ReducerState;
onRouterTransitionStart: ((url: string, type: 'push' | 'replace' | 'traverse') => void) | null;
pending: ActionQueueNode | null;
needsRefresh?: boolean;
last: ActionQueueNode | null;
};
export type ActionQueueNode = {
payload: ReducerActions;
next: ActionQueueNode | null;
resolve: (value: ReducerState) => void;
reject: (err: Error) => void;
discarded?: boolean;
};
export declare function createMutableActionQueue(initialState: AppRouterState, instrumentationHooks: ClientInstrumentationHooks | null): AppRouterActionQueue;
export declare function getCurrentAppRouterState(): AppRouterState | null;
export declare function dispatchNavigateAction(href: string, navigateType: NavigateAction['navigateType'], shouldScroll: boolean, linkInstanceRef: LinkInstance | null): void;
export declare function dispatchTraverseAction(href: string, tree: FlightRouterState | undefined): void;
/**
* The app router that is exposed through `useRouter`. These are public API
* methods. Internal Next.js code should call the lower level methods directly
* (although there's lots of existing code that doesn't do that).
*/
export declare const publicAppRouterInstance: AppRouterInstance;

View File

@@ -0,0 +1,311 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createMutableActionQueue: null,
dispatchNavigateAction: null,
dispatchTraverseAction: null,
getCurrentAppRouterState: null,
publicAppRouterInstance: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createMutableActionQueue: function() {
return createMutableActionQueue;
},
dispatchNavigateAction: function() {
return dispatchNavigateAction;
},
dispatchTraverseAction: function() {
return dispatchTraverseAction;
},
getCurrentAppRouterState: function() {
return getCurrentAppRouterState;
},
publicAppRouterInstance: function() {
return publicAppRouterInstance;
}
});
const _routerreducertypes = require("./router-reducer/router-reducer-types");
const _routerreducer = require("./router-reducer/router-reducer");
const _react = require("react");
const _isthenable = require("../../shared/lib/is-thenable");
const _segmentcache = require("./segment-cache");
const _useactionqueue = require("./use-action-queue");
const _addbasepath = require("../add-base-path");
const _approuter = require("./app-router");
const _prefetchreducer = require("./router-reducer/reducers/prefetch-reducer");
const _links = require("./links");
function runRemainingActions(actionQueue, setState) {
if (actionQueue.pending !== null) {
actionQueue.pending = actionQueue.pending.next;
if (actionQueue.pending !== null) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
runAction({
actionQueue,
action: actionQueue.pending,
setState
});
} else {
// No more actions are pending, check if a refresh is needed
if (actionQueue.needsRefresh) {
actionQueue.needsRefresh = false;
actionQueue.dispatch({
type: _routerreducertypes.ACTION_REFRESH,
origin: window.location.origin
}, setState);
}
}
}
}
async function runAction(param) {
let { actionQueue, action, setState } = param;
const prevState = actionQueue.state;
actionQueue.pending = action;
const payload = action.payload;
const actionResult = actionQueue.action(prevState, payload);
function handleResult(nextState) {
// if we discarded this action, the state should also be discarded
if (action.discarded) {
return;
}
actionQueue.state = nextState;
runRemainingActions(actionQueue, setState);
action.resolve(nextState);
}
// if the action is a promise, set up a callback to resolve it
if ((0, _isthenable.isThenable)(actionResult)) {
actionResult.then(handleResult, (err)=>{
runRemainingActions(actionQueue, setState);
action.reject(err);
});
} else {
handleResult(actionResult);
}
}
function dispatchAction(actionQueue, payload, setState) {
let resolvers = {
resolve: setState,
reject: ()=>{}
};
// most of the action types are async with the exception of restore
// it's important that restore is handled quickly since it's fired on the popstate event
// and we don't want to add any delay on a back/forward nav
// this only creates a promise for the async actions
if (payload.type !== _routerreducertypes.ACTION_RESTORE) {
// Create the promise and assign the resolvers to the object.
const deferredPromise = new Promise((resolve, reject)=>{
resolvers = {
resolve,
reject
};
});
(0, _react.startTransition)(()=>{
// we immediately notify React of the pending promise -- the resolver is attached to the action node
// and will be called when the associated action promise resolves
setState(deferredPromise);
});
}
const newAction = {
payload,
next: null,
resolve: resolvers.resolve,
reject: resolvers.reject
};
// Check if the queue is empty
if (actionQueue.pending === null) {
// The queue is empty, so add the action and start it immediately
// Mark this action as the last in the queue
actionQueue.last = newAction;
runAction({
actionQueue,
action: newAction,
setState
});
} else if (payload.type === _routerreducertypes.ACTION_NAVIGATE || payload.type === _routerreducertypes.ACTION_RESTORE) {
// Navigations (including back/forward) take priority over any pending actions.
// Mark the pending action as discarded (so the state is never applied) and start the navigation action immediately.
actionQueue.pending.discarded = true;
// The rest of the current queue should still execute after this navigation.
// (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)
newAction.next = actionQueue.pending.next;
// if the pending action was a server action, mark the queue as needing a refresh once events are processed
if (actionQueue.pending.payload.type === _routerreducertypes.ACTION_SERVER_ACTION) {
actionQueue.needsRefresh = true;
}
runAction({
actionQueue,
action: newAction,
setState
});
} else {
// The queue is not empty, so add the action to the end of the queue
// It will be started by runRemainingActions after the previous action finishes
if (actionQueue.last !== null) {
actionQueue.last.next = newAction;
}
actionQueue.last = newAction;
}
}
let globalActionQueue = null;
function createMutableActionQueue(initialState, instrumentationHooks) {
const actionQueue = {
state: initialState,
dispatch: (payload, setState)=>dispatchAction(actionQueue, payload, setState),
action: async (state, action)=>{
const result = (0, _routerreducer.reducer)(state, action);
return result;
},
pending: null,
last: null,
onRouterTransitionStart: instrumentationHooks !== null && typeof instrumentationHooks.onRouterTransitionStart === 'function' ? instrumentationHooks.onRouterTransitionStart : null
};
if (typeof window !== 'undefined') {
// The action queue is lazily created on hydration, but after that point
// it doesn't change. So we can store it in a global rather than pass
// it around everywhere via props/context.
if (globalActionQueue !== null) {
throw Object.defineProperty(new Error('Internal Next.js Error: createMutableActionQueue was called more ' + 'than once'), "__NEXT_ERROR_CODE", {
value: "E624",
enumerable: false,
configurable: true
});
}
globalActionQueue = actionQueue;
}
return actionQueue;
}
function getCurrentAppRouterState() {
return globalActionQueue !== null ? globalActionQueue.state : null;
}
function getAppRouterActionQueue() {
if (globalActionQueue === null) {
throw Object.defineProperty(new Error('Internal Next.js error: Router action dispatched before initialization.'), "__NEXT_ERROR_CODE", {
value: "E668",
enumerable: false,
configurable: true
});
}
return globalActionQueue;
}
function getProfilingHookForOnNavigationStart() {
if (globalActionQueue !== null) {
return globalActionQueue.onRouterTransitionStart;
}
return null;
}
function dispatchNavigateAction(href, navigateType, shouldScroll, linkInstanceRef) {
// TODO: This stuff could just go into the reducer. Leaving as-is for now
// since we're about to rewrite all the router reducer stuff anyway.
const url = new URL((0, _addbasepath.addBasePath)(href), location.href);
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url;
}
(0, _links.setLinkForCurrentNavigation)(linkInstanceRef);
const onRouterTransitionStart = getProfilingHookForOnNavigationStart();
if (onRouterTransitionStart !== null) {
onRouterTransitionStart(href, navigateType);
}
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_NAVIGATE,
url,
isExternalUrl: (0, _approuter.isExternalURL)(url),
locationSearch: location.search,
shouldScroll,
navigateType,
allowAliasing: true
});
}
function dispatchTraverseAction(href, tree) {
const onRouterTransitionStart = getProfilingHookForOnNavigationStart();
if (onRouterTransitionStart !== null) {
onRouterTransitionStart(href, 'traverse');
}
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_RESTORE,
url: new URL(href),
tree
});
}
const publicAppRouterInstance = {
back: ()=>window.history.back(),
forward: ()=>window.history.forward(),
prefetch: process.env.__NEXT_CLIENT_SEGMENT_CACHE ? // data in the router reducer state; it writes into a global mutable
// cache. So we don't need to dispatch an action.
(href, options)=>{
const actionQueue = getAppRouterActionQueue();
(0, _segmentcache.prefetch)(href, actionQueue.state.nextUrl, actionQueue.state.tree, (options == null ? void 0 : options.kind) === _routerreducertypes.PrefetchKind.FULL);
} : (href, options)=>{
// Use the old prefetch implementation.
const actionQueue = getAppRouterActionQueue();
const url = (0, _approuter.createPrefetchURL)(href);
if (url !== null) {
var _options_kind;
// The prefetch reducer doesn't actually update any state or
// trigger a rerender. It just writes to a mutable cache. So we
// shouldn't bother calling setState/dispatch; we can just re-run
// the reducer directly using the current state.
// TODO: Refactor this away from a "reducer" so it's
// less confusing.
(0, _prefetchreducer.prefetchReducer)(actionQueue.state, {
type: _routerreducertypes.ACTION_PREFETCH,
url,
kind: (_options_kind = options == null ? void 0 : options.kind) != null ? _options_kind : _routerreducertypes.PrefetchKind.FULL
});
}
},
replace: (href, options)=>{
(0, _react.startTransition)(()=>{
var _options_scroll;
dispatchNavigateAction(href, 'replace', (_options_scroll = options == null ? void 0 : options.scroll) != null ? _options_scroll : true, null);
});
},
push: (href, options)=>{
(0, _react.startTransition)(()=>{
var _options_scroll;
dispatchNavigateAction(href, 'push', (_options_scroll = options == null ? void 0 : options.scroll) != null ? _options_scroll : true, null);
});
},
refresh: ()=>{
(0, _react.startTransition)(()=>{
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_REFRESH,
origin: window.location.origin
});
});
},
hmrRefresh: ()=>{
if (process.env.NODE_ENV !== 'development') {
throw Object.defineProperty(new Error('hmrRefresh can only be used in development mode. Please use refresh instead.'), "__NEXT_ERROR_CODE", {
value: "E485",
enumerable: false,
configurable: true
});
} else {
(0, _react.startTransition)(()=>{
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_HMR_REFRESH,
origin: window.location.origin
});
});
}
}
};
// Exists for debugging purposes. Don't use in application code.
if (typeof window !== 'undefined' && window.next) {
window.next.router = publicAppRouterInstance;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-router-instance.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
import React from 'react';
import type { CacheNode } from '../../shared/lib/app-router-context.shared-runtime';
import { type GlobalErrorComponent } from './error-boundary';
import { type AppRouterActionQueue } from './app-router-instance';
export declare function isExternalURL(url: URL): boolean;
/**
* Given a link href, constructs the URL that should be prefetched. Returns null
* in cases where prefetching should be disabled, like external URLs, or
* during development.
* @param href The href passed to <Link>, router.prefetch(), or similar
* @returns A URL object to prefetch, or null if prefetching should be disabled
*/
export declare function createPrefetchURL(href: string): URL | null;
export declare function createEmptyCacheNode(): CacheNode;
export default function AppRouter({ actionQueue, globalErrorComponentAndStyles: [globalErrorComponent, globalErrorStyles], assetPrefix, }: {
actionQueue: AppRouterActionQueue;
globalErrorComponentAndStyles: [GlobalErrorComponent, React.ReactNode];
assetPrefix: string;
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,536 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createEmptyCacheNode: null,
createPrefetchURL: null,
default: null,
isExternalURL: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createEmptyCacheNode: function() {
return createEmptyCacheNode;
},
createPrefetchURL: function() {
return createPrefetchURL;
},
default: function() {
return AppRouter;
},
isExternalURL: function() {
return isExternalURL;
}
});
const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
const _approutercontextsharedruntime = require("../../shared/lib/app-router-context.shared-runtime");
const _routerreducertypes = require("./router-reducer/router-reducer-types");
const _createhreffromurl = require("./router-reducer/create-href-from-url");
const _hooksclientcontextsharedruntime = require("../../shared/lib/hooks-client-context.shared-runtime");
const _useactionqueue = require("./use-action-queue");
const _errorboundary = /*#__PURE__*/ _interop_require_wildcard._(require("./error-boundary"));
const _isbot = require("../../shared/lib/router/utils/is-bot");
const _addbasepath = require("../add-base-path");
const _approuterannouncer = require("./app-router-announcer");
const _redirectboundary = require("./redirect-boundary");
const _findheadincache = require("./router-reducer/reducers/find-head-in-cache");
const _unresolvedthenable = require("./unresolved-thenable");
const _removebasepath = require("../remove-base-path");
const _hasbasepath = require("../has-base-path");
const _computechangedpath = require("./router-reducer/compute-changed-path");
const _navfailurehandler = require("./nav-failure-handler");
const _approuterinstance = require("./app-router-instance");
const _redirect = require("./redirect");
const _redirecterror = require("./redirect-error");
const _links = require("./links");
const globalMutable = {};
function isExternalURL(url) {
return url.origin !== window.location.origin;
}
function createPrefetchURL(href) {
// Don't prefetch for bots as they don't navigate.
if ((0, _isbot.isBot)(window.navigator.userAgent)) {
return null;
}
let url;
try {
url = new URL((0, _addbasepath.addBasePath)(href), window.location.href);
} catch (_) {
// TODO: Does this need to throw or can we just console.error instead? Does
// anyone rely on this throwing? (Seems unlikely.)
throw Object.defineProperty(new Error("Cannot prefetch '" + href + "' because it cannot be converted to a URL."), "__NEXT_ERROR_CODE", {
value: "E234",
enumerable: false,
configurable: true
});
}
// Don't prefetch during development (improves compilation performance)
if (process.env.NODE_ENV === 'development') {
return null;
}
// External urls can't be prefetched in the same way.
if (isExternalURL(url)) {
return null;
}
return url;
}
function HistoryUpdater(param) {
let { appRouterState } = param;
(0, _react.useInsertionEffect)(()=>{
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
// clear pending URL as navigation is no longer
// in flight
window.next.__pendingUrl = undefined;
}
const { tree, pushRef, canonicalUrl } = appRouterState;
const historyState = {
...pushRef.preserveCustomHistoryState ? window.history.state : {},
// Identifier is shortened intentionally.
// __NA is used to identify if the history entry can be handled by the app-router.
// __N is used to identify if the history entry can be handled by the old router.
__NA: true,
__PRIVATE_NEXTJS_INTERNALS_TREE: tree
};
if (pushRef.pendingPush && // Skip pushing an additional history entry if the canonicalUrl is the same as the current url.
// This mirrors the browser behavior for normal navigation.
(0, _createhreffromurl.createHrefFromUrl)(new URL(window.location.href)) !== canonicalUrl) {
// This intentionally mutates React state, pushRef is overwritten to ensure additional push/replace calls do not trigger an additional history entry.
pushRef.pendingPush = false;
window.history.pushState(historyState, '', canonicalUrl);
} else {
window.history.replaceState(historyState, '', canonicalUrl);
}
}, [
appRouterState
]);
(0, _react.useEffect)(()=>{
// The Next-Url and the base tree may affect the result of a prefetch
// task. Re-prefetch all visible links with the updated values. In most
// cases, this will not result in any new network requests, only if
// the prefetch result actually varies on one of these inputs.
if (process.env.__NEXT_CLIENT_SEGMENT_CACHE) {
(0, _links.pingVisibleLinks)(appRouterState.nextUrl, appRouterState.tree);
}
}, [
appRouterState.nextUrl,
appRouterState.tree
]);
return null;
}
function createEmptyCacheNode() {
return {
lazyData: null,
rsc: null,
prefetchRsc: null,
head: null,
prefetchHead: null,
parallelRoutes: new Map(),
loading: null,
navigatedAt: -1
};
}
function copyNextJsInternalHistoryState(data) {
if (data == null) data = {};
const currentState = window.history.state;
const __NA = currentState == null ? void 0 : currentState.__NA;
if (__NA) {
data.__NA = __NA;
}
const __PRIVATE_NEXTJS_INTERNALS_TREE = currentState == null ? void 0 : currentState.__PRIVATE_NEXTJS_INTERNALS_TREE;
if (__PRIVATE_NEXTJS_INTERNALS_TREE) {
data.__PRIVATE_NEXTJS_INTERNALS_TREE = __PRIVATE_NEXTJS_INTERNALS_TREE;
}
return data;
}
function Head(param) {
let { headCacheNode } = param;
// If this segment has a `prefetchHead`, it's the statically prefetched data.
// We should use that on initial render instead of `head`. Then we'll switch
// to `head` when the dynamic response streams in.
const head = headCacheNode !== null ? headCacheNode.head : null;
const prefetchHead = headCacheNode !== null ? headCacheNode.prefetchHead : null;
// If no prefetch data is available, then we go straight to rendering `head`.
const resolvedPrefetchRsc = prefetchHead !== null ? prefetchHead : head;
// We use `useDeferredValue` to handle switching between the prefetched and
// final values. The second argument is returned on initial render, then it
// re-renders with the first argument.
return (0, _react.useDeferredValue)(head, resolvedPrefetchRsc);
}
/**
* The global router that wraps the application components.
*/ function Router(param) {
let { actionQueue, assetPrefix, globalError } = param;
const state = (0, _useactionqueue.useActionQueue)(actionQueue);
const { canonicalUrl } = state;
// Add memoized pathname/query for useSearchParams and usePathname.
const { searchParams, pathname } = (0, _react.useMemo)(()=>{
const url = new URL(canonicalUrl, typeof window === 'undefined' ? 'http://n' : window.location.href);
return {
// This is turned into a readonly class in `useSearchParams`
searchParams: url.searchParams,
pathname: (0, _hasbasepath.hasBasePath)(url.pathname) ? (0, _removebasepath.removeBasePath)(url.pathname) : url.pathname
};
}, [
canonicalUrl
]);
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { cache, prefetchCache, tree } = state;
// This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes
// eslint-disable-next-line react-hooks/rules-of-hooks
(0, _react.useEffect)(()=>{
// Add `window.nd` for debugging purposes.
// This is not meant for use in applications as concurrent rendering will affect the cache/tree/router.
// @ts-ignore this is for debugging
window.nd = {
router: _approuterinstance.publicAppRouterInstance,
cache,
prefetchCache,
tree
};
}, [
cache,
prefetchCache,
tree
]);
}
(0, _react.useEffect)(()=>{
// If the app is restored from bfcache, it's possible that
// pushRef.mpaNavigation is true, which would mean that any re-render of this component
// would trigger the mpa navigation logic again from the lines below.
// This will restore the router to the initial state in the event that the app is restored from bfcache.
function handlePageShow(event) {
var _window_history_state;
if (!event.persisted || !((_window_history_state = window.history.state) == null ? void 0 : _window_history_state.__PRIVATE_NEXTJS_INTERNALS_TREE)) {
return;
}
// Clear the pendingMpaPath value so that a subsequent MPA navigation to the same URL can be triggered.
// This is necessary because if the browser restored from bfcache, the pendingMpaPath would still be set to the value
// of the last MPA navigation.
globalMutable.pendingMpaPath = undefined;
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_RESTORE,
url: new URL(window.location.href),
tree: window.history.state.__PRIVATE_NEXTJS_INTERNALS_TREE
});
}
window.addEventListener('pageshow', handlePageShow);
return ()=>{
window.removeEventListener('pageshow', handlePageShow);
};
}, []);
(0, _react.useEffect)(()=>{
// Ensure that any redirect errors that bubble up outside of the RedirectBoundary
// are caught and handled by the router.
function handleUnhandledRedirect(event) {
const error = 'reason' in event ? event.reason : event.error;
if ((0, _redirecterror.isRedirectError)(error)) {
event.preventDefault();
const url = (0, _redirect.getURLFromRedirectError)(error);
const redirectType = (0, _redirect.getRedirectTypeFromError)(error);
// TODO: This should access the router methods directly, rather than
// go through the public interface.
if (redirectType === _redirecterror.RedirectType.push) {
_approuterinstance.publicAppRouterInstance.push(url, {});
} else {
_approuterinstance.publicAppRouterInstance.replace(url, {});
}
}
}
window.addEventListener('error', handleUnhandledRedirect);
window.addEventListener('unhandledrejection', handleUnhandledRedirect);
return ()=>{
window.removeEventListener('error', handleUnhandledRedirect);
window.removeEventListener('unhandledrejection', handleUnhandledRedirect);
};
}, []);
// When mpaNavigation flag is set do a hard navigation to the new url.
// Infinitely suspend because we don't actually want to rerender any child
// components with the new URL and any entangled state updates shouldn't
// commit either (eg: useTransition isPending should stay true until the page
// unloads).
//
// This is a side effect in render. Don't try this at home, kids. It's
// probably safe because we know this is a singleton component and it's never
// in <Offscreen>. At least I hope so. (It will run twice in dev strict mode,
// but that's... fine?)
const { pushRef } = state;
if (pushRef.mpaNavigation) {
// if there's a re-render, we don't want to trigger another redirect if one is already in flight to the same URL
if (globalMutable.pendingMpaPath !== canonicalUrl) {
const location = window.location;
if (pushRef.pendingPush) {
location.assign(canonicalUrl);
} else {
location.replace(canonicalUrl);
}
globalMutable.pendingMpaPath = canonicalUrl;
}
// TODO-APP: Should we listen to navigateerror here to catch failed
// navigations somehow? And should we call window.stop() if a SPA navigation
// should interrupt an MPA one?
(0, _react.use)(_unresolvedthenable.unresolvedThenable);
}
(0, _react.useEffect)(()=>{
const originalPushState = window.history.pushState.bind(window.history);
const originalReplaceState = window.history.replaceState.bind(window.history);
// Ensure the canonical URL in the Next.js Router is updated when the URL is changed so that `usePathname` and `useSearchParams` hold the pushed values.
const applyUrlFromHistoryPushReplace = (url)=>{
var _window_history_state;
const href = window.location.href;
const tree = (_window_history_state = window.history.state) == null ? void 0 : _window_history_state.__PRIVATE_NEXTJS_INTERNALS_TREE;
(0, _react.startTransition)(()=>{
(0, _useactionqueue.dispatchAppRouterAction)({
type: _routerreducertypes.ACTION_RESTORE,
url: new URL(url != null ? url : href, href),
tree
});
});
};
/**
* Patch pushState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/ window.history.pushState = function pushState(data, _unused, url) {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if ((data == null ? void 0 : data.__NA) || (data == null ? void 0 : data._N)) {
return originalPushState(data, _unused, url);
}
data = copyNextJsInternalHistoryState(data);
if (url) {
applyUrlFromHistoryPushReplace(url);
}
return originalPushState(data, _unused, url);
};
/**
* Patch replaceState to ensure external changes to the history are reflected in the Next.js Router.
* Ensures Next.js internal history state is copied to the new history entry.
* Ensures usePathname and useSearchParams hold the newly provided url.
*/ window.history.replaceState = function replaceState(data, _unused, url) {
// Avoid a loop when Next.js internals trigger pushState/replaceState
if ((data == null ? void 0 : data.__NA) || (data == null ? void 0 : data._N)) {
return originalReplaceState(data, _unused, url);
}
data = copyNextJsInternalHistoryState(data);
if (url) {
applyUrlFromHistoryPushReplace(url);
}
return originalReplaceState(data, _unused, url);
};
/**
* Handle popstate event, this is used to handle back/forward in the browser.
* By default dispatches ACTION_RESTORE, however if the history entry was not pushed/replaced by app-router it will reload the page.
* That case can happen when the old router injected the history entry.
*/ const onPopState = (event)=>{
if (!event.state) {
// TODO-APP: this case only happens when pushState/replaceState was called outside of Next.js. It should probably reload the page in this case.
return;
}
// This case happens when the history entry was pushed by the `pages` router.
if (!event.state.__NA) {
window.location.reload();
return;
}
// TODO-APP: Ideally the back button should not use startTransition as it should apply the updates synchronously
// Without startTransition works if the cache is there for this path
(0, _react.startTransition)(()=>{
(0, _approuterinstance.dispatchTraverseAction)(window.location.href, event.state.__PRIVATE_NEXTJS_INTERNALS_TREE);
});
};
// Register popstate event to call onPopstate.
window.addEventListener('popstate', onPopState);
return ()=>{
window.history.pushState = originalPushState;
window.history.replaceState = originalReplaceState;
window.removeEventListener('popstate', onPopState);
};
}, []);
const { cache, tree, nextUrl, focusAndScrollRef } = state;
const matchingHead = (0, _react.useMemo)(()=>{
return (0, _findheadincache.findHeadInCache)(cache, tree[1]);
}, [
cache,
tree
]);
// Add memoized pathParams for useParams.
const pathParams = (0, _react.useMemo)(()=>{
return (0, _computechangedpath.getSelectedParams)(tree);
}, [
tree
]);
const layoutRouterContext = (0, _react.useMemo)(()=>{
return {
parentTree: tree,
parentCacheNode: cache,
parentSegmentPath: null,
// Root node always has `url`
// Provided in AppTreeContext to ensure it can be overwritten in layout-router
url: canonicalUrl
};
}, [
tree,
cache,
canonicalUrl
]);
const globalLayoutRouterContext = (0, _react.useMemo)(()=>{
return {
tree,
focusAndScrollRef,
nextUrl
};
}, [
tree,
focusAndScrollRef,
nextUrl
]);
let head;
if (matchingHead !== null) {
// The head is wrapped in an extra component so we can use
// `useDeferredValue` to swap between the prefetched and final versions of
// the head. (This is what LayoutRouter does for segment data, too.)
//
// The `key` is used to remount the component whenever the head moves to
// a different segment.
const [headCacheNode, headKey] = matchingHead;
head = /*#__PURE__*/ (0, _jsxruntime.jsx)(Head, {
headCacheNode: headCacheNode
}, headKey);
} else {
head = null;
}
let content = /*#__PURE__*/ (0, _jsxruntime.jsxs)(_redirectboundary.RedirectBoundary, {
children: [
head,
cache.rsc,
/*#__PURE__*/ (0, _jsxruntime.jsx)(_approuterannouncer.AppRouterAnnouncer, {
tree: tree
})
]
});
if (process.env.NODE_ENV !== 'production') {
// In development, we apply few error boundaries and hot-reloader:
// - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout
// - HotReloader:
// - hot-reload the app when the code changes
// - render dev overlay
// - catch runtime errors and display global-error when necessary
if (typeof window !== 'undefined') {
const { DevRootHTTPAccessFallbackBoundary } = require('./dev-root-http-access-fallback-boundary');
content = /*#__PURE__*/ (0, _jsxruntime.jsx)(DevRootHTTPAccessFallbackBoundary, {
children: content
});
}
const HotReloader = require('./react-dev-overlay/app/hot-reloader-client').default;
content = /*#__PURE__*/ (0, _jsxruntime.jsx)(HotReloader, {
assetPrefix: assetPrefix,
globalError: globalError,
children: content
});
} else {
// In production, we only apply the user-customized global error boundary.
content = /*#__PURE__*/ (0, _jsxruntime.jsx)(_errorboundary.ErrorBoundary, {
errorComponent: globalError[0],
errorStyles: globalError[1],
children: content
});
}
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(HistoryUpdater, {
appRouterState: state
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(RuntimeStyles, {}),
/*#__PURE__*/ (0, _jsxruntime.jsx)(_hooksclientcontextsharedruntime.PathParamsContext.Provider, {
value: pathParams,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_hooksclientcontextsharedruntime.PathnameContext.Provider, {
value: pathname,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_hooksclientcontextsharedruntime.SearchParamsContext.Provider, {
value: searchParams,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_approutercontextsharedruntime.GlobalLayoutRouterContext.Provider, {
value: globalLayoutRouterContext,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_approutercontextsharedruntime.AppRouterContext.Provider, {
value: _approuterinstance.publicAppRouterInstance,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_approutercontextsharedruntime.LayoutRouterContext.Provider, {
value: layoutRouterContext,
children: content
})
})
})
})
})
})
]
});
}
function AppRouter(param) {
let { actionQueue, globalErrorComponentAndStyles: [globalErrorComponent, globalErrorStyles], assetPrefix } = param;
(0, _navfailurehandler.useNavFailureHandler)();
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_errorboundary.ErrorBoundary, {
// At the very top level, use the default GlobalError component as the final fallback.
// When the app router itself fails, which means the framework itself fails, we show the default error.
errorComponent: _errorboundary.default,
children: /*#__PURE__*/ (0, _jsxruntime.jsx)(Router, {
actionQueue: actionQueue,
assetPrefix: assetPrefix,
globalError: [
globalErrorComponent,
globalErrorStyles
]
})
});
}
const runtimeStyles = new Set();
let runtimeStyleChanged = new Set();
globalThis._N_E_STYLE_LOAD = function(href) {
let len = runtimeStyles.size;
runtimeStyles.add(href);
if (runtimeStyles.size !== len) {
runtimeStyleChanged.forEach((cb)=>cb());
}
// TODO figure out how to get a promise here
// But maybe it's not necessary as react would block rendering until it's loaded
return Promise.resolve();
};
function RuntimeStyles() {
const [, forceUpdate] = _react.default.useState(0);
const renderedStylesSize = runtimeStyles.size;
(0, _react.useEffect)(()=>{
const changed = ()=>forceUpdate((c)=>c + 1);
runtimeStyleChanged.add(changed);
if (renderedStylesSize !== runtimeStyles.size) {
changed();
}
return ()=>{
runtimeStyleChanged.delete(changed);
};
}, [
renderedStylesSize,
forceUpdate
]);
const dplId = process.env.NEXT_DEPLOYMENT_ID ? "?dpl=" + process.env.NEXT_DEPLOYMENT_ID : '';
return [
...runtimeStyles
].map((href, i)=>/*#__PURE__*/ (0, _jsxruntime.jsx)("link", {
rel: "stylesheet",
href: "" + href + dplId,
// @ts-ignore
precedence: "next"
}, i));
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=app-router.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function bailoutToClientRendering(reason: string): void | never;

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "bailoutToClientRendering", {
enumerable: true,
get: function() {
return bailoutToClientRendering;
}
});
const _bailouttocsr = require("../../shared/lib/lazy-dynamic/bailout-to-csr");
const _workasyncstorageexternal = require("../../server/app-render/work-async-storage.external");
function bailoutToClientRendering(reason) {
const workStore = _workasyncstorageexternal.workAsyncStorage.getStore();
if (workStore == null ? void 0 : workStore.forceStatic) return;
if (workStore == null ? void 0 : workStore.isStaticGeneration) throw Object.defineProperty(new _bailouttocsr.BailoutToCSRError(reason), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=bailout-to-client-rendering.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/bailout-to-client-rendering.ts"],"sourcesContent":["import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { workAsyncStorage } from '../../server/app-render/work-async-storage.external'\n\nexport function bailoutToClientRendering(reason: string): void | never {\n const workStore = workAsyncStorage.getStore()\n\n if (workStore?.forceStatic) return\n\n if (workStore?.isStaticGeneration) throw new BailoutToCSRError(reason)\n}\n"],"names":["bailoutToClientRendering","reason","workStore","workAsyncStorage","getStore","forceStatic","isStaticGeneration","BailoutToCSRError"],"mappings":";;;;+BAGgBA;;;eAAAA;;;8BAHkB;0CACD;AAE1B,SAASA,yBAAyBC,MAAc;IACrD,MAAMC,YAAYC,0CAAgB,CAACC,QAAQ;IAE3C,IAAIF,6BAAAA,UAAWG,WAAW,EAAE;IAE5B,IAAIH,6BAAAA,UAAWI,kBAAkB,EAAE,MAAM,qBAA6B,CAA7B,IAAIC,+BAAiB,CAACN,SAAtB,qBAAA;eAAA;oBAAA;sBAAA;IAA4B;AACvE"}

View File

@@ -0,0 +1,16 @@
import type { ParsedUrlQuery } from 'querystring';
import type { Params } from '../../server/request/params';
/**
* When the Page is a client component we send the params and searchParams to this client wrapper
* where they are turned into dynamically tracked values before being passed to the actual Page component.
*
* additionally we may send promises representing the params and searchParams. We don't ever use these passed
* values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations.
* It is up to the caller to decide if the promises are needed.
*/
export declare function ClientPageRoot({ Component, searchParams, params, promises, }: {
Component: React.ComponentType<any>;
searchParams: ParsedUrlQuery;
params: Params;
promises?: Array<Promise<any>>;
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,57 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ClientPageRoot", {
enumerable: true,
get: function() {
return ClientPageRoot;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _invarianterror = require("../../shared/lib/invariant-error");
function ClientPageRoot(param) {
let { Component, searchParams, params, // eslint-disable-next-line @typescript-eslint/no-unused-vars
promises } = param;
if (typeof window === 'undefined') {
const { workAsyncStorage } = require('../../server/app-render/work-async-storage.external');
let clientSearchParams;
let clientParams;
// We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering
const store = workAsyncStorage.getStore();
if (!store) {
throw Object.defineProperty(new _invarianterror.InvariantError('Expected workStore to exist when handling searchParams in a client Page.'), "__NEXT_ERROR_CODE", {
value: "E564",
enumerable: false,
configurable: true
});
}
const { createSearchParamsFromClient } = require('../../server/request/search-params');
clientSearchParams = createSearchParamsFromClient(searchParams, store);
const { createParamsFromClient } = require('../../server/request/params');
clientParams = createParamsFromClient(params, store);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
params: clientParams,
searchParams: clientSearchParams
});
} else {
const { createRenderSearchParamsFromClient } = require('../request/search-params.browser');
const clientSearchParams = createRenderSearchParamsFromClient(searchParams);
const { createRenderParamsFromClient } = require('../request/params.browser');
const clientParams = createRenderParamsFromClient(params);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
params: clientParams,
searchParams: clientSearchParams
});
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=client-page.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/client-page.tsx"],"sourcesContent":["'use client'\n\nimport type { ParsedUrlQuery } from 'querystring'\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport type { Params } from '../../server/request/params'\n\n/**\n * When the Page is a client component we send the params and searchParams to this client wrapper\n * where they are turned into dynamically tracked values before being passed to the actual Page component.\n *\n * additionally we may send promises representing the params and searchParams. We don't ever use these passed\n * values but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations.\n * It is up to the caller to decide if the promises are needed.\n */\nexport function ClientPageRoot({\n Component,\n searchParams,\n params,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n promises,\n}: {\n Component: React.ComponentType<any>\n searchParams: ParsedUrlQuery\n params: Params\n promises?: Array<Promise<any>>\n}) {\n if (typeof window === 'undefined') {\n const { workAsyncStorage } =\n require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')\n\n let clientSearchParams: Promise<ParsedUrlQuery>\n let clientParams: Promise<Params>\n // We are going to instrument the searchParams prop with tracking for the\n // appropriate context. We wrap differently in prerendering vs rendering\n const store = workAsyncStorage.getStore()\n if (!store) {\n throw new InvariantError(\n 'Expected workStore to exist when handling searchParams in a client Page.'\n )\n }\n\n const { createSearchParamsFromClient } =\n require('../../server/request/search-params') as typeof import('../../server/request/search-params')\n clientSearchParams = createSearchParamsFromClient(searchParams, store)\n\n const { createParamsFromClient } =\n require('../../server/request/params') as typeof import('../../server/request/params')\n clientParams = createParamsFromClient(params, store)\n\n return <Component params={clientParams} searchParams={clientSearchParams} />\n } else {\n const { createRenderSearchParamsFromClient } =\n require('../request/search-params.browser') as typeof import('../request/search-params.browser')\n const clientSearchParams = createRenderSearchParamsFromClient(searchParams)\n const { createRenderParamsFromClient } =\n require('../request/params.browser') as typeof import('../request/params.browser')\n const clientParams = createRenderParamsFromClient(params)\n\n return <Component params={clientParams} searchParams={clientSearchParams} />\n }\n}\n"],"names":["ClientPageRoot","Component","searchParams","params","promises","window","workAsyncStorage","require","clientSearchParams","clientParams","store","getStore","InvariantError","createSearchParamsFromClient","createParamsFromClient","createRenderSearchParamsFromClient","createRenderParamsFromClient"],"mappings":"AAAA;;;;;+BAegBA;;;eAAAA;;;;gCAZe;AAYxB,SAASA,eAAe,KAW9B;IAX8B,IAAA,EAC7BC,SAAS,EACTC,YAAY,EACZC,MAAM,EACN,6DAA6D;IAC7DC,QAAQ,EAMT,GAX8B;IAY7B,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAM,EAAEC,gBAAgB,EAAE,GACxBC,QAAQ;QAEV,IAAIC;QACJ,IAAIC;QACJ,yEAAyE;QACzE,wEAAwE;QACxE,MAAMC,QAAQJ,iBAAiBK,QAAQ;QACvC,IAAI,CAACD,OAAO;YACV,MAAM,qBAEL,CAFK,IAAIE,8BAAc,CACtB,6EADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,MAAM,EAAEC,4BAA4B,EAAE,GACpCN,QAAQ;QACVC,qBAAqBK,6BAA6BX,cAAcQ;QAEhE,MAAM,EAAEI,sBAAsB,EAAE,GAC9BP,QAAQ;QACVE,eAAeK,uBAAuBX,QAAQO;QAE9C,qBAAO,qBAACT;YAAUE,QAAQM;YAAcP,cAAcM;;IACxD,OAAO;QACL,MAAM,EAAEO,kCAAkC,EAAE,GAC1CR,QAAQ;QACV,MAAMC,qBAAqBO,mCAAmCb;QAC9D,MAAM,EAAEc,4BAA4B,EAAE,GACpCT,QAAQ;QACV,MAAME,eAAeO,6BAA6Bb;QAElD,qBAAO,qBAACF;YAAUE,QAAQM;YAAcP,cAAcM;;IACxD;AACF"}

View File

@@ -0,0 +1,17 @@
import type { Params } from '../../server/request/params';
/**
* When the Page is a client component we send the params to this client wrapper
* where they are turned into dynamically tracked values before being passed to the actual Segment component.
*
* additionally we may send a promise representing params. We don't ever use this passed
* value but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations
* such as when dynamicIO is enabled. It is up to the caller to decide if the promises are needed.
*/
export declare function ClientSegmentRoot({ Component, slots, params, promise, }: {
Component: React.ComponentType<any>;
slots: {
[key: string]: React.ReactNode;
};
params: Params;
promise?: Promise<any>;
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,52 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "ClientSegmentRoot", {
enumerable: true,
get: function() {
return ClientSegmentRoot;
}
});
const _jsxruntime = require("react/jsx-runtime");
const _invarianterror = require("../../shared/lib/invariant-error");
function ClientSegmentRoot(param) {
let { Component, slots, params, // eslint-disable-next-line @typescript-eslint/no-unused-vars
promise } = param;
if (typeof window === 'undefined') {
const { workAsyncStorage } = require('../../server/app-render/work-async-storage.external');
let clientParams;
// We are going to instrument the searchParams prop with tracking for the
// appropriate context. We wrap differently in prerendering vs rendering
const store = workAsyncStorage.getStore();
if (!store) {
throw Object.defineProperty(new _invarianterror.InvariantError('Expected workStore to exist when handling params in a client segment such as a Layout or Template.'), "__NEXT_ERROR_CODE", {
value: "E600",
enumerable: false,
configurable: true
});
}
const { createParamsFromClient } = require('../../server/request/params');
clientParams = createParamsFromClient(params, store);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
...slots,
params: clientParams
});
} else {
const { createRenderParamsFromClient } = require('../request/params.browser');
const clientParams = createRenderParamsFromClient(params);
return /*#__PURE__*/ (0, _jsxruntime.jsx)(Component, {
...slots,
params: clientParams
});
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=client-segment.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/client-segment.tsx"],"sourcesContent":["'use client'\n\nimport { InvariantError } from '../../shared/lib/invariant-error'\n\nimport type { Params } from '../../server/request/params'\n\n/**\n * When the Page is a client component we send the params to this client wrapper\n * where they are turned into dynamically tracked values before being passed to the actual Segment component.\n *\n * additionally we may send a promise representing params. We don't ever use this passed\n * value but it can be necessary for the sender to send a Promise that doesn't resolve in certain situations\n * such as when dynamicIO is enabled. It is up to the caller to decide if the promises are needed.\n */\nexport function ClientSegmentRoot({\n Component,\n slots,\n params,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n promise,\n}: {\n Component: React.ComponentType<any>\n slots: { [key: string]: React.ReactNode }\n params: Params\n promise?: Promise<any>\n}) {\n if (typeof window === 'undefined') {\n const { workAsyncStorage } =\n require('../../server/app-render/work-async-storage.external') as typeof import('../../server/app-render/work-async-storage.external')\n\n let clientParams: Promise<Params>\n // We are going to instrument the searchParams prop with tracking for the\n // appropriate context. We wrap differently in prerendering vs rendering\n const store = workAsyncStorage.getStore()\n if (!store) {\n throw new InvariantError(\n 'Expected workStore to exist when handling params in a client segment such as a Layout or Template.'\n )\n }\n\n const { createParamsFromClient } =\n require('../../server/request/params') as typeof import('../../server/request/params')\n clientParams = createParamsFromClient(params, store)\n\n return <Component {...slots} params={clientParams} />\n } else {\n const { createRenderParamsFromClient } =\n require('../request/params.browser') as typeof import('../request/params.browser')\n const clientParams = createRenderParamsFromClient(params)\n return <Component {...slots} params={clientParams} />\n }\n}\n"],"names":["ClientSegmentRoot","Component","slots","params","promise","window","workAsyncStorage","require","clientParams","store","getStore","InvariantError","createParamsFromClient","createRenderParamsFromClient"],"mappings":"AAAA;;;;;+BAcgBA;;;eAAAA;;;;gCAZe;AAYxB,SAASA,kBAAkB,KAWjC;IAXiC,IAAA,EAChCC,SAAS,EACTC,KAAK,EACLC,MAAM,EACN,6DAA6D;IAC7DC,OAAO,EAMR,GAXiC;IAYhC,IAAI,OAAOC,WAAW,aAAa;QACjC,MAAM,EAAEC,gBAAgB,EAAE,GACxBC,QAAQ;QAEV,IAAIC;QACJ,yEAAyE;QACzE,wEAAwE;QACxE,MAAMC,QAAQH,iBAAiBI,QAAQ;QACvC,IAAI,CAACD,OAAO;YACV,MAAM,qBAEL,CAFK,IAAIE,8BAAc,CACtB,uGADI,qBAAA;uBAAA;4BAAA;8BAAA;YAEN;QACF;QAEA,MAAM,EAAEC,sBAAsB,EAAE,GAC9BL,QAAQ;QACVC,eAAeI,uBAAuBT,QAAQM;QAE9C,qBAAO,qBAACR;YAAW,GAAGC,KAAK;YAAEC,QAAQK;;IACvC,OAAO;QACL,MAAM,EAAEK,4BAA4B,EAAE,GACpCN,QAAQ;QACV,MAAMC,eAAeK,6BAA6BV;QAClD,qBAAO,qBAACF;YAAW,GAAGC,KAAK;YAAEC,QAAQK;;IACvC;AACF"}

View File

@@ -0,0 +1,4 @@
import React from 'react';
export default function DefaultLayout({ children, }: {
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return DefaultLayout;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
function DefaultLayout(param) {
let { children } = param;
return /*#__PURE__*/ (0, _jsxruntime.jsx)("html", {
children: /*#__PURE__*/ (0, _jsxruntime.jsx)("body", {
children: children
})
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=default-layout.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/default-layout.tsx"],"sourcesContent":["import React from 'react'\n\nexport default function DefaultLayout({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n <html>\n <body>{children}</body>\n </html>\n )\n}\n"],"names":["DefaultLayout","children","html","body"],"mappings":";;;;+BAEA;;;eAAwBA;;;;;gEAFN;AAEH,SAASA,cAAc,KAIrC;IAJqC,IAAA,EACpCC,QAAQ,EAGT,GAJqC;IAKpC,qBACE,qBAACC;kBACC,cAAA,qBAACC;sBAAMF;;;AAGb"}

View File

@@ -0,0 +1,5 @@
import React from 'react';
export declare function bailOnRootNotFound(): void;
export declare function DevRootHTTPAccessFallbackBoundary({ children, }: {
children: React.ReactNode;
}): import("react/jsx-runtime").JSX.Element;

View File

@@ -0,0 +1,53 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
DevRootHTTPAccessFallbackBoundary: null,
bailOnRootNotFound: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
DevRootHTTPAccessFallbackBoundary: function() {
return DevRootHTTPAccessFallbackBoundary;
},
bailOnRootNotFound: function() {
return bailOnRootNotFound;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const _errorboundary = require("./http-access-fallback/error-boundary");
function bailOnRootNotFound() {
throw Object.defineProperty(new Error('notFound() is not allowed to use in root layout'), "__NEXT_ERROR_CODE", {
value: "E192",
enumerable: false,
configurable: true
});
}
function NotAllowedRootHTTPFallbackError() {
bailOnRootNotFound();
return null;
}
function DevRootHTTPAccessFallbackBoundary(param) {
let { children } = param;
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_errorboundary.HTTPAccessFallbackBoundary, {
notFound: /*#__PURE__*/ (0, _jsxruntime.jsx)(NotAllowedRootHTTPFallbackError, {}),
children: children
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=dev-root-http-access-fallback-boundary.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/client/components/dev-root-http-access-fallback-boundary.tsx"],"sourcesContent":["'use client'\n\nimport React from 'react'\nimport { HTTPAccessFallbackBoundary } from './http-access-fallback/error-boundary'\n\n// TODO: error on using forbidden and unauthorized in root layout\nexport function bailOnRootNotFound() {\n throw new Error('notFound() is not allowed to use in root layout')\n}\n\nfunction NotAllowedRootHTTPFallbackError() {\n bailOnRootNotFound()\n return null\n}\n\nexport function DevRootHTTPAccessFallbackBoundary({\n children,\n}: {\n children: React.ReactNode\n}) {\n return (\n <HTTPAccessFallbackBoundary notFound={<NotAllowedRootHTTPFallbackError />}>\n {children}\n </HTTPAccessFallbackBoundary>\n )\n}\n"],"names":["DevRootHTTPAccessFallbackBoundary","bailOnRootNotFound","Error","NotAllowedRootHTTPFallbackError","children","HTTPAccessFallbackBoundary","notFound"],"mappings":"AAAA;;;;;;;;;;;;;;;;IAegBA,iCAAiC;eAAjCA;;IATAC,kBAAkB;eAAlBA;;;;;gEAJE;+BACyB;AAGpC,SAASA;IACd,MAAM,qBAA4D,CAA5D,IAAIC,MAAM,oDAAV,qBAAA;eAAA;oBAAA;sBAAA;IAA2D;AACnE;AAEA,SAASC;IACPF;IACA,OAAO;AACT;AAEO,SAASD,kCAAkC,KAIjD;IAJiD,IAAA,EAChDI,QAAQ,EAGT,GAJiD;IAKhD,qBACE,qBAACC,yCAA0B;QAACC,wBAAU,qBAACH;kBACpCC;;AAGP"}

View File

@@ -0,0 +1,46 @@
import React, { type JSX } from 'react';
export type ErrorComponent = React.ComponentType<{
error: Error;
reset?: () => void;
}>;
export interface ErrorBoundaryProps {
children?: React.ReactNode;
errorComponent: ErrorComponent | undefined;
errorStyles?: React.ReactNode | undefined;
errorScripts?: React.ReactNode | undefined;
}
interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {
pathname: string | null;
errorComponent: ErrorComponent;
}
interface ErrorBoundaryHandlerState {
error: Error | null;
previousPathname: string | null;
}
export declare class ErrorBoundaryHandler extends React.Component<ErrorBoundaryHandlerProps, ErrorBoundaryHandlerState> {
constructor(props: ErrorBoundaryHandlerProps);
static getDerivedStateFromError(error: Error): {
error: Error;
};
static getDerivedStateFromProps(props: ErrorBoundaryHandlerProps, state: ErrorBoundaryHandlerState): ErrorBoundaryHandlerState | null;
reset: () => void;
render(): React.ReactNode;
}
export type GlobalErrorComponent = React.ComponentType<{
error: any;
}>;
export declare function GlobalError({ error }: {
error: any;
}): import("react/jsx-runtime").JSX.Element;
export default GlobalError;
/**
* Handles errors through `getDerivedStateFromError`.
* Renders the provided error component and provides a way to `reset` the error boundary state.
*/
/**
* Renders error boundary with the provided "errorComponent" property as the fallback.
* If no "errorComponent" property is provided it renders the children without an error boundary.
*/
export declare function ErrorBoundary({ errorComponent, errorStyles, errorScripts, children, }: ErrorBoundaryProps & {
children: React.ReactNode;
}): JSX.Element;

View File

@@ -0,0 +1,215 @@
'use client';
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
ErrorBoundary: null,
ErrorBoundaryHandler: null,
GlobalError: null,
default: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
ErrorBoundary: function() {
return ErrorBoundary;
},
ErrorBoundaryHandler: function() {
return ErrorBoundaryHandler;
},
GlobalError: function() {
return GlobalError;
},
// Exported so that the import signature in the loaders can be identical to user
// supplied custom global error signatures.
default: function() {
return _default;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const _navigationuntracked = require("./navigation-untracked");
const _isnextroutererror = require("./is-next-router-error");
const _navfailurehandler = require("./nav-failure-handler");
const workAsyncStorage = typeof window === 'undefined' ? require('../../server/app-render/work-async-storage.external').workAsyncStorage : undefined;
const styles = {
error: {
// https://github.com/sindresorhus/modern-normalize/blob/main/modern-normalize.css#L38-L52
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'
},
text: {
fontSize: '14px',
fontWeight: 400,
lineHeight: '28px',
margin: '0 8px'
}
};
// if we are revalidating we want to re-throw the error so the
// function crashes so we can maintain our previous cache
// instead of caching the error page
function HandleISRError(param) {
let { error } = param;
if (workAsyncStorage) {
const store = workAsyncStorage.getStore();
if ((store == null ? void 0 : store.isRevalidate) || (store == null ? void 0 : store.isStaticGeneration)) {
console.error(error);
throw error;
}
}
return null;
}
class ErrorBoundaryHandler extends _react.default.Component {
static getDerivedStateFromError(error) {
if ((0, _isnextroutererror.isNextRouterError)(error)) {
// Re-throw if an expected internal Next.js router error occurs
// this means it should be handled by a different boundary (such as a NotFound boundary in a parent segment)
throw error;
}
return {
error
};
}
static getDerivedStateFromProps(props, state) {
const { error } = state;
// if we encounter an error while
// a navigation is pending we shouldn't render
// the error boundary and instead should fallback
// to a hard navigation to attempt recovering
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
if (error && (0, _navfailurehandler.handleHardNavError)(error)) {
// clear error so we don't render anything
return {
error: null,
previousPathname: props.pathname
};
}
}
/**
* Handles reset of the error boundary when a navigation happens.
* Ensures the error boundary does not stay enabled when navigating to a new page.
* Approach of setState in render is safe as it checks the previous pathname and then overrides
* it as outlined in https://react.dev/reference/react/useState#storing-information-from-previous-renders
*/ if (props.pathname !== state.previousPathname && state.error) {
return {
error: null,
previousPathname: props.pathname
};
}
return {
error: state.error,
previousPathname: props.pathname
};
}
// Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.
render() {
if (this.state.error) {
return /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(HandleISRError, {
error: this.state.error
}),
this.props.errorStyles,
this.props.errorScripts,
/*#__PURE__*/ (0, _jsxruntime.jsx)(this.props.errorComponent, {
error: this.state.error,
reset: this.reset
})
]
});
}
return this.props.children;
}
constructor(props){
super(props), this.reset = ()=>{
this.setState({
error: null
});
};
this.state = {
error: null,
previousPathname: this.props.pathname
};
}
}
function GlobalError(param) {
let { error } = param;
const digest = error == null ? void 0 : error.digest;
return /*#__PURE__*/ (0, _jsxruntime.jsxs)("html", {
id: "__next_error__",
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)("head", {}),
/*#__PURE__*/ (0, _jsxruntime.jsxs)("body", {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsx)(HandleISRError, {
error: error
}),
/*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
style: styles.error,
children: /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
children: [
/*#__PURE__*/ (0, _jsxruntime.jsxs)("h2", {
style: styles.text,
children: [
"Application error: a ",
digest ? 'server' : 'client',
"-side exception has occurred while loading ",
window.location.hostname,
" (see the",
' ',
digest ? 'server logs' : 'browser console',
" for more information)."
]
}),
digest ? /*#__PURE__*/ (0, _jsxruntime.jsx)("p", {
style: styles.text,
children: "Digest: " + digest
}) : null
]
})
})
]
})
]
});
}
const _default = GlobalError;
function ErrorBoundary(param) {
let { errorComponent, errorStyles, errorScripts, children } = param;
// When we're rendering the missing params shell, this will return null. This
// is because we won't be rendering any not found boundaries or error
// boundaries for the missing params shell. When this runs on the client
// (where these errors can occur), we will get the correct pathname.
const pathname = (0, _navigationuntracked.useUntrackedPathname)();
if (errorComponent) {
return /*#__PURE__*/ (0, _jsxruntime.jsx)(ErrorBoundaryHandler, {
pathname: pathname,
errorComponent: errorComponent,
errorStyles: errorStyles,
errorScripts: errorScripts,
children: children
});
}
return /*#__PURE__*/ (0, _jsxruntime.jsx)(_jsxruntime.Fragment, {
children: children
});
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=error-boundary.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export declare function attachHydrationErrorState(error: Error): void;

View File

@@ -0,0 +1,84 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "attachHydrationErrorState", {
enumerable: true,
get: function() {
return attachHydrationErrorState;
}
});
const _ishydrationerror = require("../is-hydration-error");
const _hydrationerrorinfo = require("./hydration-error-info");
function attachHydrationErrorState(error) {
let parsedHydrationErrorState = {};
const isHydrationWarning = (0, _ishydrationerror.testReactHydrationWarning)(error.message);
const isHydrationRuntimeError = (0, _ishydrationerror.isHydrationError)(error);
// If it's not hydration warnings or errors, skip
if (!(isHydrationRuntimeError || isHydrationWarning)) {
return;
}
const reactHydrationDiffSegments = (0, _hydrationerrorinfo.getReactHydrationDiffSegments)(error.message);
// If the reactHydrationDiffSegments exists
// and the diff (reactHydrationDiffSegments[1]) exists
// e.g. the hydration diff log error.
if (reactHydrationDiffSegments) {
const diff = reactHydrationDiffSegments[1];
parsedHydrationErrorState = {
...error.details,
..._hydrationerrorinfo.hydrationErrorState,
// If diff is present in error, we don't need to pick up the console logged warning.
// - if hydration error has diff, and is not hydration diff log, then it's a normal hydration error.
// - if hydration error no diff, then leverage the one from the hydration diff log.
warning: (diff && !isHydrationWarning ? null : _hydrationerrorinfo.hydrationErrorState.warning) || [
(0, _ishydrationerror.getDefaultHydrationErrorMessage)(),
'',
''
],
// When it's hydration diff log, do not show notes section.
// This condition is only for the 1st squashed error.
notes: isHydrationWarning ? '' : reactHydrationDiffSegments[0],
reactOutputComponentDiff: diff
};
// Cache the `reactOutputComponentDiff` into hydrationErrorState.
// This is only required for now when we still squashed the hydration diff log into hydration error.
// Once the all error is logged to dev overlay in order, this will go away.
if (!_hydrationerrorinfo.hydrationErrorState.reactOutputComponentDiff && diff) {
_hydrationerrorinfo.hydrationErrorState.reactOutputComponentDiff = diff;
}
// If it's hydration runtime error that doesn't contain the diff, combine the diff from the cached hydration diff.
if (!diff && isHydrationRuntimeError && _hydrationerrorinfo.hydrationErrorState.reactOutputComponentDiff) {
parsedHydrationErrorState.reactOutputComponentDiff = _hydrationerrorinfo.hydrationErrorState.reactOutputComponentDiff;
}
} else {
// Normal runtime error, where it doesn't contain the hydration diff.
// If there's any extra information in the error message to display,
// append it to the error message details property
if (_hydrationerrorinfo.hydrationErrorState.warning) {
// The patched console.error found hydration errors logged by React
// Append the logged warning to the error message
parsedHydrationErrorState = {
...error.details,
// It contains the warning, component stack, server and client tag names
..._hydrationerrorinfo.hydrationErrorState
};
}
// Consume the cached hydration diff.
// This is only required for now when we still squashed the hydration diff log into hydration error.
// Once the all error is logged to dev overlay in order, this will go away.
if (_hydrationerrorinfo.hydrationErrorState.reactOutputComponentDiff) {
parsedHydrationErrorState.reactOutputComponentDiff = _hydrationerrorinfo.hydrationErrorState.reactOutputComponentDiff;
}
}
// If it's a hydration error, store the hydration error state into the error object
;
error.details = parsedHydrationErrorState;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=attach-hydration-error-state.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
declare const digestSym: unique symbol;
declare const consoleTypeSym: unique symbol;
export type ConsoleError = Error & {
[digestSym]: 'NEXT_CONSOLE_ERROR';
[consoleTypeSym]: 'string' | 'error';
environmentName: string;
};
export declare function createConsoleError(message: string | Error, environmentName?: string | null): ConsoleError;
export declare const isConsoleError: (error: any) => error is ConsoleError;
export declare const getConsoleErrorType: (error: ConsoleError) => "string" | "error";
export {};

View File

@@ -0,0 +1,56 @@
// To distinguish from React error.digest, we use a different symbol here to determine if the error is from console.error or unhandled promise rejection.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
createConsoleError: null,
getConsoleErrorType: null,
isConsoleError: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
createConsoleError: function() {
return createConsoleError;
},
getConsoleErrorType: function() {
return getConsoleErrorType;
},
isConsoleError: function() {
return isConsoleError;
}
});
const digestSym = Symbol.for('next.console.error.digest');
const consoleTypeSym = Symbol.for('next.console.error.type');
function createConsoleError(message, environmentName) {
const error = typeof message === 'string' ? Object.defineProperty(new Error(message), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
}) : message;
error[digestSym] = 'NEXT_CONSOLE_ERROR';
error[consoleTypeSym] = typeof message === 'string' ? 'string' : 'error';
if (environmentName && !error.environmentName) {
error.environmentName = environmentName;
}
return error;
}
const isConsoleError = (error)=>{
return error && error[digestSym] === 'NEXT_CONSOLE_ERROR';
};
const getConsoleErrorType = (error)=>{
return error[consoleTypeSym];
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=console-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/errors/console-error.ts"],"sourcesContent":["// To distinguish from React error.digest, we use a different symbol here to determine if the error is from console.error or unhandled promise rejection.\nconst digestSym = Symbol.for('next.console.error.digest')\nconst consoleTypeSym = Symbol.for('next.console.error.type')\n\n// Represent non Error shape unhandled promise rejections or console.error errors.\n// Those errors will be captured and displayed in Error Overlay.\nexport type ConsoleError = Error & {\n [digestSym]: 'NEXT_CONSOLE_ERROR'\n [consoleTypeSym]: 'string' | 'error'\n environmentName: string\n}\n\nexport function createConsoleError(\n message: string | Error,\n environmentName?: string | null\n): ConsoleError {\n const error = (\n typeof message === 'string' ? new Error(message) : message\n ) as ConsoleError\n error[digestSym] = 'NEXT_CONSOLE_ERROR'\n error[consoleTypeSym] = typeof message === 'string' ? 'string' : 'error'\n\n if (environmentName && !error.environmentName) {\n error.environmentName = environmentName\n }\n\n return error\n}\n\nexport const isConsoleError = (error: any): error is ConsoleError => {\n return error && error[digestSym] === 'NEXT_CONSOLE_ERROR'\n}\n\nexport const getConsoleErrorType = (error: ConsoleError) => {\n return error[consoleTypeSym]\n}\n"],"names":["createConsoleError","getConsoleErrorType","isConsoleError","digestSym","Symbol","for","consoleTypeSym","message","environmentName","error","Error"],"mappings":"AAAA,yJAAyJ;;;;;;;;;;;;;;;;;IAYzIA,kBAAkB;eAAlBA;;IAqBHC,mBAAmB;eAAnBA;;IAJAC,cAAc;eAAdA;;;AA5Bb,MAAMC,YAAYC,OAAOC,GAAG,CAAC;AAC7B,MAAMC,iBAAiBF,OAAOC,GAAG,CAAC;AAU3B,SAASL,mBACdO,OAAuB,EACvBC,eAA+B;IAE/B,MAAMC,QACJ,OAAOF,YAAY,WAAW,qBAAkB,CAAlB,IAAIG,MAAMH,UAAV,qBAAA;eAAA;oBAAA;sBAAA;IAAiB,KAAIA;IAErDE,KAAK,CAACN,UAAU,GAAG;IACnBM,KAAK,CAACH,eAAe,GAAG,OAAOC,YAAY,WAAW,WAAW;IAEjE,IAAIC,mBAAmB,CAACC,MAAMD,eAAe,EAAE;QAC7CC,MAAMD,eAAe,GAAGA;IAC1B;IAEA,OAAOC;AACT;AAEO,MAAMP,iBAAiB,CAACO;IAC7B,OAAOA,SAASA,KAAK,CAACN,UAAU,KAAK;AACvC;AAEO,MAAMF,sBAAsB,CAACQ;IAClC,OAAOA,KAAK,CAACH,eAAe;AAC9B"}

View File

@@ -0,0 +1 @@
export declare function enqueueConsecutiveDedupedError(queue: Array<Error>, error: Error): void;

View File

@@ -0,0 +1,27 @@
// Dedupe the two consecutive errors: If the previous one is same as current one, ignore the current one.
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "enqueueConsecutiveDedupedError", {
enumerable: true,
get: function() {
return enqueueConsecutiveDedupedError;
}
});
function enqueueConsecutiveDedupedError(queue, error) {
const previousError = queue[queue.length - 1];
// Compare the error stack to dedupe the consecutive errors
if (previousError && previousError.stack === error.stack) {
return;
}
queue.push(error);
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=enqueue-client-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/errors/enqueue-client-error.ts"],"sourcesContent":["// Dedupe the two consecutive errors: If the previous one is same as current one, ignore the current one.\nexport function enqueueConsecutiveDedupedError(\n queue: Array<Error>,\n error: Error\n) {\n const previousError = queue[queue.length - 1]\n // Compare the error stack to dedupe the consecutive errors\n if (previousError && previousError.stack === error.stack) {\n return\n }\n queue.push(error)\n}\n"],"names":["enqueueConsecutiveDedupedError","queue","error","previousError","length","stack","push"],"mappings":"AAAA,yGAAyG;;;;;+BACzFA;;;eAAAA;;;AAAT,SAASA,+BACdC,KAAmB,EACnBC,KAAY;IAEZ,MAAMC,gBAAgBF,KAAK,CAACA,MAAMG,MAAM,GAAG,EAAE;IAC7C,2DAA2D;IAC3D,IAAID,iBAAiBA,cAAcE,KAAK,KAAKH,MAAMG,KAAK,EAAE;QACxD;IACF;IACAJ,MAAMK,IAAI,CAACJ;AACb"}

View File

@@ -0,0 +1,19 @@
export type HydrationErrorState = {
warning?: [string, string, string];
serverContent?: string;
clientContent?: string;
notes?: string;
reactOutputComponentDiff?: string;
};
type NullableText = string | null | undefined;
export declare const hydrationErrorState: HydrationErrorState;
export declare const getHydrationWarningType: (message: NullableText) => "tag" | "text" | "text-in-tag";
export declare const getReactHydrationDiffSegments: (msg: NullableText) => (string | undefined)[] | undefined;
/**
* Patch console.error to capture hydration errors.
* If any of the knownHydrationWarnings are logged, store the message and component stack.
* When the hydration runtime error is thrown, the message and component stack are added to the error.
* This results in a more helpful error message in the error overlay.
*/
export declare function storeHydrationErrorStateFromConsoleArgs(...args: any[]): void;
export {};

View File

@@ -0,0 +1,171 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
getHydrationWarningType: null,
getReactHydrationDiffSegments: null,
hydrationErrorState: null,
storeHydrationErrorStateFromConsoleArgs: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
getHydrationWarningType: function() {
return getHydrationWarningType;
},
getReactHydrationDiffSegments: function() {
return getReactHydrationDiffSegments;
},
hydrationErrorState: function() {
return hydrationErrorState;
},
storeHydrationErrorStateFromConsoleArgs: function() {
return storeHydrationErrorStateFromConsoleArgs;
}
});
const _ishydrationerror = require("../is-hydration-error");
const hydrationErrorState = {};
// https://github.com/facebook/react/blob/main/packages/react-dom/src/__tests__/ReactDOMHydrationDiff-test.js used as a reference
const htmlTagsWarnings = new Set([
'Warning: In HTML, %s cannot be a child of <%s>.%s\nThis will cause a hydration error.%s',
'Warning: In HTML, %s cannot be a descendant of <%s>.\nThis will cause a hydration error.%s',
'Warning: In HTML, text nodes cannot be a child of <%s>.\nThis will cause a hydration error.',
"Warning: In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.",
'Warning: Expected server HTML to contain a matching <%s> in <%s>.%s',
'Warning: Did not expect server HTML to contain a <%s> in <%s>.%s'
]);
const textAndTagsMismatchWarnings = new Set([
'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s',
'Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s'
]);
const getHydrationWarningType = (message)=>{
if (typeof message !== 'string') {
// TODO: Doesn't make sense to treat no message as a hydration error message.
// We should bail out somewhere earlier.
return 'text';
}
const normalizedMessage = message.startsWith('Warning: ') ? message : "Warning: " + message;
if (isHtmlTagsWarning(normalizedMessage)) return 'tag';
if (isTextInTagsMismatchWarning(normalizedMessage)) return 'text-in-tag';
return 'text';
};
const isHtmlTagsWarning = (message)=>htmlTagsWarnings.has(message);
const isTextInTagsMismatchWarning = (msg)=>textAndTagsMismatchWarnings.has(msg);
const getReactHydrationDiffSegments = (msg)=>{
if (msg) {
const { message, diff } = (0, _ishydrationerror.getHydrationErrorStackInfo)(msg);
if (message) return [
message,
diff
];
}
return undefined;
};
function storeHydrationErrorStateFromConsoleArgs() {
for(var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++){
args[_key] = arguments[_key];
}
let [msg, firstContent, secondContent, ...rest] = args;
if ((0, _ishydrationerror.testReactHydrationWarning)(msg)) {
// Some hydration warnings has 4 arguments, some has 3, fallback to the last argument
// when the 3rd argument is not the component stack but an empty string
const isReact18 = msg.startsWith('Warning: ');
// For some warnings, there's only 1 argument for template.
// The second argument is the diff or component stack.
if (args.length === 3) {
secondContent = '';
}
const warning = [
// remove the last %s from the message
msg,
firstContent,
secondContent
];
const lastArg = (rest[rest.length - 1] || '').trim();
if (!isReact18) {
hydrationErrorState.reactOutputComponentDiff = lastArg;
} else {
hydrationErrorState.reactOutputComponentDiff = generateHydrationDiffReact18(msg, firstContent, secondContent, lastArg);
}
hydrationErrorState.warning = warning;
hydrationErrorState.serverContent = firstContent;
hydrationErrorState.clientContent = secondContent;
}
}
/*
* Some hydration errors in React 18 does not have the diff in the error message.
* Instead it has the error stack trace which is component stack that we can leverage.
* Will parse the diff from the error stack trace
* e.g.
* Warning: Expected server HTML to contain a matching <div> in <p>.
* at div
* at p
* at div
* at div
* at Page
* output:
* <Page>
* <div>
* <p>
* > <div>
*
*/ function generateHydrationDiffReact18(message, firstContent, secondContent, lastArg) {
const componentStack = lastArg;
let firstIndex = -1;
let secondIndex = -1;
const hydrationWarningType = getHydrationWarningType(message);
// at div\n at Foo\n at Bar (....)\n -> [div, Foo]
const components = componentStack.split('\n')// .reverse()
.map((line, index)=>{
// `<space>at <component> (<location>)` -> `at <component> (<location>)`
line = line.trim();
// extract `<space>at <component>` to `<<component>>`
// e.g. ` at Foo` -> `<Foo>`
const [, component, location] = /at (\w+)( \((.*)\))?/.exec(line) || [];
// If there's no location then it's user-land stack frame
if (!location) {
if (component === firstContent && firstIndex === -1) {
firstIndex = index;
} else if (component === secondContent && secondIndex === -1) {
secondIndex = index;
}
}
return location ? '' : component;
}).filter(Boolean).reverse();
let diff = '';
for(let i = 0; i < components.length; i++){
const component = components[i];
const matchFirstContent = hydrationWarningType === 'tag' && i === components.length - firstIndex - 1;
const matchSecondContent = hydrationWarningType === 'tag' && i === components.length - secondIndex - 1;
if (matchFirstContent || matchSecondContent) {
const spaces = ' '.repeat(Math.max(i * 2 - 2, 0) + 2);
diff += "> " + spaces + "<" + component + ">\n";
} else {
const spaces = ' '.repeat(i * 2 + 2);
diff += spaces + "<" + component + ">\n";
}
}
if (hydrationWarningType === 'text') {
const spaces = ' '.repeat(components.length * 2);
diff += "+ " + spaces + '"' + firstContent + '"\n';
diff += "- " + spaces + '"' + secondContent + '"\n';
} else if (hydrationWarningType === 'text-in-tag') {
const spaces = ' '.repeat(components.length * 2);
diff += "> " + spaces + "<" + secondContent + ">\n";
diff += "> " + spaces + '"' + firstContent + '"\n';
}
return diff;
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=hydration-error-info.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export declare const RuntimeErrorHandler: {
hadRuntimeError: boolean;
};

View File

@@ -0,0 +1,21 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "RuntimeErrorHandler", {
enumerable: true,
get: function() {
return RuntimeErrorHandler;
}
});
const RuntimeErrorHandler = {
hadRuntimeError: false
};
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=runtime-error-handler.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/errors/runtime-error-handler.ts"],"sourcesContent":["export const RuntimeErrorHandler = {\n hadRuntimeError: false,\n}\n"],"names":["RuntimeErrorHandler","hadRuntimeError"],"mappings":";;;;+BAAaA;;;eAAAA;;;AAAN,MAAMA,sBAAsB;IACjCC,iBAAiB;AACnB"}

View File

@@ -0,0 +1 @@
export declare function getReactStitchedError<T = unknown>(err: T): Error | T;

View File

@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "getReactStitchedError", {
enumerable: true,
get: function() {
return getReactStitchedError;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _react = /*#__PURE__*/ _interop_require_default._(require("react"));
const _iserror = /*#__PURE__*/ _interop_require_default._(require("../../../lib/is-error"));
const _errortelemetryutils = require("../../../lib/error-telemetry-utils");
const REACT_ERROR_STACK_BOTTOM_FRAME = 'react-stack-bottom-frame';
const REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = new RegExp("(at " + REACT_ERROR_STACK_BOTTOM_FRAME + " )|(" + REACT_ERROR_STACK_BOTTOM_FRAME + "\\@)");
function getReactStitchedError(err) {
const isErrorInstance = (0, _iserror.default)(err);
const originStack = isErrorInstance ? err.stack || '' : '';
const originMessage = isErrorInstance ? err.message : '';
const stackLines = originStack.split('\n');
const indexOfSplit = stackLines.findIndex((line)=>REACT_ERROR_STACK_BOTTOM_FRAME_REGEX.test(line));
const isOriginalReactError = indexOfSplit >= 0 // has the react-stack-bottom-frame
;
let newStack = isOriginalReactError ? stackLines.slice(0, indexOfSplit).join('\n') : originStack;
const newError = Object.defineProperty(new Error(originMessage), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
// Copy all enumerable properties, e.g. digest
Object.assign(newError, err);
(0, _errortelemetryutils.copyNextErrorCode)(err, newError);
newError.stack = newStack;
// Avoid duplicate overriding stack frames
appendOwnerStack(newError);
return newError;
}
function appendOwnerStack(error) {
if (!_react.default.captureOwnerStack) {
return;
}
let stack = error.stack || '';
// This module is only bundled in development mode so this is safe.
const ownerStack = _react.default.captureOwnerStack();
// Avoid duplicate overriding stack frames
if (ownerStack && stack.endsWith(ownerStack) === false) {
stack += ownerStack;
// Override stack
error.stack = stack;
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=stitched-error.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/client/components/errors/stitched-error.ts"],"sourcesContent":["import React from 'react'\nimport isError from '../../../lib/is-error'\nimport { copyNextErrorCode } from '../../../lib/error-telemetry-utils'\n\nconst REACT_ERROR_STACK_BOTTOM_FRAME = 'react-stack-bottom-frame'\nconst REACT_ERROR_STACK_BOTTOM_FRAME_REGEX = new RegExp(\n `(at ${REACT_ERROR_STACK_BOTTOM_FRAME} )|(${REACT_ERROR_STACK_BOTTOM_FRAME}\\\\@)`\n)\n\nexport function getReactStitchedError<T = unknown>(err: T): Error | T {\n const isErrorInstance = isError(err)\n const originStack = isErrorInstance ? err.stack || '' : ''\n const originMessage = isErrorInstance ? err.message : ''\n const stackLines = originStack.split('\\n')\n const indexOfSplit = stackLines.findIndex((line) =>\n REACT_ERROR_STACK_BOTTOM_FRAME_REGEX.test(line)\n )\n const isOriginalReactError = indexOfSplit >= 0 // has the react-stack-bottom-frame\n let newStack = isOriginalReactError\n ? stackLines.slice(0, indexOfSplit).join('\\n')\n : originStack\n\n const newError = new Error(originMessage)\n // Copy all enumerable properties, e.g. digest\n Object.assign(newError, err)\n copyNextErrorCode(err, newError)\n newError.stack = newStack\n\n // Avoid duplicate overriding stack frames\n appendOwnerStack(newError)\n\n return newError\n}\n\nfunction appendOwnerStack(error: Error) {\n if (!React.captureOwnerStack) {\n return\n }\n let stack = error.stack || ''\n // This module is only bundled in development mode so this is safe.\n const ownerStack = React.captureOwnerStack()\n // Avoid duplicate overriding stack frames\n if (ownerStack && stack.endsWith(ownerStack) === false) {\n stack += ownerStack\n // Override stack\n error.stack = stack\n }\n}\n"],"names":["getReactStitchedError","REACT_ERROR_STACK_BOTTOM_FRAME","REACT_ERROR_STACK_BOTTOM_FRAME_REGEX","RegExp","err","isErrorInstance","isError","originStack","stack","originMessage","message","stackLines","split","indexOfSplit","findIndex","line","test","isOriginalReactError","newStack","slice","join","newError","Error","Object","assign","copyNextErrorCode","appendOwnerStack","error","React","captureOwnerStack","ownerStack","endsWith"],"mappings":";;;;+BASgBA;;;eAAAA;;;;gEATE;kEACE;qCACc;AAElC,MAAMC,iCAAiC;AACvC,MAAMC,uCAAuC,IAAIC,OAC/C,AAAC,SAAMF,iCAA+B,SAAMA,iCAA+B;AAGtE,SAASD,sBAAmCI,GAAM;IACvD,MAAMC,kBAAkBC,IAAAA,gBAAO,EAACF;IAChC,MAAMG,cAAcF,kBAAkBD,IAAII,KAAK,IAAI,KAAK;IACxD,MAAMC,gBAAgBJ,kBAAkBD,IAAIM,OAAO,GAAG;IACtD,MAAMC,aAAaJ,YAAYK,KAAK,CAAC;IACrC,MAAMC,eAAeF,WAAWG,SAAS,CAAC,CAACC,OACzCb,qCAAqCc,IAAI,CAACD;IAE5C,MAAME,uBAAuBJ,gBAAgB,EAAE,mCAAmC;;IAClF,IAAIK,WAAWD,uBACXN,WAAWQ,KAAK,CAAC,GAAGN,cAAcO,IAAI,CAAC,QACvCb;IAEJ,MAAMc,WAAW,qBAAwB,CAAxB,IAAIC,MAAMb,gBAAV,qBAAA;eAAA;oBAAA;sBAAA;IAAuB;IACxC,8CAA8C;IAC9Cc,OAAOC,MAAM,CAACH,UAAUjB;IACxBqB,IAAAA,sCAAiB,EAACrB,KAAKiB;IACvBA,SAASb,KAAK,GAAGU;IAEjB,0CAA0C;IAC1CQ,iBAAiBL;IAEjB,OAAOA;AACT;AAEA,SAASK,iBAAiBC,KAAY;IACpC,IAAI,CAACC,cAAK,CAACC,iBAAiB,EAAE;QAC5B;IACF;IACA,IAAIrB,QAAQmB,MAAMnB,KAAK,IAAI;IAC3B,mEAAmE;IACnE,MAAMsB,aAAaF,cAAK,CAACC,iBAAiB;IAC1C,0CAA0C;IAC1C,IAAIC,cAActB,MAAMuB,QAAQ,CAACD,gBAAgB,OAAO;QACtDtB,SAASsB;QACT,iBAAiB;QACjBH,MAAMnB,KAAK,GAAGA;IAChB;AACF"}

View File

@@ -0,0 +1,5 @@
export type ErrorHandler = (error: Error) => void;
export declare function handleConsoleError(originError: unknown, consoleErrorArgs: any[]): void;
export declare function handleClientError(originError: unknown): void;
export declare function useErrorHandler(handleOnUnhandledError: ErrorHandler, handleOnUnhandledRejection: ErrorHandler): void;
export declare function handleGlobalErrors(): void;

View File

@@ -0,0 +1,158 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
handleClientError: null,
handleConsoleError: null,
handleGlobalErrors: null,
useErrorHandler: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
handleClientError: function() {
return handleClientError;
},
handleConsoleError: function() {
return handleConsoleError;
},
handleGlobalErrors: function() {
return handleGlobalErrors;
},
useErrorHandler: function() {
return useErrorHandler;
}
});
const _interop_require_default = require("@swc/helpers/_/_interop_require_default");
const _react = require("react");
const _attachhydrationerrorstate = require("./attach-hydration-error-state");
const _isnextroutererror = require("../is-next-router-error");
const _hydrationerrorinfo = require("./hydration-error-info");
const _console = require("../../lib/console");
const _iserror = /*#__PURE__*/ _interop_require_default._(require("../../../lib/is-error"));
const _consoleerror = require("./console-error");
const _enqueueclienterror = require("./enqueue-client-error");
const _stitchederror = require("../errors/stitched-error");
const queueMicroTask = globalThis.queueMicrotask || ((cb)=>Promise.resolve().then(cb));
const errorQueue = [];
const errorHandlers = [];
const rejectionQueue = [];
const rejectionHandlers = [];
function handleConsoleError(originError, consoleErrorArgs) {
let error;
const { environmentName } = (0, _console.parseConsoleArgs)(consoleErrorArgs);
if ((0, _iserror.default)(originError)) {
error = (0, _consoleerror.createConsoleError)(originError, environmentName);
} else {
error = (0, _consoleerror.createConsoleError)((0, _console.formatConsoleArgs)(consoleErrorArgs), environmentName);
}
error = (0, _stitchederror.getReactStitchedError)(error);
(0, _hydrationerrorinfo.storeHydrationErrorStateFromConsoleArgs)(...consoleErrorArgs);
(0, _attachhydrationerrorstate.attachHydrationErrorState)(error);
(0, _enqueueclienterror.enqueueConsecutiveDedupedError)(errorQueue, error);
for (const handler of errorHandlers){
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(()=>{
handler(error);
});
}
}
function handleClientError(originError) {
let error;
if ((0, _iserror.default)(originError)) {
error = originError;
} else {
// If it's not an error, format the args into an error
const formattedErrorMessage = originError + '';
error = Object.defineProperty(new Error(formattedErrorMessage), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
error = (0, _stitchederror.getReactStitchedError)(error);
(0, _attachhydrationerrorstate.attachHydrationErrorState)(error);
(0, _enqueueclienterror.enqueueConsecutiveDedupedError)(errorQueue, error);
for (const handler of errorHandlers){
// Delayed the error being passed to React Dev Overlay,
// avoid the state being synchronously updated in the component.
queueMicroTask(()=>{
handler(error);
});
}
}
function useErrorHandler(handleOnUnhandledError, handleOnUnhandledRejection) {
(0, _react.useEffect)(()=>{
// Handle queued errors.
errorQueue.forEach(handleOnUnhandledError);
rejectionQueue.forEach(handleOnUnhandledRejection);
// Listen to new errors.
errorHandlers.push(handleOnUnhandledError);
rejectionHandlers.push(handleOnUnhandledRejection);
return ()=>{
// Remove listeners.
errorHandlers.splice(errorHandlers.indexOf(handleOnUnhandledError), 1);
rejectionHandlers.splice(rejectionHandlers.indexOf(handleOnUnhandledRejection), 1);
// Reset error queues.
errorQueue.splice(0, errorQueue.length);
rejectionQueue.splice(0, rejectionQueue.length);
};
}, [
handleOnUnhandledError,
handleOnUnhandledRejection
]);
}
function onUnhandledError(event) {
if ((0, _isnextroutererror.isNextRouterError)(event.error)) {
event.preventDefault();
return false;
}
// When there's an error property present, we log the error to error overlay.
// Otherwise we don't do anything as it's not logging in the console either.
if (event.error) {
handleClientError(event.error);
}
}
function onUnhandledRejection(ev) {
const reason = ev == null ? void 0 : ev.reason;
if ((0, _isnextroutererror.isNextRouterError)(reason)) {
ev.preventDefault();
return;
}
let error = reason;
if (error && !(0, _iserror.default)(error)) {
error = Object.defineProperty(new Error(error + ''), "__NEXT_ERROR_CODE", {
value: "E394",
enumerable: false,
configurable: true
});
}
rejectionQueue.push(error);
for (const handler of rejectionHandlers){
handler(error);
}
}
function handleGlobalErrors() {
if (typeof window !== 'undefined') {
try {
// Increase the number of stack frames on the client
Error.stackTraceLimit = 50;
} catch (e) {}
window.addEventListener('error', onUnhandledError);
window.addEventListener('unhandledrejection', onUnhandledRejection);
}
}
if ((typeof exports.default === 'function' || (typeof exports.default === 'object' && exports.default !== null)) && typeof exports.default.__esModule === 'undefined') {
Object.defineProperty(exports.default, '__esModule', { value: true });
Object.assign(exports.default, exports);
module.exports = exports.default;
}
//# sourceMappingURL=use-error-handler.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
export default function Forbidden(): import("react/jsx-runtime").JSX.Element;

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