@real-router/core 0.76.0 → 0.77.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/cloneRouter-CtIsIytx.js +2 -0
- package/dist/cjs/cloneRouter-CtIsIytx.js.map +1 -0
- package/dist/cjs/utils.js +1 -1
- package/dist/cjs/utils.js.map +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/cloneRouter-dMhYu82h.mjs +2 -0
- package/dist/esm/cloneRouter-dMhYu82h.mjs.map +1 -0
- package/dist/esm/utils.mjs +1 -1
- package/dist/esm/utils.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/cloneRouter-SIYSVozu.js +0 -2
- package/dist/cjs/cloneRouter-SIYSVozu.js.map +0 -1
- package/dist/esm/cloneRouter-DEU1GjSY.mjs +0 -2
- package/dist/esm/cloneRouter-DEU1GjSY.mjs.map +0 -1
package/dist/cjs/api.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-BX-JArfJ.js"),t=require("./esm-BIeQwCN9.js"),n=require("./cloneRouter-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-BX-JArfJ.js"),t=require("./esm-BIeQwCN9.js"),n=require("./cloneRouter-CtIsIytx.js");let r=require("@real-router/logger");function i(e,t,n){if(t){let n=t===e,i=t.startsWith(`${e}.`);if(n||i){let i=n?``:` (current: "${t}")`;return r.logger.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${i}. Navigate away first.`),!1}}return n&&r.logger.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}function a(e){return e?(r.logger.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const o=Object.freeze({replace:!0,revalidate:!0});function s(t,n,r,i){let a=e=>e===t||e.startsWith(`${t}.`);e.v(n.decoders,a),e.v(n.encoders,a),e.v(n.defaultParams,a),e.v(n.forwardMap,a),e.v(n.forwardFnMap,a),e.v(r,a),e.v(n.forwardMap,e=>a(n.forwardMap[e]));let[o,s]=i.getFactories();for(let e of Object.keys(s))a(e)&&i.clearCanActivate(e,`both`);for(let e of Object.keys(o))a(e)&&i.clearCanDeactivate(e,`both`)}function c(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function l(e,t,n,r){let i={name:e.name,path:e.path};return c(i,t,n,r),e.children&&(i.children=e.children.map(e=>l(e,`${t}.${e.name}`,n,r))),i}function u(e,t,n,r){let i={name:e,path:t};return c(i,e,n,r),Object.freeze(i)}function d(e,t){let n=new Map,r=e.lifecycleNamespace.getFactories(),i=(a,o)=>{for(let s of a){let a=o?`${o}.${s.name}`:s.name;t(a)&&n.set(a,u(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function f(e,t){let n=`${t}.`,r=d(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function p(e,t,n){let r=n.lifecycleNamespace.getFactories(),i=[],a=(e,t)=>{for(let o of e){let e=t?`${t}.${o.name}`:o.name;i.push(u(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function m(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:Object.freeze(n),added:Object.freeze(r)}}function h(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function g(t,n,r){e.a(t,n,r);let i=e.u(t,n,r);t.lifecycleNamespace.preflightHandlerLimit(i.pendingCanActivate.keys(),i.pendingCanDeactivate.keys(),!1),e.i(t,i)}function _(e,t,n){e.setState(t),e.emitTransitionSuccess(t,n,o)}function v(t,n,r,i,a){e.c(n,`addRoute`),e.o(n,``,`addRoute`),e.s(n,``,`addRoute`);let o=e.d(n,t.rootPath,t.matcherOptions);t.lifecycleNamespace.preflightHandlerLimit(o.pendingCanActivate.keys(),o.pendingCanDeactivate.keys(),!0);let s=e.m(o,t.depsStore);if(t.lifecycleNamespace.clearDefinitionGuards(),e.i(t,o,s),a?.(),i!==void 0){let n=r.matchPath(i.path,r.getOptions());if(n)if(n.name===i.name)_(r,{...n,context:i.context,transition:i.transition},i);else{let{toDeactivate:a,toActivate:o}=e.r(n,i);t.lifecycleNamespace.canNavigateTo(a,o,n,i)?_(r,{...n,transition:i.transition},i):r.navigateToNotFound(i.path)}else r.navigateToNotFound(i.path)}}function y(t,n){let r=t.definitions;return e.y(r,n)?(s(n,t.config,t.routeCustomFields,t.lifecycleNamespace),e.p(t,r),!0):!1}function b(e,n){let r=e.matcher.getSegmentsByName(n);if(!r)return;let i=t.i(r.at(-1)),a=e.lifecycleNamespace.getFactories();return l(i,n,e.config,a)}const x=new WeakMap;function S(o){let s=x.get(o);if(s)return s;let c=t.l(o),l=c.routeGetStore(),u=e=>{c.treeChanged.emit(e)},_={add:(t,r)=>{n.i(c.isDisposed),n.a(c.treeChanged.isEmitting);let i=Array.isArray(t)?t:[t],a=r?.parent;if(e.b(i,c.validator),a!==void 0&&c.validator?.routes.validateParentOption(a,l.tree),c.validator?.routes.throwIfInternalRouteInArray(i,`addRoute`),c.validator?.routes.validateAddRouteArgs(i),c.validator?.routes.validateRoutes(i,l,a),g(l,i,a),c.treeChanged.listenerCount()>0){let e=p(i,a,l);u(a===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:a})}},remove:t=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),c.validator?.routes.validateRemoveRouteArgs(t),c.validator?.routes.throwIfInternalRoute(t,`removeRoute`),e.l(t,`removeRoute`),!i(t,c.getStateName(),c.isTransitioning()))return;let a=c.treeChanged.listenerCount()>0?f(l,t):void 0;if(!y(l,t)){r.logger.warn(`router.removeRoute`,`Route "${t}" not found. No changes made.`);return}a!==void 0&&u({op:`remove`,name:t,removedSubtree:a})},update:(t,i)=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),c.validator?.routes.validateUpdateRouteBasicArgs(t,i),c.validator?.routes.throwIfInternalRoute(t,`updateRoute`),e.l(t,`updateRoute`),c.validator?.routes.validateUpdateRoutePropertyTypes(t,i),c.isTransitioning()&&r.logger.error(`router.updateRoute`,`Updating route "${t}" while navigation is in progress. This may cause unexpected behavior.`),c.validator?.routes.validateUpdateRoute(t,i,l),!l.matcher.hasRoute(t))return;let a=l.lifecycleNamespace,o=e.f(l,a,t,i);if(c.treeChanged.listenerCount()>0){let e=h(o);Object.keys(e).length>0&&u({op:`update`,name:t,patch:e})}},clear:()=>{if(n.i(c.isDisposed),n.a(c.treeChanged.isEmitting),!a(c.isTransitioning()))return;let t=c.treeChanged.listenerCount()>0?Object.freeze([...d(l,()=>!0).values()]):void 0;e.h(l),l.lifecycleNamespace.clearAll(),c.clearState(),t!==void 0&&u({op:`clear`,removed:t})},has:e=>(c.validator?.routes.validateRouteName(e,`hasRoute`),l.matcher.hasRoute(e)),get:e=>(c.validator?.routes.validateRouteName(e,`getRoute`),b(l,e)),replace:t=>{n.i(c.isDisposed),n.a(c.treeChanged.isEmitting);let r=Array.isArray(t)?t:[t];if(!a(c.isTransitioning()))return;e.b(r,c.validator),c.validator?.routes.throwIfInternalRouteInArray(r,`replaceRoutes`),c.validator?.routes.validateAddRouteArgs(r),c.validator?.routes.validateRoutes(r,l);let i=o.getState(),s=c.treeChanged.listenerCount()>0?d(l,()=>!0):void 0;v(l,r,c,i,s===void 0?void 0:()=>{let{removed:e,added:t}=m(s,d(l,()=>!0));u({op:`replace`,removed:e,added:t})})},subscribeChanges:e=>c.treeChanged.subscribe(e)};return x.set(o,_),_}function C(e,t,n,r){if(n!==void 0){if(!Object.hasOwn(e.dependencies,t))r?.dependencies.validateDependencyCount(e,`setDependency`);else{let i=e.dependencies[t];i!==n&&!(Number.isNaN(i)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(t,`setDependency`)}e.dependencies[t]=n}}function w(e,t,n){let r=[];for(let i in t)t[i]!==void 0&&(Object.hasOwn(e.dependencies,i)?r.push(i):n?.dependencies.validateDependencyCount(e,`setDependencies`),e.dependencies[i]=t[i]);r.length>0&&n?.dependencies.warnBatchOverwrite(r,`setDependencies`)}function T(e){let r=t.l(e);return{get:e=>{r.validator?.dependencies.validateDependencyName(e,`getDependency`);let t=r.dependenciesGetStore(),n=t.dependencies[e];return r.validator?.dependencies.validateDependencyExists(e,t),n},getAll:()=>({...r.dependenciesGetStore().dependencies}),set:(e,t)=>{n.i(r.isDisposed),r.validator?.dependencies.validateSetDependencyArgs(e,t,`setDependency`),C(r.dependenciesGetStore(),e,t,r.validator)},setAll:e=>{n.i(r.isDisposed);let t=r.dependenciesGetStore();r.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),w(t,e,r.validator)},remove:e=>{n.i(r.isDisposed),r.validator?.dependencies.validateDependencyName(e,`removeDependency`);let t=r.dependenciesGetStore();Object.hasOwn(t.dependencies,e)||r.validator?.dependencies.warnRemoveNonExistent(e),delete t.dependencies[e]},reset:()=>{n.i(r.isDisposed);let e=r.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(r.validator?.dependencies.validateDependencyName(e,`hasDependency`),Object.hasOwn(r.dependenciesGetStore().dependencies,e))}}exports.cloneRouter=n.t,exports.getDependenciesApi=T,exports.getLifecycleApi=n.n,exports.getPluginApi=n.r,exports.getRoutesApi=S;
|
|
2
2
|
//# sourceMappingURL=api.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./Router-BX-JArfJ.js"),t=require("./esm-BIeQwCN9.js");function n(t){if(t())throw new e.n(e.C.ROUTER_DISPOSED)}function r(t){if(t())throw new e.n(e.C.REENTRANT_TREE_MUTATION)}const i=new WeakMap;function a(r){let a=i.get(r);if(a)return a;let o=t.l(r),s={makeState:(e,t,n,r)=>(o.validator?.state.validateMakeStateArgs(e,t,n),o.makeState(e,t,n,r?.params)),buildState:(e,t)=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=o.forwardState(e,t);return o.buildStateResolved(n,r)},forwardState:(e,t)=>(o.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),o.forwardState(e,t)),matchPath:e=>(o.validator?.routes.validateMatchPathArgs(e),o.matchPath(e,o.getOptions())),navigateToState:(e,t)=>(n(o.isDisposed),o.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&o.validator?.navigation.validateNavigationOptions(t,`navigateToState`),o.navigateToState(e,t)),setRootPath:e=>{n(o.isDisposed),o.validator?.routes.validateSetRootPathArgs(e),o.setRootPath(e)},getRootPath:o.getRootPath,addEventListener:(e,t)=>(n(o.isDisposed),o.validator?.eventBus.validateListenerArgs(e,t),o.addEventListener(e,t)),buildNavigationState:(e,t={})=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=o.forwardState(e,t),i=o.buildStateResolved(n,r);if(i)return o.makeState(i.name,i.params,o.buildPath(i.name,i.params),i.meta)},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{n(o.isDisposed),o.validator?.plugins.validateAddInterceptorArgs(e,t);let r=o.interceptors.get(e);r||(r=[],o.interceptors.set(e,r)),r.push(t);let i=!1;return()=>{i||(i=!0,r.splice(r.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:t=>{n(o.isDisposed);let i=Object.keys(t);for(let t of i)if(t in r)throw new e.n(e.C.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${t}" already exists`});for(let e of i)r[e]=t[e];let a={keys:i};o.routerExtensions.push(a);let s=!1;return()=>{if(s)return;s=!0;for(let e of a.keys)delete r[e];let e=o.routerExtensions.indexOf(a);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{n(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:t=>{if(n(o.isDisposed),typeof t!=`string`||t===``)throw TypeError(`[claimContextNamespace] namespace must be a non-empty string, got ${typeof t==`string`?`an empty string`:typeof t}`);if(o.contextClaimRecords.has(t))throw new e.n(e.C.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return o.contextClaimRecords.add(t),{write(e,n){t===`__proto__`?Object.defineProperty(e.context,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e.context[t]=n},release(){o.contextClaimRecords.delete(t)}}}};return i.set(r,s),s}function o(e){let r=t.l(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addActivateGuard`),r.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t)},addDeactivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addDeactivateGuard`),r.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t)},removeActivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}function s(n,r){let i=t.l(n);if(i.isDisposed())throw new e.n(e.C.ROUTER_DISPOSED);i.validator?.dependencies.validateCloneArgs(r);let a=i.routeGetStore(),s=t.r(a.tree),c=a.config,l=a.resolvedForwardMap,u=a.routeCustomFields,{options:d,dependencies:f,pluginFactories:p}=i.getCloneState(),{definition:m,external:h}=a.lifecycleNamespace.getFactoriesByOrigin(),g=new e.t(s,d,{...f,...r}),_=t.l(g),v=_.routeGetStore(),y=v.lifecycleNamespace;e._(v.config,c),Object.assign(v.resolvedForwardMap,l),Object.assign(v.routeCustomFields,u),a.rootPath!==``&&_.setRootPath(a.rootPath);let[b,x]=m,[S,C]=h;for(let[e,t]of Object.entries(b))y.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(x))y.addCanActivate(e,t,!0);let w=o(g);for(let[e,t]of Object.entries(S))w.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(C))w.addActivateGuard(e,t);let T=new Set(_.getCloneState().pluginFactories),E=p.filter(e=>!T.has(e));return E.length>0&&g.usePlugin(...E),g}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
|
+
//# sourceMappingURL=cloneRouter-CtIsIytx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloneRouter-CtIsIytx.js","names":["RouterError","errorCodes","getInternals","RouterError","errorCodes","getInternals","getInternals","RouterError","errorCodes","routeTreeToDefinitions","RouterClass"],"sources":["../../src/api/helpers.ts","../../src/api/getPluginApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.ts"],"sourcesContent":["// packages/core/src/api/helpers.ts\n\nimport { errorCodes } from \"../constants\";\nimport { RouterError } from \"../RouterError\";\n\nexport function throwIfDisposed(isDisposed: () => boolean): void {\n if (isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n}\n\n/**\n * Bans synchronous reentrant route-CRUD: a CRUD op called while a `TREE_CHANGED`\n * emit is on the stack (i.e. from inside a `subscribeChanges` handler) throws\n * `REENTRANT_TREE_MUTATION` BEFORE mutating — the tree stays atomic (#1032).\n * Deferred CRUD (`queueMicrotask` / `await`) runs after the dispatch settles and\n * is unaffected; CRUD from a transition listener is not a TREE_CHANGED dispatch.\n */\nexport function throwIfReentrantTreeMutation(isEmitting: () => boolean): void {\n if (isEmitting()) {\n throw new RouterError(errorCodes.REENTRANT_TREE_MUTATION);\n }\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n State,\n} from \"@real-router/types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\n makeState: (name, params, path, meta) => {\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n return ctx.makeState(\n name,\n params,\n path,\n meta?.params as\n Record<string, Record<string, \"url\" | \"query\">> | undefined,\n );\n },\n buildState: (routeName, routeParams) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"buildState\",\n );\n\n const { name, params } = ctx.forwardState(routeName, routeParams);\n\n return ctx.buildStateResolved(name, params);\n },\n forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState(routeName, routeParams);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\n },\n setRootPath: (rootPath) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateSetRootPathArgs(rootPath);\n\n ctx.setRootPath(rootPath);\n },\n getRootPath: ctx.getRootPath,\n addEventListener: (eventName, cb) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.eventBus.validateListenerArgs(eventName, cb);\n\n return ctx.addEventListener(eventName, cb);\n },\n buildNavigationState: (name, params = {}) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params,\n );\n const routeInfo = ctx.buildStateResolved(resolvedName, resolvedParams);\n\n if (!routeInfo) {\n return;\n }\n\n return ctx.makeState(\n routeInfo.name,\n routeInfo.params,\n ctx.buildPath(routeInfo.name, routeInfo.params),\n routeInfo.meta,\n );\n },\n getOptions: ctx.getOptions,\n getTree: ctx.getTree,\n addInterceptor: (method, fn) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.validator?.plugins.validateAddInterceptorArgs(method, fn);\n let list = ctx.interceptors.get(method);\n\n if (!list) {\n list = [];\n ctx.interceptors.set(method, list);\n }\n\n list.push(fn);\n\n // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n return store.routeCustomFields[name];\n },\n extendRouter: (extensions: Record<string, unknown>) => {\n throwIfDisposed(ctx.isDisposed);\n\n const keys = Object.keys(extensions);\n\n for (const key of keys) {\n if (key in router) {\n throw new RouterError(errorCodes.PLUGIN_CONFLICT, {\n message: `Cannot extend router: property \"${key}\" already exists`,\n });\n }\n }\n\n for (const key of keys) {\n (router as Record<string, unknown>)[key] = extensions[key];\n }\n\n const extensionRecord = { keys };\n\n ctx.routerExtensions.push(extensionRecord);\n\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n\n for (const key of extensionRecord.keys) {\n delete (router as Record<string, unknown>)[key];\n }\n\n const idx = ctx.routerExtensions.indexOf(extensionRecord);\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n // Input-shape guard, symmetric with the other always-on invariant guards\n // (subscribe / start / navigateToNotFound each typeof-check their input).\n // A non-string namespace coerces to an inconsistent key (\"42\"); an empty\n // string is a meaningless namespace (#1191 N4).\n if (typeof namespace !== \"string\" || namespace === \"\") {\n throw new TypeError(\n `[claimContextNamespace] namespace must be a non-empty string, got ${\n typeof namespace === \"string\" ? \"an empty string\" : typeof namespace\n }`,\n );\n }\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n // `state.context[namespace] = value` dispatches into the inherited\n // Object.prototype.__proto__ setter for the literal key \"__proto__\",\n // swapping the prototype instead of creating an own entry — the data\n // then vanishes from Object.keys / serializeRouterState (#1191 N3).\n // Mirror search-params' assignParam: defineProperty writes a genuine\n // own property; normal names keep the plain-assignment fast path.\n if (namespace === \"__proto__\") {\n Object.defineProperty(state.context, namespace, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n state.context[namespace] = value;\n }\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { LifecycleApi } from \"./types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\nexport function getLifecycleApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): LifecycleApi<Dependencies> {\n const ctx = getInternals(router);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycleNamespace = ctx.routeGetStore().lifecycleNamespace!;\n\n return {\n addActivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addActivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addActivateGuard\");\n\n // Handler-limit enforcement lives at the namespace registration choke point\n // (RouteLifecycleNamespace.#registerHandler) so all paths are bounded\n // uniformly — see #961.\n lifecycleNamespace.addCanActivate(name, handler);\n },\n\n addDeactivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addDeactivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addDeactivateGuard\");\n\n lifecycleNamespace.addCanDeactivate(name, handler);\n },\n\n removeActivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeActivateGuard\");\n\n // Inverse of addActivateGuard (external): clears only the external guard;\n // a route-config (definition) canActivate survives (#1171).\n lifecycleNamespace.clearCanActivate(name, \"external\");\n },\n\n removeDeactivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeDeactivateGuard\");\n\n // Inverse of addDeactivateGuard (external): clears only the external guard;\n // a route-config (definition) canDeactivate survives (#1171).\n lifecycleNamespace.clearCanDeactivate(name, \"external\");\n },\n };\n}\n","import { routeTreeToDefinitions } from \"route-tree\";\n\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { assignConfigEntries } from \"../namespaces/RoutesNamespace/helpers\";\nimport { Router as RouterClass } from \"../Router\";\nimport { RouterError } from \"../RouterError\";\nimport { getLifecycleApi } from \"./getLifecycleApi\";\n\nimport type { Route } from \"../types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Build an independent router instance that shares the route tree, options,\n * lifecycle guards, and plugin factories of `router`. The primary use case\n * is **SSR multi-tenancy** — one base router per process, one clone per\n * request.\n *\n * @param router - Source router (must not be disposed).\n * @param dependencies - Optional per-clone overrides merged on top of the\n * base router's dependencies. Always **fresh per call** in the documented\n * SSR pattern: pass per-request state here, never store it in the base.\n *\n * @remarks\n *\n * **Dependency merge — shallow by design.** `base.dependencies` are spread\n * into the clone via `{ ...sourceDeps, ...dependencies }`. Top-level keys\n * are new objects, but **values are shared by reference**: a `Map`, `Set`,\n * class instance, function, or nested plain object stored in\n * `base.dependencies` is the **same instance** in every clone. Mutations\n * in one clone are visible in the base and in every sibling clone.\n *\n * This is intentional. `structuredClone` of dep values is **not** applied\n * because it would:\n * - strip class prototypes (`new DbClient()` → plain object, methods lost)\n * - reject functions and symbols (`DataCloneError`)\n * - fragment singleton pools (one connection pool per request — pool\n * semantics destroyed)\n * - reject circular references\n *\n * **SSR rule of thumb.** Place values in `base.dependencies` according to\n * their lifecycle:\n *\n * - **Singletons / shared services** → `base.dependencies`. Examples: DB\n * client, connection pool, logger, config, feature-flag client. Process-\n * wide pooling depends on sharing these by reference.\n * - **Per-request state** → the `dependencies` override parameter (or\n * `createRequestScope`'s `deps` argument). Examples: `currentUser`,\n * `traceId`, `sessionId`, `abortSignal`. The override is applied last,\n * so it wins over base keys; pass a fresh object per call.\n *\n * Cross-request data leaks are **only possible** when per-request mutable\n * state is incorrectly placed in `base.dependencies`. The override slot is\n * the safe channel.\n *\n * @example\n * ```typescript\n * // Server boot — singletons only\n * const base = createRouter(routes, options, {\n * db: new DbClient(dbUrl),\n * logger,\n * });\n *\n * // Per request — fresh override per call\n * const clone = cloneRouter(base, {\n * currentUser,\n * traceId,\n * });\n * // clone.deps.db === base.deps.db ✓ shared pool (intentional)\n * // clone.deps.currentUser ✓ unique per request\n * ```\n *\n * @see createRequestScope — `@real-router/core/utils` SSR helper that\n * wraps this function and injects `abortSignal` automatically.\n */\nexport function cloneRouter<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n dependencies?: Dependencies,\n): RouterClass<Dependencies> {\n const ctx = getInternals(router);\n\n if (ctx.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n ctx.validator?.dependencies.validateCloneArgs(dependencies);\n\n // Get source store directly\n const sourceStore = ctx.routeGetStore();\n const routes = routeTreeToDefinitions(sourceStore.tree);\n const routeConfig = sourceStore.config;\n const resolvedForwardMap = sourceStore.resolvedForwardMap;\n const routeCustomFields = sourceStore.routeCustomFields;\n\n const {\n options,\n dependencies: sourceDeps,\n pluginFactories,\n } = ctx.getCloneState();\n // Origin-aware factory snapshot — definition guards are re-registered with\n // `isFromDefinition=true` on the clone so `replace()` can still strip them\n // via `clearDefinitionGuards()`. External guards take the public lifecycle\n // API path so they survive `replace()` symmetric with the base.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const sourceLifecycleNamespace = sourceStore.lifecycleNamespace!;\n const { definition: definitionFactories, external: externalFactories } =\n sourceLifecycleNamespace.getFactoriesByOrigin();\n\n const mergedDeps = {\n ...sourceDeps,\n ...dependencies,\n } as Dependencies;\n\n const newRouter = new RouterClass<Dependencies>(\n routes as Route<Dependencies>[],\n options,\n mergedDeps,\n );\n\n const newCtx = getInternals(newRouter);\n const newStore = newCtx.routeGetStore();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const newLifecycleNamespace = newStore.lifecycleNamespace!;\n\n // Copy the source config + store-level maps BEFORE re-registering guards\n // (#1331 review): the definition-guard factories re-executed below must\n // observe the fully-built clone (encoders/decoders/defaultParams/custom\n // fields), mirroring the constructor where flushPendingGuards runs after the\n // store is complete. The five RouteConfig sub-maps go through a single\n // enumeration so a newly added config field is carried over automatically\n // (#965); resolvedForwardMap and routeCustomFields are store-level (not part\n // of RouteConfig) and stay explicit.\n assignConfigEntries(newStore.config, routeConfig);\n Object.assign(newStore.resolvedForwardMap, resolvedForwardMap);\n Object.assign(newStore.routeCustomFields, routeCustomFields);\n\n // #1175: carry the source rootPath. It lives in the store (not options/config),\n // and neither routeTreeToDefinitions nor getCloneState include it — so a clone\n // of a base configured with `setRootPath(\"/app\")` would otherwise build/match\n // under \"\" and 404 every request of a sub-path SSR deployment. setRootPath\n // rebuilds the tree in place with the just-copied config; the rebuild is only\n // paid when a rootPath is actually set, and it runs before the definition-guard\n // factories below so they observe the fully-built clone (rootPath included).\n if (sourceStore.rootPath !== \"\") {\n newCtx.setRootPath(sourceStore.rootPath);\n }\n\n const [definitionDeactivate, definitionActivate] = definitionFactories;\n const [externalDeactivate, externalActivate] = externalFactories;\n\n for (const [name, handler] of Object.entries(definitionDeactivate)) {\n newLifecycleNamespace.addCanDeactivate(name, handler, true);\n }\n\n for (const [name, handler] of Object.entries(definitionActivate)) {\n newLifecycleNamespace.addCanActivate(name, handler, true);\n }\n\n const lifecycle = getLifecycleApi(newRouter);\n\n for (const [name, handler] of Object.entries(externalDeactivate)) {\n lifecycle.addDeactivateGuard(name, handler);\n }\n\n for (const [name, handler] of Object.entries(externalActivate)) {\n lifecycle.addActivateGuard(name, handler);\n }\n\n // Plugin replay runs last and skips factories that a (contract-violating)\n // definition-guard factory already registered on the clone during the\n // re-compilation above — without the filter every clone would double-apply\n // such a plugin: once via the factory, once via this replay (#1331 review).\n const alreadyRegistered = new Set(newCtx.getCloneState().pluginFactories);\n const pluginsToReplay = pluginFactories.filter(\n (factory) => !alreadyRegistered.has(factory),\n );\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `usePlugin(...[])` with an empty spread is a no-op, so entering the block on an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips a real plugin list and is killable.)\n if (pluginsToReplay.length > 0) {\n newRouter.usePlugin(...pluginsToReplay);\n }\n\n return newRouter;\n}\n"],"mappings":"uEAKA,SAAgB,EAAgB,EAAiC,CAC/D,GAAI,EAAW,EACb,MAAM,IAAIA,EAAAA,EAAYC,EAAAA,EAAW,eAAe,CAEpD,CASA,SAAgB,EAA6B,EAAiC,CAC5E,GAAI,EAAW,EACb,MAAM,IAAID,EAAAA,EAAYC,EAAAA,EAAW,uBAAuB,CAE5D,CCFA,MAAM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAAM,IAAI,CAAM,EAE/B,GAAI,EACF,OAAO,EAGT,IAAM,EAAMC,EAAAA,EAAa,CAAM,EACzB,EAAiB,CACrB,WAAY,EAAM,EAAQ,EAAM,KAC9B,EAAI,WAAW,MA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cAAc,CAAC,CAAC,eAAe,EAClE,EAAkB,EAAgB,OACrC,GAAY,CAAC,EAAkB,IAAI,CAAO,CAC7C,EAOA,OAJI,EAAgB,OAAS,GAC3B,EAAU,UAAU,GAAG,CAAe,EAGjC,CACT"}
|
package/dist/cjs/utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./esm-BIeQwCN9.js"),t=require("./cloneRouter-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./esm-BIeQwCN9.js"),t=require("./cloneRouter-CtIsIytx.js");function n(e){return`signal`in e&&typeof e.signal==`object`&&e.signal!==void 0&&typeof e.signal.aborted==`boolean`}function r(e,r,i){let a,o,s;if(n(e))s=e.signal;else{let t=new AbortController,n=()=>{t.abort()};s=t.signal,o=()=>{e.on(`close`,n)},a=()=>{e.removeListener?.(`close`,n)}}let c=t.t(r,{...i,abortSignal:s});o?.();let l=!1,u=()=>l?Promise.resolve():(l=!0,a?.(),c.dispose(),Promise.resolve());return{router:c,signal:s,dispose:u,[Symbol.asyncDispose]:u}}function i(e,t){for(let n of e.children.values())n.children.size===0?t.push(n.fullName):i(n,t)}function a(e){let t=[];return i(e,t),t}async function o(e,n){let r=a(t.r(e).getTree()),i=[];for(let t of r){let r=n?.[t];if(r){let n=await r();for(let r of n)i.push(e.buildPath(t,r))}else i.push(e.buildPath(t,{}))}return i}async function s(t,n,r){let i=r?.deserialize??JSON.parse,a=typeof n==`string`?i(n):n,o=e.l(t),s=o.hydrationState;o.hydrationState=a;try{return await t.start(a.path)}finally{o.hydrationState=s}}function c(e,t){return((t?.serialize??JSON.stringify)(e)??`null`).replaceAll(`<`,String.raw`\u003c`).replaceAll(`>`,String.raw`\u003e`).replaceAll(`&`,String.raw`\u0026`)}function l(e,t){let n=t?.excludeContext,r=e.context;if(n?.length){let t=Object.create(null),i=e.context;for(let[e,r]of Object.entries(i))n.includes(e)||(t[e]=r);r=t}let i={name:e.name,params:e.params,path:e.path,context:r};return t?.serialize?c(i,{serialize:t.serialize}):c(i)}exports.createRequestScope=r,exports.getStaticPaths=o,exports.hydrateRouter=s,exports.serializeRouterState=l,exports.serializeState=c;
|
|
2
2
|
//# sourceMappingURL=utils.js.map
|
package/dist/cjs/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":["cloneRouter","getPluginApi","getInternals"],"sources":["../../src/utils/createRequestScope.ts","../../src/utils/getStaticPaths.ts","../../src/utils/hydrateRouter.ts","../../src/utils/serializeState.ts","../../src/utils/serializeRouterState.ts"],"sourcesContent":["import { cloneRouter } from \"../api/cloneRouter\";\n\nimport type { Router as RouterClass } from \"../Router\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Subset of Node's `http.IncomingMessage` that `createRequestScope` relies on:\n * a `\"close\"` event indicating that the client disconnected (or the response\n * was fully sent) and the standard `removeListener` cleanup hook.\n */\nexport interface IncomingMessageLike {\n on: (event: \"close\", listener: () => void) => unknown;\n removeListener?: (event: \"close\", listener: () => void) => unknown;\n}\n\n/**\n * Web `Request`-shaped object — anything carrying an `AbortSignal`. Web\n * runtimes (Bun, Cloudflare Workers, Vite RSC) surface client-disconnect via\n * `request.signal` directly, so no listener attachment is needed.\n */\nexport interface RequestLike {\n signal: AbortSignal;\n}\n\nexport type RequestScopeSource = IncomingMessageLike | RequestLike;\n\nexport interface RequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> extends AsyncDisposable {\n /**\n * Per-request router clone. Carries `abortSignal` injected into its\n * dependencies — loaders can `getDep(\"abortSignal\")` and pass it to fetch /\n * `withTimeout` for cooperative cancellation when the client disconnects.\n */\n readonly router: RouterClass<Dependencies>;\n\n /**\n * Aborts when the request closes (Node `IncomingMessage`'s `\"close\"` event)\n * or when the upstream Web `Request.signal` aborts.\n */\n readonly signal: AbortSignal;\n\n /**\n * Detach the close listener (if attached to a Node `IncomingMessage`) and\n * dispose the cloned router. Idempotent — safe to call multiple times or in\n * combination with `Symbol.asyncDispose`.\n */\n dispose: () => Promise<void>;\n}\n\nfunction isRequestLike(request: RequestScopeSource): request is RequestLike {\n return (\n \"signal\" in request &&\n typeof (request as Partial<RequestLike>).signal === \"object\" &&\n (request as Partial<RequestLike>).signal !== undefined &&\n typeof request.signal.aborted === \"boolean\"\n );\n}\n\n/**\n * Build a per-request router scope: clones `base`, attaches an `AbortSignal`\n * tied to the request's lifetime, and exposes `dispose()` (plus\n * `Symbol.asyncDispose` for `await using` declarations).\n *\n * Replaces the four-step boilerplate that every server entry repeats:\n *\n * 1. `new AbortController()` per request\n * 2. `req.on(\"close\", () => controller.abort())`\n * 3. `cloneRouter(base, { ...deps, abortSignal: signal })`\n * 4. `try { ... } finally { router.dispose() }`\n *\n * The signal is injected into the router clone under `abortSignal` so existing\n * loaders that read `getDep(\"abortSignal\")` keep working without changes. If\n * `deps` already carries an `abortSignal`, the request-tied signal **wins** (it\n * is spread last) — a caller-supplied `abortSignal` is intentionally overridden,\n * since the scope's purpose is to own the request-lifecycle signal.\n *\n * ## `await using` compatibility\n *\n * The scope implements `Symbol.asyncDispose`, so `await using scope = …` is\n * supported on runtimes that ship the well-known `Symbol.asyncDispose`:\n *\n * - **Node.js 24+** (full support; partial in 20.4–20.17 only for `fs`/`stream`)\n * - **Bun 1.0.23+**, **Deno 1.37+**\n * - **Chrome / Edge 127+**, **Firefox 141+**\n * - **Safari**: not yet supported (irrelevant in practice — this helper is\n * server-side only and never reaches the browser)\n *\n * On Node.js 22 LTS the well-known symbol is unavailable, so `await using`\n * fails. **The bundled SSR examples therefore use the explicit\n * `try/finally` + `await scope.dispose()` form**, which works on every\n * runtime. Use `await using` only when you control the deployment target and\n * know it ships the symbol.\n *\n * @example\n * ```typescript\n * // Explicit dispose — works on Node 18+, all browsers, every CI image\n * export async function render(url: string, req: IncomingMessage) {\n * const scope = createRequestScope(req, baseRouter, { currentUser });\n * try {\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n *\n * // `await using` — Node 24+, Bun, Deno, modern browsers\n * export async function render(url: string, req: IncomingMessage) {\n * await using scope = createRequestScope(req, baseRouter, { currentUser });\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * }\n *\n * // Web runtime (signal already on the request)\n * async function handler(request: Request) {\n * const scope = createRequestScope(request, baseRouter, { db });\n * try {\n * scope.router.usePlugin(rscServerPluginFactory(loaders));\n * return await render(scope.router, request.url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n * ```\n */\nexport function createRequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n request: RequestScopeSource,\n base: Router<Dependencies>,\n deps?: Partial<Dependencies>,\n): RequestScope<Dependencies> {\n let detach: (() => void) | undefined;\n let attach: (() => void) | undefined;\n let signal: AbortSignal;\n\n if (isRequestLike(request)) {\n signal = request.signal;\n } else {\n const controller = new AbortController();\n const onClose = (): void => {\n controller.abort();\n };\n\n signal = controller.signal;\n // Clone-before-attach (#969): defer attaching the \"close\" listener until\n // after cloneRouter succeeds. cloneRouter is synchronous, so no \"close\"\n // macrotask can fire in the gap; and if it throws (e.g. ROUTER_DISPOSED on\n // an already-disposed base) the helper exits without returning a scope\n // handle — so a listener attached here would strand on the request with no\n // way to detach it.\n attach = () => {\n request.on(\"close\", onClose);\n };\n detach = () => {\n request.removeListener?.(\"close\", onClose);\n };\n }\n\n const router = cloneRouter(base, {\n ...deps,\n abortSignal: signal,\n } as Dependencies);\n\n // The clone exists — now it is safe to attach the close listener (Node path\n // only; `attach` is undefined for the Web path).\n attach?.();\n\n let disposed = false;\n\n const dispose = (): Promise<void> => {\n if (disposed) {\n return Promise.resolve();\n }\n\n disposed = true;\n detach?.();\n router.dispose();\n\n return Promise.resolve();\n };\n\n return {\n router,\n signal,\n dispose,\n // eslint-disable-next-line unicorn/no-nonstandard-builtin-properties -- Symbol.asyncDispose is a standard ES2023 well-known symbol (`await using`)\n [Symbol.asyncDispose]: dispose,\n };\n}\n","import { getPluginApi } from \"../api/getPluginApi\";\n\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport type StaticPathEntries = Record<\n string,\n () => Promise<Record<string, string>[]>\n>;\n\nfunction collectLeafRouteNames(node: RouteTree, result: string[]): void {\n for (const child of node.children.values()) {\n if (child.children.size === 0) {\n result.push(child.fullName);\n } else {\n // Accumulate into the shared array rather than\n // `result.push(...getLeafRouteNames(child))`: the spread passes one\n // argument per leaf, and V8 caps spread/apply arguments (~124k on Node 24),\n // so a section with that many static leaf routes threw\n // `RangeError: Maximum call stack size exceeded`. Accumulating also drops\n // the per-subtree intermediate-array allocation.\n collectLeafRouteNames(child, result);\n }\n }\n}\n\nfunction getLeafRouteNames(node: RouteTree): string[] {\n const result: string[] = [];\n\n collectLeafRouteNames(node, result);\n\n return result;\n}\n\nexport async function getStaticPaths<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n entries?: StaticPathEntries,\n): Promise<string[]> {\n const tree = getPluginApi(router).getTree();\n const leafRoutes = getLeafRouteNames(tree);\n const paths: string[] = [];\n\n for (const routeName of leafRoutes) {\n const entryFn = entries?.[routeName];\n\n if (entryFn) {\n const paramSets = await entryFn();\n\n for (const params of paramSets) {\n paths.push(router.buildPath(routeName, params));\n }\n } else {\n paths.push(router.buildPath(routeName, {}));\n }\n }\n\n return paths;\n}\n","import { getInternals } from \"../internals\";\n\nimport type { SerializedRouterState } from \"./serializeRouterState\";\nimport type { Router, State } from \"@real-router/types\";\n\n/**\n * Custom deserializer signature for {@link hydrateRouter} (#606). Compatible\n * with `JSON.parse` (default), `devalue.parse`, `superjson.parse`, or any\n * user-supplied function.\n */\nexport type Deserialize = (json: string) => unknown;\n\nexport interface HydrateRouterOptions {\n /**\n * Custom deserializer (e.g., `devalue.parse` / `superjson.parse`) for\n * matching the `serialize` passed to {@link serializeRouterState}. Defaults\n * to `JSON.parse`. Ignored when `source` is already an object.\n *\n * @default JSON.parse\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n * await hydrateRouter(router, ssrJson, { deserialize: devalue.parse });\n * ```\n */\n deserialize?: Deserialize;\n}\n\n/**\n * Hydrate a fresh router from server-serialized State (#563, #596).\n *\n * Accepts either a JSON string (parsed via `JSON.parse` by default, or\n * `options.deserialize` when provided) or a State-shaped object. Extracts\n * `state.path` and delegates to `router.start(state.path)` — the canonical\n * URL is the source of truth for the router on hydration.\n *\n * The full parsed state (incl. `state.context.<namespace>` payloads) is\n * deposited into a one-shot scratchpad on `RouterInternals.hydrationState`\n * before `start()` is invoked and cleared in the matching `finally`. SSR\n * loader plugins (`@real-router/ssr-data-plugin`,\n * `@real-router/rsc-server-plugin`) read this scratchpad to skip their loader\n * call when the server-resolved namespace value is already present — avoiding\n * the post-hydration loader re-run on first paint.\n *\n * Single-shot semantics: the scratchpad is consumed during the first `start()`\n * triggered by `hydrateRouter` regardless of route mismatch; subsequent\n * `start()` calls run loaders normally.\n *\n * @example\n * ```typescript\n * // Client\n * const router = createAppRouter();\n * router.usePlugin(browserPluginFactory());\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * await hydrateRouter(router, window.__SSR_STATE__, {\n * deserialize: devalue.parse,\n * });\n * ```\n */\nexport async function hydrateRouter(\n router: Router,\n source: string | { path: string },\n options?: HydrateRouterOptions,\n): Promise<State> {\n const deserialize: Deserialize = options?.deserialize ?? JSON.parse;\n const parsed =\n typeof source === \"string\"\n ? (deserialize(source) as SerializedRouterState)\n : (source as SerializedRouterState);\n\n const ctx = getInternals(router);\n const previous = ctx.hydrationState;\n\n ctx.hydrationState = parsed;\n\n try {\n return await router.start(parsed.path);\n } finally {\n ctx.hydrationState = previous;\n }\n}\n","/**\n * Custom serializer signature for {@link serializeState} (#606).\n *\n * Compatible with `JSON.stringify` (default) as well as `devalue.stringify`,\n * `superjson.stringify`, or any user-supplied function that returns a JSON\n * string. The output is run through XSS-safe character escapes regardless\n * of which serializer produced it.\n */\nexport type Serialize = (data: unknown) => string;\n\nexport interface SerializeStateOptions {\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types (Date / Map / Set / RegExp / BigInt). Defaults to\n * `JSON.stringify`. Output is still XSS-escaped.\n *\n * @default JSON.stringify\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization for embedding data in HTML `<script>` tags.\n *\n * Escapes `<`, `>`, and `&` to their Unicode equivalents to prevent\n * injection via `</script>` or HTML entities inside inline scripts.\n *\n * Pass `options.serialize` to use a custom serializer such as `devalue` or\n * `superjson` for non-JSON types (Date/Map/Set/RegExp/BigInt). The serializer\n * must return a string; XSS-escape is applied to its output.\n *\n * @example\n * ```typescript\n * const json = serializeState({ name: \"home\", path: \"/\" });\n * const html = `<script>window.__STATE__=${json}</script>`;\n * ```\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeState(\n * { date: new Date(), tags: new Set([\"a\", \"b\"]) },\n * { serialize: devalue.stringify },\n * );\n * ```\n */\nexport function serializeState(\n data: unknown,\n options?: SerializeStateOptions,\n): string {\n const serialize = options?.serialize ?? JSON.stringify;\n // JSON.stringify returns undefined for top-level `undefined`, Symbol,\n // function, and other non-serializable values (lib.d.ts types it as\n // `string` but the runtime can return undefined). A custom serializer\n // that returns undefined for unsupported input is normalized the same way.\n const serialized = (serialize(data) as string | undefined) ?? \"null\";\n\n return serialized\n .replaceAll(\"<\", String.raw`\\u003c`)\n .replaceAll(\">\", String.raw`\\u003e`)\n .replaceAll(\"&\", String.raw`\\u0026`);\n}\n","import { serializeState } from \"./serializeState\";\n\nimport type { Serialize } from \"./serializeState\";\nimport type { Params, State } from \"@real-router/types\";\n\n/**\n * Parsed shape produced by {@link serializeRouterState} (after `JSON.parse`).\n *\n * Identical to {@link State} minus `transition` (per-navigation `TransitionMeta`\n * is meaningless after hydration; the client builds its own on commit). Used as\n * the input shape for {@link hydrateRouter} and as the type of the one-shot\n * hydration scratchpad consumed by SSR loader plugins.\n */\nexport type SerializedRouterState<P extends Params = Params> = Omit<\n State<P>,\n \"transition\"\n>;\n\nexport interface SerializeRouterStateOptions {\n /**\n * Plugin context namespaces to strip from the serialized output.\n * Use when a plugin populates `state.context.<ns>` with non-JSON-serializable\n * values (e.g., RSC payload: ReactNode trees containing functions/symbols).\n *\n * @default []\n */\n excludeContext?: readonly string[];\n\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types in `state.params` and `state.context.<ns>` payloads\n * (Date / Map / Set / RegExp / BigInt). Defaults to `JSON.stringify`.\n *\n * Pair with the matching `deserialize` on `hydrateRouter` to round-trip the\n * extended types on the client.\n *\n * @default JSON.stringify\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * ```\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization of router State for SSR → client transport (#563).\n *\n * Strips `state.transition` (per-navigation `TransitionMeta` — meaningless after\n * hydration; the client's hydration commit produces its own `transition`).\n * Keeps `name`, `params`, `path`, and `context` (plugin context namespaces are\n * preserved as-is — server's `state.context.data` from `ssr-data-plugin` and\n * any other plugin claims travel to the client untouched).\n *\n * Pass `options.excludeContext` to strip specific namespaces from the output —\n * required for plugins that publish non-JSON-serializable values (e.g., RSC\n * `ReactNode` trees from `@real-router/rsc-server-plugin`).\n *\n * @example\n * ```typescript\n * // Server\n * const state = await router.start(req.url);\n * const html = `<script>window.__SSR_STATE__=${serializeRouterState(state)}</script>`;\n *\n * // Client\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With RSC plugin: strip the \"rsc\" namespace before transport\n * const state = await router.start(url);\n * const json = serializeRouterState(state, { excludeContext: [\"rsc\"] });\n * ```\n *\n * @example\n * ```typescript\n * // Non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * // On the client:\n * await hydrateRouter(router, json, { deserialize: devalue.parse });\n * ```\n */\nexport function serializeRouterState(\n state: State,\n options?: SerializeRouterStateOptions,\n): string {\n const exclude = options?.excludeContext;\n\n let context = state.context;\n\n if (exclude?.length) {\n const filtered: Record<string, unknown> = {};\n const source = state.context;\n\n for (const [key, value] of Object.entries(source)) {\n if (!exclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n context = filtered;\n }\n\n const payload = {\n name: state.name,\n params: state.params,\n path: state.path,\n context,\n };\n\n return options?.serialize\n ? serializeState(payload, { serialize: options.serialize })\n : serializeState(payload);\n}\n"],"mappings":"+IAkDA,SAAS,EAAc,EAAqD,CAC1E,MACE,WAAY,GACZ,OAAQ,EAAiC,QAAW,UACnD,EAAiC,SAAW,IAAA,IAC7C,OAAO,EAAQ,OAAO,SAAY,SAEtC,CAqEA,SAAgB,EAGd,EACA,EACA,EAC4B,CAC5B,IAAI,EACA,EACA,EAEJ,GAAI,EAAc,CAAO,EACvB,EAAS,EAAQ,WACZ,CACL,IAAM,EAAa,IAAI,gBACjB,MAAsB,CAC1B,EAAW,MAAM,CACnB,EAEA,EAAS,EAAW,OAOpB,MAAe,CACb,EAAQ,GAAG,QAAS,CAAO,CAC7B,EACA,MAAe,CACb,EAAQ,iBAAiB,QAAS,CAAO,CAC3C,CACF,CAEA,IAAM,EAASA,EAAAA,EAAY,EAAM,CAC/B,GAAG,EACH,YAAa,CACf,CAAiB,EAIjB,IAAS,EAET,IAAI,EAAW,GAET,MACA,EACK,QAAQ,QAAQ,GAGzB,EAAW,GACX,IAAS,EACT,EAAO,QAAQ,EAER,QAAQ,QAAQ,GAGzB,MAAO,CAC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AAU,GAAS,eAErB,EAAU,EAAM,QAEpB,GAAI,GAAS,OAAQ,CACnB,IAAM,EAAoC,CAAC,EACrC,EAAS,EAAM,QAErB,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EACzC,EAAQ,SAAS,CAAG,IACvB,EAAS,GAAO,GAIpB,EAAU,CACZ,CAEA,IAAM,EAAU,CACd,KAAM,EAAM,KACZ,OAAQ,EAAM,OACd,KAAM,EAAM,KACZ,SACF,EAEA,OAAO,GAAS,UACZ,EAAe,EAAS,CAAE,UAAW,EAAQ,SAAU,CAAC,EACxD,EAAe,CAAO,CAC5B"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":["cloneRouter","getPluginApi","getInternals"],"sources":["../../src/utils/createRequestScope.ts","../../src/utils/getStaticPaths.ts","../../src/utils/hydrateRouter.ts","../../src/utils/serializeState.ts","../../src/utils/serializeRouterState.ts"],"sourcesContent":["import { cloneRouter } from \"../api/cloneRouter\";\n\nimport type { Router as RouterClass } from \"../Router\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Subset of Node's `http.IncomingMessage` that `createRequestScope` relies on:\n * a `\"close\"` event indicating that the client disconnected (or the response\n * was fully sent) and the standard `removeListener` cleanup hook.\n */\nexport interface IncomingMessageLike {\n on: (event: \"close\", listener: () => void) => unknown;\n removeListener?: (event: \"close\", listener: () => void) => unknown;\n}\n\n/**\n * Web `Request`-shaped object — anything carrying an `AbortSignal`. Web\n * runtimes (Bun, Cloudflare Workers, Vite RSC) surface client-disconnect via\n * `request.signal` directly, so no listener attachment is needed.\n */\nexport interface RequestLike {\n signal: AbortSignal;\n}\n\nexport type RequestScopeSource = IncomingMessageLike | RequestLike;\n\nexport interface RequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> extends AsyncDisposable {\n /**\n * Per-request router clone. Carries `abortSignal` injected into its\n * dependencies — loaders can `getDep(\"abortSignal\")` and pass it to fetch /\n * `withTimeout` for cooperative cancellation when the client disconnects.\n */\n readonly router: RouterClass<Dependencies>;\n\n /**\n * Aborts when the request closes (Node `IncomingMessage`'s `\"close\"` event)\n * or when the upstream Web `Request.signal` aborts.\n */\n readonly signal: AbortSignal;\n\n /**\n * Detach the close listener (if attached to a Node `IncomingMessage`) and\n * dispose the cloned router. Idempotent — safe to call multiple times or in\n * combination with `Symbol.asyncDispose`.\n */\n dispose: () => Promise<void>;\n}\n\nfunction isRequestLike(request: RequestScopeSource): request is RequestLike {\n return (\n \"signal\" in request &&\n typeof (request as Partial<RequestLike>).signal === \"object\" &&\n (request as Partial<RequestLike>).signal !== undefined &&\n typeof request.signal.aborted === \"boolean\"\n );\n}\n\n/**\n * Build a per-request router scope: clones `base`, attaches an `AbortSignal`\n * tied to the request's lifetime, and exposes `dispose()` (plus\n * `Symbol.asyncDispose` for `await using` declarations).\n *\n * Replaces the four-step boilerplate that every server entry repeats:\n *\n * 1. `new AbortController()` per request\n * 2. `req.on(\"close\", () => controller.abort())`\n * 3. `cloneRouter(base, { ...deps, abortSignal: signal })`\n * 4. `try { ... } finally { router.dispose() }`\n *\n * The signal is injected into the router clone under `abortSignal` so existing\n * loaders that read `getDep(\"abortSignal\")` keep working without changes. If\n * `deps` already carries an `abortSignal`, the request-tied signal **wins** (it\n * is spread last) — a caller-supplied `abortSignal` is intentionally overridden,\n * since the scope's purpose is to own the request-lifecycle signal.\n *\n * ## `await using` compatibility\n *\n * The scope implements `Symbol.asyncDispose`, so `await using scope = …` is\n * supported on runtimes that ship the well-known `Symbol.asyncDispose`:\n *\n * - **Node.js 24+** (full support; partial in 20.4–20.17 only for `fs`/`stream`)\n * - **Bun 1.0.23+**, **Deno 1.37+**\n * - **Chrome / Edge 127+**, **Firefox 141+**\n * - **Safari**: not yet supported (irrelevant in practice — this helper is\n * server-side only and never reaches the browser)\n *\n * On Node.js 22 LTS the well-known symbol is unavailable, so `await using`\n * fails. **The bundled SSR examples therefore use the explicit\n * `try/finally` + `await scope.dispose()` form**, which works on every\n * runtime. Use `await using` only when you control the deployment target and\n * know it ships the symbol.\n *\n * @example\n * ```typescript\n * // Explicit dispose — works on Node 18+, all browsers, every CI image\n * export async function render(url: string, req: IncomingMessage) {\n * const scope = createRequestScope(req, baseRouter, { currentUser });\n * try {\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n *\n * // `await using` — Node 24+, Bun, Deno, modern browsers\n * export async function render(url: string, req: IncomingMessage) {\n * await using scope = createRequestScope(req, baseRouter, { currentUser });\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * }\n *\n * // Web runtime (signal already on the request)\n * async function handler(request: Request) {\n * const scope = createRequestScope(request, baseRouter, { db });\n * try {\n * scope.router.usePlugin(rscServerPluginFactory(loaders));\n * return await render(scope.router, request.url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n * ```\n */\nexport function createRequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n request: RequestScopeSource,\n base: Router<Dependencies>,\n deps?: Partial<Dependencies>,\n): RequestScope<Dependencies> {\n let detach: (() => void) | undefined;\n let attach: (() => void) | undefined;\n let signal: AbortSignal;\n\n if (isRequestLike(request)) {\n signal = request.signal;\n } else {\n const controller = new AbortController();\n const onClose = (): void => {\n controller.abort();\n };\n\n signal = controller.signal;\n // Clone-before-attach (#969): defer attaching the \"close\" listener until\n // after cloneRouter succeeds. cloneRouter is synchronous, so no \"close\"\n // macrotask can fire in the gap; and if it throws (e.g. ROUTER_DISPOSED on\n // an already-disposed base) the helper exits without returning a scope\n // handle — so a listener attached here would strand on the request with no\n // way to detach it.\n attach = () => {\n request.on(\"close\", onClose);\n };\n detach = () => {\n request.removeListener?.(\"close\", onClose);\n };\n }\n\n const router = cloneRouter(base, {\n ...deps,\n abortSignal: signal,\n } as Dependencies);\n\n // The clone exists — now it is safe to attach the close listener (Node path\n // only; `attach` is undefined for the Web path).\n attach?.();\n\n let disposed = false;\n\n const dispose = (): Promise<void> => {\n if (disposed) {\n return Promise.resolve();\n }\n\n disposed = true;\n detach?.();\n router.dispose();\n\n return Promise.resolve();\n };\n\n return {\n router,\n signal,\n dispose,\n // eslint-disable-next-line unicorn/no-nonstandard-builtin-properties -- Symbol.asyncDispose is a standard ES2023 well-known symbol (`await using`)\n [Symbol.asyncDispose]: dispose,\n };\n}\n","import { getPluginApi } from \"../api/getPluginApi\";\n\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport type StaticPathEntries = Record<\n string,\n () => Promise<Record<string, string>[]>\n>;\n\nfunction collectLeafRouteNames(node: RouteTree, result: string[]): void {\n for (const child of node.children.values()) {\n if (child.children.size === 0) {\n result.push(child.fullName);\n } else {\n // Accumulate into the shared array rather than\n // `result.push(...getLeafRouteNames(child))`: the spread passes one\n // argument per leaf, and V8 caps spread/apply arguments (~124k on Node 24),\n // so a section with that many static leaf routes threw\n // `RangeError: Maximum call stack size exceeded`. Accumulating also drops\n // the per-subtree intermediate-array allocation.\n collectLeafRouteNames(child, result);\n }\n }\n}\n\nfunction getLeafRouteNames(node: RouteTree): string[] {\n const result: string[] = [];\n\n collectLeafRouteNames(node, result);\n\n return result;\n}\n\nexport async function getStaticPaths<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n entries?: StaticPathEntries,\n): Promise<string[]> {\n const tree = getPluginApi(router).getTree();\n const leafRoutes = getLeafRouteNames(tree);\n const paths: string[] = [];\n\n for (const routeName of leafRoutes) {\n const entryFn = entries?.[routeName];\n\n if (entryFn) {\n const paramSets = await entryFn();\n\n for (const params of paramSets) {\n paths.push(router.buildPath(routeName, params));\n }\n } else {\n paths.push(router.buildPath(routeName, {}));\n }\n }\n\n return paths;\n}\n","import { getInternals } from \"../internals\";\n\nimport type { SerializedRouterState } from \"./serializeRouterState\";\nimport type { Router, State } from \"@real-router/types\";\n\n/**\n * Custom deserializer signature for {@link hydrateRouter} (#606). Compatible\n * with `JSON.parse` (default), `devalue.parse`, `superjson.parse`, or any\n * user-supplied function.\n */\nexport type Deserialize = (json: string) => unknown;\n\nexport interface HydrateRouterOptions {\n /**\n * Custom deserializer (e.g., `devalue.parse` / `superjson.parse`) for\n * matching the `serialize` passed to {@link serializeRouterState}. Defaults\n * to `JSON.parse`. Ignored when `source` is already an object.\n *\n * @default JSON.parse\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n * await hydrateRouter(router, ssrJson, { deserialize: devalue.parse });\n * ```\n */\n deserialize?: Deserialize;\n}\n\n/**\n * Hydrate a fresh router from server-serialized State (#563, #596).\n *\n * Accepts either a JSON string (parsed via `JSON.parse` by default, or\n * `options.deserialize` when provided) or a State-shaped object. Extracts\n * `state.path` and delegates to `router.start(state.path)` — the canonical\n * URL is the source of truth for the router on hydration.\n *\n * The full parsed state (incl. `state.context.<namespace>` payloads) is\n * deposited into a one-shot scratchpad on `RouterInternals.hydrationState`\n * before `start()` is invoked and cleared in the matching `finally`. SSR\n * loader plugins (`@real-router/ssr-data-plugin`,\n * `@real-router/rsc-server-plugin`) read this scratchpad to skip their loader\n * call when the server-resolved namespace value is already present — avoiding\n * the post-hydration loader re-run on first paint.\n *\n * Single-shot semantics: the scratchpad is consumed during the first `start()`\n * triggered by `hydrateRouter` regardless of route mismatch; subsequent\n * `start()` calls run loaders normally.\n *\n * @example\n * ```typescript\n * // Client\n * const router = createAppRouter();\n * router.usePlugin(browserPluginFactory());\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * await hydrateRouter(router, window.__SSR_STATE__, {\n * deserialize: devalue.parse,\n * });\n * ```\n */\nexport async function hydrateRouter(\n router: Router,\n source: string | { path: string },\n options?: HydrateRouterOptions,\n): Promise<State> {\n const deserialize: Deserialize = options?.deserialize ?? JSON.parse;\n const parsed =\n typeof source === \"string\"\n ? (deserialize(source) as SerializedRouterState)\n : (source as SerializedRouterState);\n\n const ctx = getInternals(router);\n const previous = ctx.hydrationState;\n\n ctx.hydrationState = parsed;\n\n try {\n return await router.start(parsed.path);\n } finally {\n ctx.hydrationState = previous;\n }\n}\n","/**\n * Custom serializer signature for {@link serializeState} (#606).\n *\n * Compatible with `JSON.stringify` (default) as well as `devalue.stringify`,\n * `superjson.stringify`, or any user-supplied function that returns a JSON\n * string. The output is run through XSS-safe character escapes regardless\n * of which serializer produced it.\n */\nexport type Serialize = (data: unknown) => string;\n\nexport interface SerializeStateOptions {\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types (Date / Map / Set / RegExp / BigInt). Defaults to\n * `JSON.stringify`. Output is still XSS-escaped.\n *\n * @default JSON.stringify\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization for embedding data in HTML `<script>` tags.\n *\n * Escapes `<`, `>`, and `&` to their Unicode equivalents to prevent\n * injection via `</script>` or HTML entities inside inline scripts.\n *\n * Pass `options.serialize` to use a custom serializer such as `devalue` or\n * `superjson` for non-JSON types (Date/Map/Set/RegExp/BigInt). The serializer\n * must return a string; XSS-escape is applied to its output.\n *\n * @example\n * ```typescript\n * const json = serializeState({ name: \"home\", path: \"/\" });\n * const html = `<script>window.__STATE__=${json}</script>`;\n * ```\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeState(\n * { date: new Date(), tags: new Set([\"a\", \"b\"]) },\n * { serialize: devalue.stringify },\n * );\n * ```\n */\nexport function serializeState(\n data: unknown,\n options?: SerializeStateOptions,\n): string {\n const serialize = options?.serialize ?? JSON.stringify;\n // JSON.stringify returns undefined for top-level `undefined`, Symbol,\n // function, and other non-serializable values (lib.d.ts types it as\n // `string` but the runtime can return undefined). A custom serializer\n // that returns undefined for unsupported input is normalized the same way.\n const serialized = (serialize(data) as string | undefined) ?? \"null\";\n\n return serialized\n .replaceAll(\"<\", String.raw`\\u003c`)\n .replaceAll(\">\", String.raw`\\u003e`)\n .replaceAll(\"&\", String.raw`\\u0026`);\n}\n","import { serializeState } from \"./serializeState\";\n\nimport type { Serialize } from \"./serializeState\";\nimport type { Params, State } from \"@real-router/types\";\n\n/**\n * Parsed shape produced by {@link serializeRouterState} (after `JSON.parse`).\n *\n * Identical to {@link State} minus `transition` (per-navigation `TransitionMeta`\n * is meaningless after hydration; the client builds its own on commit). Used as\n * the input shape for {@link hydrateRouter} and as the type of the one-shot\n * hydration scratchpad consumed by SSR loader plugins.\n */\nexport type SerializedRouterState<P extends Params = Params> = Omit<\n State<P>,\n \"transition\"\n>;\n\nexport interface SerializeRouterStateOptions {\n /**\n * Plugin context namespaces to strip from the serialized output.\n * Use when a plugin populates `state.context.<ns>` with non-JSON-serializable\n * values (e.g., RSC payload: ReactNode trees containing functions/symbols).\n *\n * @default []\n */\n excludeContext?: readonly string[];\n\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types in `state.params` and `state.context.<ns>` payloads\n * (Date / Map / Set / RegExp / BigInt). Defaults to `JSON.stringify`.\n *\n * Pair with the matching `deserialize` on `hydrateRouter` to round-trip the\n * extended types on the client.\n *\n * @default JSON.stringify\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * ```\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization of router State for SSR → client transport (#563).\n *\n * Strips `state.transition` (per-navigation `TransitionMeta` — meaningless after\n * hydration; the client's hydration commit produces its own `transition`).\n * Keeps `name`, `params`, `path`, and `context` (plugin context namespaces are\n * preserved as-is — server's `state.context.data` from `ssr-data-plugin` and\n * any other plugin claims travel to the client untouched).\n *\n * Pass `options.excludeContext` to strip specific namespaces from the output —\n * required for plugins that publish non-JSON-serializable values (e.g., RSC\n * `ReactNode` trees from `@real-router/rsc-server-plugin`).\n *\n * @example\n * ```typescript\n * // Server\n * const state = await router.start(req.url);\n * const html = `<script>window.__SSR_STATE__=${serializeRouterState(state)}</script>`;\n *\n * // Client\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With RSC plugin: strip the \"rsc\" namespace before transport\n * const state = await router.start(url);\n * const json = serializeRouterState(state, { excludeContext: [\"rsc\"] });\n * ```\n *\n * @example\n * ```typescript\n * // Non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * // On the client:\n * await hydrateRouter(router, json, { deserialize: devalue.parse });\n * ```\n */\nexport function serializeRouterState(\n state: State,\n options?: SerializeRouterStateOptions,\n): string {\n const exclude = options?.excludeContext;\n\n let context = state.context;\n\n if (exclude?.length) {\n // Null-proto target so a literal \"__proto__\" namespace (a real own key on\n // state.context, e.g. written by claimContextNamespace) is copied as a\n // genuine own entry by the plain assignment below — a `{}` target would\n // instead dispatch into the inherited Object.prototype.__proto__ setter and\n // silently drop the data (#1191, same hazard the write path guards).\n const filtered: Record<string, unknown> = Object.create(null) as Record<\n string,\n unknown\n >;\n const source = state.context;\n\n for (const [key, value] of Object.entries(source)) {\n if (!exclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n context = filtered;\n }\n\n const payload = {\n name: state.name,\n params: state.params,\n path: state.path,\n context,\n };\n\n return options?.serialize\n ? serializeState(payload, { serialize: options.serialize })\n : serializeState(payload);\n}\n"],"mappings":"+IAkDA,SAAS,EAAc,EAAqD,CAC1E,MACE,WAAY,GACZ,OAAQ,EAAiC,QAAW,UACnD,EAAiC,SAAW,IAAA,IAC7C,OAAO,EAAQ,OAAO,SAAY,SAEtC,CAqEA,SAAgB,EAGd,EACA,EACA,EAC4B,CAC5B,IAAI,EACA,EACA,EAEJ,GAAI,EAAc,CAAO,EACvB,EAAS,EAAQ,WACZ,CACL,IAAM,EAAa,IAAI,gBACjB,MAAsB,CAC1B,EAAW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ACF,OAAO,MAAM,EAAO,MAAM,EAAO,IAAI,CACvC,QAAU,CACR,EAAI,eAAiB,CACvB,CACF,CCzCA,SAAgB,EACd,EACA,EACQ,CAQR,QAPkB,GAAS,WAAa,KAAK,UAAA,CAKf,CAAI,GAA4B,OAAA,CAG3D,WAAW,IAAK,OAAO,GAAG,QAAQ,CAAC,CACnC,WAAW,IAAK,OAAO,GAAG,QAAQ,CAAC,CACnC,WAAW,IAAK,OAAO,GAAG,QAAQ,CACvC,CC0BA,SAAgB,EACd,EACA,EACQ,CACR,IAAM,EAAU,GAAS,eAErB,EAAU,EAAM,QAEpB,GAAI,GAAS,OAAQ,CAMnB,IAAM,EAAoC,OAAO,OAAO,IAAI,EAItD,EAAS,EAAM,QAErB,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EACzC,EAAQ,SAAS,CAAG,IACvB,EAAS,GAAO,GAIpB,EAAU,CACZ,CAEA,IAAM,EAAU,CACd,KAAM,EAAM,KACZ,OAAQ,EAAM,OACd,KAAM,EAAM,KACZ,SACF,EAEA,OAAO,GAAS,UACZ,EAAe,EAAS,CAAE,UAAW,EAAQ,SAAU,CAAC,EACxD,EAAe,CAAO,CAC5B"}
|
package/dist/esm/api.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as e,b as t,c as n,d as r,f as i,h as a,i as o,l as s,m as c,o as l,p as u,r as d,s as f,u as p,v as m,y as h}from"./Router-07LbiPS7.mjs";import{i as g,l as _}from"./esm-CLeBo4Hk.mjs";import{a as v,i as y,n as b,r as x,t as S}from"./cloneRouter-
|
|
1
|
+
import{a as e,b as t,c as n,d as r,f as i,h as a,i as o,l as s,m as c,o as l,p as u,r as d,s as f,u as p,v as m,y as h}from"./Router-07LbiPS7.mjs";import{i as g,l as _}from"./esm-CLeBo4Hk.mjs";import{a as v,i as y,n as b,r as x,t as S}from"./cloneRouter-dMhYu82h.mjs";import{logger as C}from"@real-router/logger";function w(e,t,n){if(t){let n=t===e,r=t.startsWith(`${e}.`);if(n||r){let r=n?``:` (current: "${t}")`;return C.warn(`router.removeRoute`,`Cannot remove route "${e}" — it is currently active${r}. Navigate away first.`),!1}}return n&&C.warn(`router.removeRoute`,`Route "${e}" removed while navigation is in progress. This may cause unexpected behavior.`),!0}function T(e){return e?(C.error(`router.clearRoutes`,`Cannot clear routes while navigation is in progress. Wait for navigation to complete.`),!1):!0}const E=Object.freeze({replace:!0,revalidate:!0});function D(e,t,n,r){let i=t=>t===e||t.startsWith(`${e}.`);m(t.decoders,i),m(t.encoders,i),m(t.defaultParams,i),m(t.forwardMap,i),m(t.forwardFnMap,i),m(n,i),m(t.forwardMap,e=>i(t.forwardMap[e]));let[a,o]=r.getFactories();for(let e of Object.keys(o))i(e)&&r.clearCanActivate(e,`both`);for(let e of Object.keys(a))i(e)&&r.clearCanDeactivate(e,`both`)}function O(e,t,n,r){let i=n.forwardFnMap[t],a=n.forwardMap[t];i===void 0?a!==void 0&&(e.forwardTo=a):e.forwardTo=i,t in n.defaultParams&&(e.defaultParams=n.defaultParams[t]),t in n.decoders&&(e.decodeParams=n.decoders[t]),t in n.encoders&&(e.encodeParams=n.encoders[t]);let[o,s]=r;return t in s&&(e.canActivate=s[t]),t in o&&(e.canDeactivate=o[t]),e}function k(e,t,n,r){let i={name:e.name,path:e.path};return O(i,t,n,r),e.children&&(i.children=e.children.map(e=>k(e,`${t}.${e.name}`,n,r))),i}function A(e,t,n,r){let i={name:e,path:t};return O(i,e,n,r),Object.freeze(i)}function j(e,t){let n=new Map,r=e.lifecycleNamespace.getFactories(),i=(a,o)=>{for(let s of a){let a=o?`${o}.${s.name}`:s.name;t(a)&&n.set(a,A(a,s.path,e.config,r)),s.children&&i(s.children,a)}};return i(e.definitions,``),n}function M(e,t){let n=`${t}.`,r=j(e,e=>e===t||e.startsWith(n));return Object.freeze([...r.values()])}function N(e,t,n){let r=n.lifecycleNamespace.getFactories(),i=[],a=(e,t)=>{for(let o of e){let e=t?`${t}.${o.name}`:o.name;i.push(A(e,o.path,n.config,r)),o.children&&a(o.children,e)}};return a(e,t??``),Object.freeze(i)}function P(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:Object.freeze(n),added:Object.freeze(r)}}function F(e){let t={};return e.forwardTo!==void 0&&(t.forwardTo=e.forwardTo),e.defaultParams!==void 0&&(t.defaultParams=e.defaultParams),e.encodeParams!==void 0&&(t.encodeParams=e.encodeParams),e.decodeParams!==void 0&&(t.decodeParams=e.decodeParams),Object.freeze(t)}function I(t,n,r){e(t,n,r);let i=p(t,n,r);t.lifecycleNamespace.preflightHandlerLimit(i.pendingCanActivate.keys(),i.pendingCanDeactivate.keys(),!1),o(t,i)}function L(e,t,n){e.setState(t),e.emitTransitionSuccess(t,n,E)}function R(e,t,i,a,s){n(t,`addRoute`),l(t,``,`addRoute`),f(t,``,`addRoute`);let u=r(t,e.rootPath,e.matcherOptions);e.lifecycleNamespace.preflightHandlerLimit(u.pendingCanActivate.keys(),u.pendingCanDeactivate.keys(),!0);let p=c(u,e.depsStore);if(e.lifecycleNamespace.clearDefinitionGuards(),o(e,u,p),s?.(),a!==void 0){let t=i.matchPath(a.path,i.getOptions());if(t)if(t.name===a.name)L(i,{...t,context:a.context,transition:a.transition},a);else{let{toDeactivate:n,toActivate:r}=d(t,a);e.lifecycleNamespace.canNavigateTo(n,r,t,a)?L(i,{...t,transition:a.transition},a):i.navigateToNotFound(a.path)}else i.navigateToNotFound(a.path)}}function z(e,t){let n=e.definitions;return h(n,t)?(D(t,e.config,e.routeCustomFields,e.lifecycleNamespace),u(e,n),!0):!1}function B(e,t){let n=e.matcher.getSegmentsByName(t);if(!n)return;let r=g(n.at(-1)),i=e.lifecycleNamespace.getFactories();return k(r,t,e.config,i)}const V=new WeakMap;function H(e){let n=V.get(e);if(n)return n;let r=_(e),o=r.routeGetStore(),c=e=>{r.treeChanged.emit(e)},l={add:(e,n)=>{y(r.isDisposed),v(r.treeChanged.isEmitting);let i=Array.isArray(e)?e:[e],a=n?.parent;if(t(i,r.validator),a!==void 0&&r.validator?.routes.validateParentOption(a,o.tree),r.validator?.routes.throwIfInternalRouteInArray(i,`addRoute`),r.validator?.routes.validateAddRouteArgs(i),r.validator?.routes.validateRoutes(i,o,a),I(o,i,a),r.treeChanged.listenerCount()>0){let e=N(i,a,o);c(a===void 0?{op:`add`,added:e}:{op:`add`,added:e,parent:a})}},remove:e=>{if(y(r.isDisposed),v(r.treeChanged.isEmitting),r.validator?.routes.validateRemoveRouteArgs(e),r.validator?.routes.throwIfInternalRoute(e,`removeRoute`),s(e,`removeRoute`),!w(e,r.getStateName(),r.isTransitioning()))return;let t=r.treeChanged.listenerCount()>0?M(o,e):void 0;if(!z(o,e)){C.warn(`router.removeRoute`,`Route "${e}" not found. No changes made.`);return}t!==void 0&&c({op:`remove`,name:e,removedSubtree:t})},update:(e,t)=>{if(y(r.isDisposed),v(r.treeChanged.isEmitting),r.validator?.routes.validateUpdateRouteBasicArgs(e,t),r.validator?.routes.throwIfInternalRoute(e,`updateRoute`),s(e,`updateRoute`),r.validator?.routes.validateUpdateRoutePropertyTypes(e,t),r.isTransitioning()&&C.error(`router.updateRoute`,`Updating route "${e}" while navigation is in progress. This may cause unexpected behavior.`),r.validator?.routes.validateUpdateRoute(e,t,o),!o.matcher.hasRoute(e))return;let n=o.lifecycleNamespace,a=i(o,n,e,t);if(r.treeChanged.listenerCount()>0){let t=F(a);Object.keys(t).length>0&&c({op:`update`,name:e,patch:t})}},clear:()=>{if(y(r.isDisposed),v(r.treeChanged.isEmitting),!T(r.isTransitioning()))return;let e=r.treeChanged.listenerCount()>0?Object.freeze([...j(o,()=>!0).values()]):void 0;a(o),o.lifecycleNamespace.clearAll(),r.clearState(),e!==void 0&&c({op:`clear`,removed:e})},has:e=>(r.validator?.routes.validateRouteName(e,`hasRoute`),o.matcher.hasRoute(e)),get:e=>(r.validator?.routes.validateRouteName(e,`getRoute`),B(o,e)),replace:n=>{y(r.isDisposed),v(r.treeChanged.isEmitting);let i=Array.isArray(n)?n:[n];if(!T(r.isTransitioning()))return;t(i,r.validator),r.validator?.routes.throwIfInternalRouteInArray(i,`replaceRoutes`),r.validator?.routes.validateAddRouteArgs(i),r.validator?.routes.validateRoutes(i,o);let a=e.getState(),s=r.treeChanged.listenerCount()>0?j(o,()=>!0):void 0;R(o,i,r,a,s===void 0?void 0:()=>{let{removed:e,added:t}=P(s,j(o,()=>!0));c({op:`replace`,removed:e,added:t})})},subscribeChanges:e=>r.treeChanged.subscribe(e)};return V.set(e,l),l}function U(e,t,n,r){if(n!==void 0){if(!Object.hasOwn(e.dependencies,t))r?.dependencies.validateDependencyCount(e,`setDependency`);else{let i=e.dependencies[t];i!==n&&!(Number.isNaN(i)&&Number.isNaN(n))&&r?.dependencies.warnOverwrite(t,`setDependency`)}e.dependencies[t]=n}}function W(e,t,n){let r=[];for(let i in t)t[i]!==void 0&&(Object.hasOwn(e.dependencies,i)?r.push(i):n?.dependencies.validateDependencyCount(e,`setDependencies`),e.dependencies[i]=t[i]);r.length>0&&n?.dependencies.warnBatchOverwrite(r,`setDependencies`)}function G(e){let t=_(e);return{get:e=>{t.validator?.dependencies.validateDependencyName(e,`getDependency`);let n=t.dependenciesGetStore(),r=n.dependencies[e];return t.validator?.dependencies.validateDependencyExists(e,n),r},getAll:()=>({...t.dependenciesGetStore().dependencies}),set:(e,n)=>{y(t.isDisposed),t.validator?.dependencies.validateSetDependencyArgs(e,n,`setDependency`),U(t.dependenciesGetStore(),e,n,t.validator)},setAll:e=>{y(t.isDisposed);let n=t.dependenciesGetStore();t.validator?.dependencies.validateDependenciesObject(e,`setDependencies`),W(n,e,t.validator)},remove:e=>{y(t.isDisposed),t.validator?.dependencies.validateDependencyName(e,`removeDependency`);let n=t.dependenciesGetStore();Object.hasOwn(n.dependencies,e)||t.validator?.dependencies.warnRemoveNonExistent(e),delete n.dependencies[e]},reset:()=>{y(t.isDisposed);let e=t.dependenciesGetStore();e.dependencies=Object.create(null)},has:e=>(t.validator?.dependencies.validateDependencyName(e,`hasDependency`),Object.hasOwn(t.dependenciesGetStore().dependencies,e))}}export{S as cloneRouter,G as getDependenciesApi,b as getLifecycleApi,x as getPluginApi,H as getRoutesApi};
|
|
2
2
|
//# sourceMappingURL=api.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{C as e,_ as t,n,t as r}from"./Router-07LbiPS7.mjs";import{l as i,r as a}from"./esm-CLeBo4Hk.mjs";function o(t){if(t())throw new n(e.ROUTER_DISPOSED)}function s(t){if(t())throw new n(e.REENTRANT_TREE_MUTATION)}const c=new WeakMap;function l(t){let r=c.get(t);if(r)return r;let a=i(t),s={makeState:(e,t,n,r)=>(a.validator?.state.validateMakeStateArgs(e,t,n),a.makeState(e,t,n,r?.params)),buildState:(e,t)=>{a.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=a.forwardState(e,t);return a.buildStateResolved(n,r)},forwardState:(e,t)=>(a.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),a.forwardState(e,t)),matchPath:e=>(a.validator?.routes.validateMatchPathArgs(e),a.matchPath(e,a.getOptions())),navigateToState:(e,t)=>(o(a.isDisposed),a.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&a.validator?.navigation.validateNavigationOptions(t,`navigateToState`),a.navigateToState(e,t)),setRootPath:e=>{o(a.isDisposed),a.validator?.routes.validateSetRootPathArgs(e),a.setRootPath(e)},getRootPath:a.getRootPath,addEventListener:(e,t)=>(o(a.isDisposed),a.validator?.eventBus.validateListenerArgs(e,t),a.addEventListener(e,t)),buildNavigationState:(e,t={})=>{a.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=a.forwardState(e,t),i=a.buildStateResolved(n,r);if(i)return a.makeState(i.name,i.params,a.buildPath(i.name,i.params),i.meta)},getOptions:a.getOptions,getTree:a.getTree,addInterceptor:(e,t)=>{o(a.isDisposed),a.validator?.plugins.validateAddInterceptorArgs(e,t);let n=a.interceptors.get(e);n||(n=[],a.interceptors.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=a.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:r=>{o(a.isDisposed);let i=Object.keys(r);for(let r of i)if(r in t)throw new n(e.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${r}" already exists`});for(let e of i)t[e]=r[e];let s={keys:i};a.routerExtensions.push(s);let c=!1;return()=>{if(c)return;c=!0;for(let e of s.keys)delete t[e];let e=a.routerExtensions.indexOf(s);e!==-1&&a.routerExtensions.splice(e,1)}},emitTransitionError:e=>{o(a.isDisposed),a.emitTransitionError(e)},claimContextNamespace:t=>{if(o(a.isDisposed),typeof t!=`string`||t===``)throw TypeError(`[claimContextNamespace] namespace must be a non-empty string, got ${typeof t==`string`?`an empty string`:typeof t}`);if(a.contextClaimRecords.has(t))throw new n(e.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return a.contextClaimRecords.add(t),{write(e,n){t===`__proto__`?Object.defineProperty(e.context,t,{value:n,writable:!0,enumerable:!0,configurable:!0}):e.context[t]=n},release(){a.contextClaimRecords.delete(t)}}}};return c.set(t,s),s}function u(e){let t=i(e),n=t.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,r){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`addActivateGuard`),t.validator?.lifecycle.validateHandler(r,`addActivateGuard`),n.addCanActivate(e,r)},addDeactivateGuard(e,r){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`addDeactivateGuard`),t.validator?.lifecycle.validateHandler(r,`addDeactivateGuard`),n.addCanDeactivate(e,r)},removeActivateGuard(e){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`removeActivateGuard`),n.clearCanActivate(e,`external`)},removeDeactivateGuard(e){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),n.clearCanDeactivate(e,`external`)}}}function d(o,s){let c=i(o);if(c.isDisposed())throw new n(e.ROUTER_DISPOSED);c.validator?.dependencies.validateCloneArgs(s);let l=c.routeGetStore(),d=a(l.tree),f=l.config,p=l.resolvedForwardMap,m=l.routeCustomFields,{options:h,dependencies:g,pluginFactories:_}=c.getCloneState(),{definition:v,external:y}=l.lifecycleNamespace.getFactoriesByOrigin(),b=new r(d,h,{...g,...s}),x=i(b),S=x.routeGetStore(),C=S.lifecycleNamespace;t(S.config,f),Object.assign(S.resolvedForwardMap,p),Object.assign(S.routeCustomFields,m),l.rootPath!==``&&x.setRootPath(l.rootPath);let[w,T]=v,[E,D]=y;for(let[e,t]of Object.entries(w))C.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(T))C.addCanActivate(e,t,!0);let O=u(b);for(let[e,t]of Object.entries(E))O.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(D))O.addActivateGuard(e,t);let k=new Set(x.getCloneState().pluginFactories),A=_.filter(e=>!k.has(e));return A.length>0&&b.usePlugin(...A),b}export{s as a,o as i,u as n,l as r,d as t};
|
|
2
|
+
//# sourceMappingURL=cloneRouter-dMhYu82h.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cloneRouter-dMhYu82h.mjs","names":["routeTreeToDefinitions","RouterClass"],"sources":["../../src/api/helpers.ts","../../src/api/getPluginApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.ts"],"sourcesContent":["// packages/core/src/api/helpers.ts\n\nimport { errorCodes } from \"../constants\";\nimport { RouterError } from \"../RouterError\";\n\nexport function throwIfDisposed(isDisposed: () => boolean): void {\n if (isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n}\n\n/**\n * Bans synchronous reentrant route-CRUD: a CRUD op called while a `TREE_CHANGED`\n * emit is on the stack (i.e. from inside a `subscribeChanges` handler) throws\n * `REENTRANT_TREE_MUTATION` BEFORE mutating — the tree stays atomic (#1032).\n * Deferred CRUD (`queueMicrotask` / `await`) runs after the dispatch settles and\n * is unaffected; CRUD from a transition listener is not a TREE_CHANGED dispatch.\n */\nexport function throwIfReentrantTreeMutation(isEmitting: () => boolean): void {\n if (isEmitting()) {\n throw new RouterError(errorCodes.REENTRANT_TREE_MUTATION);\n }\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n State,\n} from \"@real-router/types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\n makeState: (name, params, path, meta) => {\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n return ctx.makeState(\n name,\n params,\n path,\n meta?.params as\n Record<string, Record<string, \"url\" | \"query\">> | undefined,\n );\n },\n buildState: (routeName, routeParams) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"buildState\",\n );\n\n const { name, params } = ctx.forwardState(routeName, routeParams);\n\n return ctx.buildStateResolved(name, params);\n },\n forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState(routeName, routeParams);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\n },\n setRootPath: (rootPath) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateSetRootPathArgs(rootPath);\n\n ctx.setRootPath(rootPath);\n },\n getRootPath: ctx.getRootPath,\n addEventListener: (eventName, cb) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.eventBus.validateListenerArgs(eventName, cb);\n\n return ctx.addEventListener(eventName, cb);\n },\n buildNavigationState: (name, params = {}) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params,\n );\n const routeInfo = ctx.buildStateResolved(resolvedName, resolvedParams);\n\n if (!routeInfo) {\n return;\n }\n\n return ctx.makeState(\n routeInfo.name,\n routeInfo.params,\n ctx.buildPath(routeInfo.name, routeInfo.params),\n routeInfo.meta,\n );\n },\n getOptions: ctx.getOptions,\n getTree: ctx.getTree,\n addInterceptor: (method, fn) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.validator?.plugins.validateAddInterceptorArgs(method, fn);\n let list = ctx.interceptors.get(method);\n\n if (!list) {\n list = [];\n ctx.interceptors.set(method, list);\n }\n\n list.push(fn);\n\n // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n return store.routeCustomFields[name];\n },\n extendRouter: (extensions: Record<string, unknown>) => {\n throwIfDisposed(ctx.isDisposed);\n\n const keys = Object.keys(extensions);\n\n for (const key of keys) {\n if (key in router) {\n throw new RouterError(errorCodes.PLUGIN_CONFLICT, {\n message: `Cannot extend router: property \"${key}\" already exists`,\n });\n }\n }\n\n for (const key of keys) {\n (router as Record<string, unknown>)[key] = extensions[key];\n }\n\n const extensionRecord = { keys };\n\n ctx.routerExtensions.push(extensionRecord);\n\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n\n for (const key of extensionRecord.keys) {\n delete (router as Record<string, unknown>)[key];\n }\n\n const idx = ctx.routerExtensions.indexOf(extensionRecord);\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n // Input-shape guard, symmetric with the other always-on invariant guards\n // (subscribe / start / navigateToNotFound each typeof-check their input).\n // A non-string namespace coerces to an inconsistent key (\"42\"); an empty\n // string is a meaningless namespace (#1191 N4).\n if (typeof namespace !== \"string\" || namespace === \"\") {\n throw new TypeError(\n `[claimContextNamespace] namespace must be a non-empty string, got ${\n typeof namespace === \"string\" ? \"an empty string\" : typeof namespace\n }`,\n );\n }\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n // `state.context[namespace] = value` dispatches into the inherited\n // Object.prototype.__proto__ setter for the literal key \"__proto__\",\n // swapping the prototype instead of creating an own entry — the data\n // then vanishes from Object.keys / serializeRouterState (#1191 N3).\n // Mirror search-params' assignParam: defineProperty writes a genuine\n // own property; normal names keep the plain-assignment fast path.\n if (namespace === \"__proto__\") {\n Object.defineProperty(state.context, namespace, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n } else {\n state.context[namespace] = value;\n }\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { LifecycleApi } from \"./types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\nexport function getLifecycleApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): LifecycleApi<Dependencies> {\n const ctx = getInternals(router);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycleNamespace = ctx.routeGetStore().lifecycleNamespace!;\n\n return {\n addActivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addActivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addActivateGuard\");\n\n // Handler-limit enforcement lives at the namespace registration choke point\n // (RouteLifecycleNamespace.#registerHandler) so all paths are bounded\n // uniformly — see #961.\n lifecycleNamespace.addCanActivate(name, handler);\n },\n\n addDeactivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addDeactivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addDeactivateGuard\");\n\n lifecycleNamespace.addCanDeactivate(name, handler);\n },\n\n removeActivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeActivateGuard\");\n\n // Inverse of addActivateGuard (external): clears only the external guard;\n // a route-config (definition) canActivate survives (#1171).\n lifecycleNamespace.clearCanActivate(name, \"external\");\n },\n\n removeDeactivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeDeactivateGuard\");\n\n // Inverse of addDeactivateGuard (external): clears only the external guard;\n // a route-config (definition) canDeactivate survives (#1171).\n lifecycleNamespace.clearCanDeactivate(name, \"external\");\n },\n };\n}\n","import { routeTreeToDefinitions } from \"route-tree\";\n\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { assignConfigEntries } from \"../namespaces/RoutesNamespace/helpers\";\nimport { Router as RouterClass } from \"../Router\";\nimport { RouterError } from \"../RouterError\";\nimport { getLifecycleApi } from \"./getLifecycleApi\";\n\nimport type { Route } from \"../types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Build an independent router instance that shares the route tree, options,\n * lifecycle guards, and plugin factories of `router`. The primary use case\n * is **SSR multi-tenancy** — one base router per process, one clone per\n * request.\n *\n * @param router - Source router (must not be disposed).\n * @param dependencies - Optional per-clone overrides merged on top of the\n * base router's dependencies. Always **fresh per call** in the documented\n * SSR pattern: pass per-request state here, never store it in the base.\n *\n * @remarks\n *\n * **Dependency merge — shallow by design.** `base.dependencies` are spread\n * into the clone via `{ ...sourceDeps, ...dependencies }`. Top-level keys\n * are new objects, but **values are shared by reference**: a `Map`, `Set`,\n * class instance, function, or nested plain object stored in\n * `base.dependencies` is the **same instance** in every clone. Mutations\n * in one clone are visible in the base and in every sibling clone.\n *\n * This is intentional. `structuredClone` of dep values is **not** applied\n * because it would:\n * - strip class prototypes (`new DbClient()` → plain object, methods lost)\n * - reject functions and symbols (`DataCloneError`)\n * - fragment singleton pools (one connection pool per request — pool\n * semantics destroyed)\n * - reject circular references\n *\n * **SSR rule of thumb.** Place values in `base.dependencies` according to\n * their lifecycle:\n *\n * - **Singletons / shared services** → `base.dependencies`. Examples: DB\n * client, connection pool, logger, config, feature-flag client. Process-\n * wide pooling depends on sharing these by reference.\n * - **Per-request state** → the `dependencies` override parameter (or\n * `createRequestScope`'s `deps` argument). Examples: `currentUser`,\n * `traceId`, `sessionId`, `abortSignal`. The override is applied last,\n * so it wins over base keys; pass a fresh object per call.\n *\n * Cross-request data leaks are **only possible** when per-request mutable\n * state is incorrectly placed in `base.dependencies`. The override slot is\n * the safe channel.\n *\n * @example\n * ```typescript\n * // Server boot — singletons only\n * const base = createRouter(routes, options, {\n * db: new DbClient(dbUrl),\n * logger,\n * });\n *\n * // Per request — fresh override per call\n * const clone = cloneRouter(base, {\n * currentUser,\n * traceId,\n * });\n * // clone.deps.db === base.deps.db ✓ shared pool (intentional)\n * // clone.deps.currentUser ✓ unique per request\n * ```\n *\n * @see createRequestScope — `@real-router/core/utils` SSR helper that\n * wraps this function and injects `abortSignal` automatically.\n */\nexport function cloneRouter<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n dependencies?: Dependencies,\n): RouterClass<Dependencies> {\n const ctx = getInternals(router);\n\n if (ctx.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n ctx.validator?.dependencies.validateCloneArgs(dependencies);\n\n // Get source store directly\n const sourceStore = ctx.routeGetStore();\n const routes = routeTreeToDefinitions(sourceStore.tree);\n const routeConfig = sourceStore.config;\n const resolvedForwardMap = sourceStore.resolvedForwardMap;\n const routeCustomFields = sourceStore.routeCustomFields;\n\n const {\n options,\n dependencies: sourceDeps,\n pluginFactories,\n } = ctx.getCloneState();\n // Origin-aware factory snapshot — definition guards are re-registered with\n // `isFromDefinition=true` on the clone so `replace()` can still strip them\n // via `clearDefinitionGuards()`. External guards take the public lifecycle\n // API path so they survive `replace()` symmetric with the base.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const sourceLifecycleNamespace = sourceStore.lifecycleNamespace!;\n const { definition: definitionFactories, external: externalFactories } =\n sourceLifecycleNamespace.getFactoriesByOrigin();\n\n const mergedDeps = {\n ...sourceDeps,\n ...dependencies,\n } as Dependencies;\n\n const newRouter = new RouterClass<Dependencies>(\n routes as Route<Dependencies>[],\n options,\n mergedDeps,\n );\n\n const newCtx = getInternals(newRouter);\n const newStore = newCtx.routeGetStore();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const newLifecycleNamespace = newStore.lifecycleNamespace!;\n\n // Copy the source config + store-level maps BEFORE re-registering guards\n // (#1331 review): the definition-guard factories re-executed below must\n // observe the fully-built clone (encoders/decoders/defaultParams/custom\n // fields), mirroring the constructor where flushPendingGuards runs after the\n // store is complete. The five RouteConfig sub-maps go through a single\n // enumeration so a newly added config field is carried over automatically\n // (#965); resolvedForwardMap and routeCustomFields are store-level (not part\n // of RouteConfig) and stay explicit.\n assignConfigEntries(newStore.config, routeConfig);\n Object.assign(newStore.resolvedForwardMap, resolvedForwardMap);\n Object.assign(newStore.routeCustomFields, routeCustomFields);\n\n // #1175: carry the source rootPath. It lives in the store (not options/config),\n // and neither routeTreeToDefinitions nor getCloneState include it — so a clone\n // of a base configured with `setRootPath(\"/app\")` would otherwise build/match\n // under \"\" and 404 every request of a sub-path SSR deployment. setRootPath\n // rebuilds the tree in place with the just-copied config; the rebuild is only\n // paid when a rootPath is actually set, and it runs before the definition-guard\n // factories below so they observe the fully-built clone (rootPath included).\n if (sourceStore.rootPath !== \"\") {\n newCtx.setRootPath(sourceStore.rootPath);\n }\n\n const [definitionDeactivate, definitionActivate] = definitionFactories;\n const [externalDeactivate, externalActivate] = externalFactories;\n\n for (const [name, handler] of Object.entries(definitionDeactivate)) {\n newLifecycleNamespace.addCanDeactivate(name, handler, true);\n }\n\n for (const [name, handler] of Object.entries(definitionActivate)) {\n newLifecycleNamespace.addCanActivate(name, handler, true);\n }\n\n const lifecycle = getLifecycleApi(newRouter);\n\n for (const [name, handler] of Object.entries(externalDeactivate)) {\n lifecycle.addDeactivateGuard(name, handler);\n }\n\n for (const [name, handler] of Object.entries(externalActivate)) {\n lifecycle.addActivateGuard(name, handler);\n }\n\n // Plugin replay runs last and skips factories that a (contract-violating)\n // definition-guard factory already registered on the clone during the\n // re-compilation above — without the filter every clone would double-apply\n // such a plugin: once via the factory, once via this replay (#1331 review).\n const alreadyRegistered = new Set(newCtx.getCloneState().pluginFactories);\n const pluginsToReplay = pluginFactories.filter(\n (factory) => !alreadyRegistered.has(factory),\n );\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `usePlugin(...[])` with an empty spread is a no-op, so entering the block on an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips a real plugin list and is killable.)\n if (pluginsToReplay.length > 0) {\n newRouter.usePlugin(...pluginsToReplay);\n }\n\n return newRouter;\n}\n"],"mappings":"wGAKA,SAAgB,EAAgB,EAAiC,CAC/D,GAAI,EAAW,EACb,MAAM,IAAI,EAAY,EAAW,eAAe,CAEpD,CASA,SAAgB,EAA6B,EAAiC,CAC5E,GAAI,EAAW,EACb,MAAM,IAAI,EAAY,EAAW,uBAAuB,CAE5D,CCFA,MAAM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAAM,IAAI,CAAM,EAE/B,GAAI,EACF,OAAO,EAGT,IAAM,EAAM,EAAa,CAAM,EACzB,EAAiB,CACrB,WAAY,EAAM,EAAQ,EAAM,KAC9B,EAAI,WAAW,MAAM,sBAAsB,EAAM,EAAQ,CAAI,EAEtD,EAAI,UACT,EACA,EACA,EACA,GAAM,MAER,GAEF,YAAa,EAAW,IAAgB,CACtC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+1,2 @@
|
|
|
1
|
-
import{l as e}from"./esm-CLeBo4Hk.mjs";import{r as t,t as n}from"./cloneRouter-
|
|
1
|
+
import{l as e}from"./esm-CLeBo4Hk.mjs";import{r as t,t as n}from"./cloneRouter-dMhYu82h.mjs";function r(e){return`signal`in e&&typeof e.signal==`object`&&e.signal!==void 0&&typeof e.signal.aborted==`boolean`}function i(e,t,i){let a,o,s;if(r(e))s=e.signal;else{let t=new AbortController,n=()=>{t.abort()};s=t.signal,o=()=>{e.on(`close`,n)},a=()=>{e.removeListener?.(`close`,n)}}let c=n(t,{...i,abortSignal:s});o?.();let l=!1,u=()=>l?Promise.resolve():(l=!0,a?.(),c.dispose(),Promise.resolve());return{router:c,signal:s,dispose:u,[Symbol.asyncDispose]:u}}function a(e,t){for(let n of e.children.values())n.children.size===0?t.push(n.fullName):a(n,t)}function o(e){let t=[];return a(e,t),t}async function s(e,n){let r=o(t(e).getTree()),i=[];for(let t of r){let r=n?.[t];if(r){let n=await r();for(let r of n)i.push(e.buildPath(t,r))}else i.push(e.buildPath(t,{}))}return i}async function c(t,n,r){let i=r?.deserialize??JSON.parse,a=typeof n==`string`?i(n):n,o=e(t),s=o.hydrationState;o.hydrationState=a;try{return await t.start(a.path)}finally{o.hydrationState=s}}function l(e,t){return((t?.serialize??JSON.stringify)(e)??`null`).replaceAll(`<`,String.raw`\u003c`).replaceAll(`>`,String.raw`\u003e`).replaceAll(`&`,String.raw`\u0026`)}function u(e,t){let n=t?.excludeContext,r=e.context;if(n?.length){let t=Object.create(null),i=e.context;for(let[e,r]of Object.entries(i))n.includes(e)||(t[e]=r);r=t}let i={name:e.name,params:e.params,path:e.path,context:r};return t?.serialize?l(i,{serialize:t.serialize}):l(i)}export{i as createRequestScope,s as getStaticPaths,c as hydrateRouter,u as serializeRouterState,l as serializeState};
|
|
2
2
|
//# sourceMappingURL=utils.mjs.map
|
package/dist/esm/utils.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","names":[],"sources":["../../src/utils/createRequestScope.ts","../../src/utils/getStaticPaths.ts","../../src/utils/hydrateRouter.ts","../../src/utils/serializeState.ts","../../src/utils/serializeRouterState.ts"],"sourcesContent":["import { cloneRouter } from \"../api/cloneRouter\";\n\nimport type { Router as RouterClass } from \"../Router\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Subset of Node's `http.IncomingMessage` that `createRequestScope` relies on:\n * a `\"close\"` event indicating that the client disconnected (or the response\n * was fully sent) and the standard `removeListener` cleanup hook.\n */\nexport interface IncomingMessageLike {\n on: (event: \"close\", listener: () => void) => unknown;\n removeListener?: (event: \"close\", listener: () => void) => unknown;\n}\n\n/**\n * Web `Request`-shaped object — anything carrying an `AbortSignal`. Web\n * runtimes (Bun, Cloudflare Workers, Vite RSC) surface client-disconnect via\n * `request.signal` directly, so no listener attachment is needed.\n */\nexport interface RequestLike {\n signal: AbortSignal;\n}\n\nexport type RequestScopeSource = IncomingMessageLike | RequestLike;\n\nexport interface RequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> extends AsyncDisposable {\n /**\n * Per-request router clone. Carries `abortSignal` injected into its\n * dependencies — loaders can `getDep(\"abortSignal\")` and pass it to fetch /\n * `withTimeout` for cooperative cancellation when the client disconnects.\n */\n readonly router: RouterClass<Dependencies>;\n\n /**\n * Aborts when the request closes (Node `IncomingMessage`'s `\"close\"` event)\n * or when the upstream Web `Request.signal` aborts.\n */\n readonly signal: AbortSignal;\n\n /**\n * Detach the close listener (if attached to a Node `IncomingMessage`) and\n * dispose the cloned router. Idempotent — safe to call multiple times or in\n * combination with `Symbol.asyncDispose`.\n */\n dispose: () => Promise<void>;\n}\n\nfunction isRequestLike(request: RequestScopeSource): request is RequestLike {\n return (\n \"signal\" in request &&\n typeof (request as Partial<RequestLike>).signal === \"object\" &&\n (request as Partial<RequestLike>).signal !== undefined &&\n typeof request.signal.aborted === \"boolean\"\n );\n}\n\n/**\n * Build a per-request router scope: clones `base`, attaches an `AbortSignal`\n * tied to the request's lifetime, and exposes `dispose()` (plus\n * `Symbol.asyncDispose` for `await using` declarations).\n *\n * Replaces the four-step boilerplate that every server entry repeats:\n *\n * 1. `new AbortController()` per request\n * 2. `req.on(\"close\", () => controller.abort())`\n * 3. `cloneRouter(base, { ...deps, abortSignal: signal })`\n * 4. `try { ... } finally { router.dispose() }`\n *\n * The signal is injected into the router clone under `abortSignal` so existing\n * loaders that read `getDep(\"abortSignal\")` keep working without changes. If\n * `deps` already carries an `abortSignal`, the request-tied signal **wins** (it\n * is spread last) — a caller-supplied `abortSignal` is intentionally overridden,\n * since the scope's purpose is to own the request-lifecycle signal.\n *\n * ## `await using` compatibility\n *\n * The scope implements `Symbol.asyncDispose`, so `await using scope = …` is\n * supported on runtimes that ship the well-known `Symbol.asyncDispose`:\n *\n * - **Node.js 24+** (full support; partial in 20.4–20.17 only for `fs`/`stream`)\n * - **Bun 1.0.23+**, **Deno 1.37+**\n * - **Chrome / Edge 127+**, **Firefox 141+**\n * - **Safari**: not yet supported (irrelevant in practice — this helper is\n * server-side only and never reaches the browser)\n *\n * On Node.js 22 LTS the well-known symbol is unavailable, so `await using`\n * fails. **The bundled SSR examples therefore use the explicit\n * `try/finally` + `await scope.dispose()` form**, which works on every\n * runtime. Use `await using` only when you control the deployment target and\n * know it ships the symbol.\n *\n * @example\n * ```typescript\n * // Explicit dispose — works on Node 18+, all browsers, every CI image\n * export async function render(url: string, req: IncomingMessage) {\n * const scope = createRequestScope(req, baseRouter, { currentUser });\n * try {\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n *\n * // `await using` — Node 24+, Bun, Deno, modern browsers\n * export async function render(url: string, req: IncomingMessage) {\n * await using scope = createRequestScope(req, baseRouter, { currentUser });\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * }\n *\n * // Web runtime (signal already on the request)\n * async function handler(request: Request) {\n * const scope = createRequestScope(request, baseRouter, { db });\n * try {\n * scope.router.usePlugin(rscServerPluginFactory(loaders));\n * return await render(scope.router, request.url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n * ```\n */\nexport function createRequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n request: RequestScopeSource,\n base: Router<Dependencies>,\n deps?: Partial<Dependencies>,\n): RequestScope<Dependencies> {\n let detach: (() => void) | undefined;\n let attach: (() => void) | undefined;\n let signal: AbortSignal;\n\n if (isRequestLike(request)) {\n signal = request.signal;\n } else {\n const controller = new AbortController();\n const onClose = (): void => {\n controller.abort();\n };\n\n signal = controller.signal;\n // Clone-before-attach (#969): defer attaching the \"close\" listener until\n // after cloneRouter succeeds. cloneRouter is synchronous, so no \"close\"\n // macrotask can fire in the gap; and if it throws (e.g. ROUTER_DISPOSED on\n // an already-disposed base) the helper exits without returning a scope\n // handle — so a listener attached here would strand on the request with no\n // way to detach it.\n attach = () => {\n request.on(\"close\", onClose);\n };\n detach = () => {\n request.removeListener?.(\"close\", onClose);\n };\n }\n\n const router = cloneRouter(base, {\n ...deps,\n abortSignal: signal,\n } as Dependencies);\n\n // The clone exists — now it is safe to attach the close listener (Node path\n // only; `attach` is undefined for the Web path).\n attach?.();\n\n let disposed = false;\n\n const dispose = (): Promise<void> => {\n if (disposed) {\n return Promise.resolve();\n }\n\n disposed = true;\n detach?.();\n router.dispose();\n\n return Promise.resolve();\n };\n\n return {\n router,\n signal,\n dispose,\n // eslint-disable-next-line unicorn/no-nonstandard-builtin-properties -- Symbol.asyncDispose is a standard ES2023 well-known symbol (`await using`)\n [Symbol.asyncDispose]: dispose,\n };\n}\n","import { getPluginApi } from \"../api/getPluginApi\";\n\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport type StaticPathEntries = Record<\n string,\n () => Promise<Record<string, string>[]>\n>;\n\nfunction collectLeafRouteNames(node: RouteTree, result: string[]): void {\n for (const child of node.children.values()) {\n if (child.children.size === 0) {\n result.push(child.fullName);\n } else {\n // Accumulate into the shared array rather than\n // `result.push(...getLeafRouteNames(child))`: the spread passes one\n // argument per leaf, and V8 caps spread/apply arguments (~124k on Node 24),\n // so a section with that many static leaf routes threw\n // `RangeError: Maximum call stack size exceeded`. Accumulating also drops\n // the per-subtree intermediate-array allocation.\n collectLeafRouteNames(child, result);\n }\n }\n}\n\nfunction getLeafRouteNames(node: RouteTree): string[] {\n const result: string[] = [];\n\n collectLeafRouteNames(node, result);\n\n return result;\n}\n\nexport async function getStaticPaths<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n entries?: StaticPathEntries,\n): Promise<string[]> {\n const tree = getPluginApi(router).getTree();\n const leafRoutes = getLeafRouteNames(tree);\n const paths: string[] = [];\n\n for (const routeName of leafRoutes) {\n const entryFn = entries?.[routeName];\n\n if (entryFn) {\n const paramSets = await entryFn();\n\n for (const params of paramSets) {\n paths.push(router.buildPath(routeName, params));\n }\n } else {\n paths.push(router.buildPath(routeName, {}));\n }\n }\n\n return paths;\n}\n","import { getInternals } from \"../internals\";\n\nimport type { SerializedRouterState } from \"./serializeRouterState\";\nimport type { Router, State } from \"@real-router/types\";\n\n/**\n * Custom deserializer signature for {@link hydrateRouter} (#606). Compatible\n * with `JSON.parse` (default), `devalue.parse`, `superjson.parse`, or any\n * user-supplied function.\n */\nexport type Deserialize = (json: string) => unknown;\n\nexport interface HydrateRouterOptions {\n /**\n * Custom deserializer (e.g., `devalue.parse` / `superjson.parse`) for\n * matching the `serialize` passed to {@link serializeRouterState}. Defaults\n * to `JSON.parse`. Ignored when `source` is already an object.\n *\n * @default JSON.parse\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n * await hydrateRouter(router, ssrJson, { deserialize: devalue.parse });\n * ```\n */\n deserialize?: Deserialize;\n}\n\n/**\n * Hydrate a fresh router from server-serialized State (#563, #596).\n *\n * Accepts either a JSON string (parsed via `JSON.parse` by default, or\n * `options.deserialize` when provided) or a State-shaped object. Extracts\n * `state.path` and delegates to `router.start(state.path)` — the canonical\n * URL is the source of truth for the router on hydration.\n *\n * The full parsed state (incl. `state.context.<namespace>` payloads) is\n * deposited into a one-shot scratchpad on `RouterInternals.hydrationState`\n * before `start()` is invoked and cleared in the matching `finally`. SSR\n * loader plugins (`@real-router/ssr-data-plugin`,\n * `@real-router/rsc-server-plugin`) read this scratchpad to skip their loader\n * call when the server-resolved namespace value is already present — avoiding\n * the post-hydration loader re-run on first paint.\n *\n * Single-shot semantics: the scratchpad is consumed during the first `start()`\n * triggered by `hydrateRouter` regardless of route mismatch; subsequent\n * `start()` calls run loaders normally.\n *\n * @example\n * ```typescript\n * // Client\n * const router = createAppRouter();\n * router.usePlugin(browserPluginFactory());\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * await hydrateRouter(router, window.__SSR_STATE__, {\n * deserialize: devalue.parse,\n * });\n * ```\n */\nexport async function hydrateRouter(\n router: Router,\n source: string | { path: string },\n options?: HydrateRouterOptions,\n): Promise<State> {\n const deserialize: Deserialize = options?.deserialize ?? JSON.parse;\n const parsed =\n typeof source === \"string\"\n ? (deserialize(source) as SerializedRouterState)\n : (source as SerializedRouterState);\n\n const ctx = getInternals(router);\n const previous = ctx.hydrationState;\n\n ctx.hydrationState = parsed;\n\n try {\n return await router.start(parsed.path);\n } finally {\n ctx.hydrationState = previous;\n }\n}\n","/**\n * Custom serializer signature for {@link serializeState} (#606).\n *\n * Compatible with `JSON.stringify` (default) as well as `devalue.stringify`,\n * `superjson.stringify`, or any user-supplied function that returns a JSON\n * string. The output is run through XSS-safe character escapes regardless\n * of which serializer produced it.\n */\nexport type Serialize = (data: unknown) => string;\n\nexport interface SerializeStateOptions {\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types (Date / Map / Set / RegExp / BigInt). Defaults to\n * `JSON.stringify`. Output is still XSS-escaped.\n *\n * @default JSON.stringify\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization for embedding data in HTML `<script>` tags.\n *\n * Escapes `<`, `>`, and `&` to their Unicode equivalents to prevent\n * injection via `</script>` or HTML entities inside inline scripts.\n *\n * Pass `options.serialize` to use a custom serializer such as `devalue` or\n * `superjson` for non-JSON types (Date/Map/Set/RegExp/BigInt). The serializer\n * must return a string; XSS-escape is applied to its output.\n *\n * @example\n * ```typescript\n * const json = serializeState({ name: \"home\", path: \"/\" });\n * const html = `<script>window.__STATE__=${json}</script>`;\n * ```\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeState(\n * { date: new Date(), tags: new Set([\"a\", \"b\"]) },\n * { serialize: devalue.stringify },\n * );\n * ```\n */\nexport function serializeState(\n data: unknown,\n options?: SerializeStateOptions,\n): string {\n const serialize = options?.serialize ?? JSON.stringify;\n // JSON.stringify returns undefined for top-level `undefined`, Symbol,\n // function, and other non-serializable values (lib.d.ts types it as\n // `string` but the runtime can return undefined). A custom serializer\n // that returns undefined for unsupported input is normalized the same way.\n const serialized = (serialize(data) as string | undefined) ?? \"null\";\n\n return serialized\n .replaceAll(\"<\", String.raw`\\u003c`)\n .replaceAll(\">\", String.raw`\\u003e`)\n .replaceAll(\"&\", String.raw`\\u0026`);\n}\n","import { serializeState } from \"./serializeState\";\n\nimport type { Serialize } from \"./serializeState\";\nimport type { Params, State } from \"@real-router/types\";\n\n/**\n * Parsed shape produced by {@link serializeRouterState} (after `JSON.parse`).\n *\n * Identical to {@link State} minus `transition` (per-navigation `TransitionMeta`\n * is meaningless after hydration; the client builds its own on commit). Used as\n * the input shape for {@link hydrateRouter} and as the type of the one-shot\n * hydration scratchpad consumed by SSR loader plugins.\n */\nexport type SerializedRouterState<P extends Params = Params> = Omit<\n State<P>,\n \"transition\"\n>;\n\nexport interface SerializeRouterStateOptions {\n /**\n * Plugin context namespaces to strip from the serialized output.\n * Use when a plugin populates `state.context.<ns>` with non-JSON-serializable\n * values (e.g., RSC payload: ReactNode trees containing functions/symbols).\n *\n * @default []\n */\n excludeContext?: readonly string[];\n\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types in `state.params` and `state.context.<ns>` payloads\n * (Date / Map / Set / RegExp / BigInt). Defaults to `JSON.stringify`.\n *\n * Pair with the matching `deserialize` on `hydrateRouter` to round-trip the\n * extended types on the client.\n *\n * @default JSON.stringify\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * ```\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization of router State for SSR → client transport (#563).\n *\n * Strips `state.transition` (per-navigation `TransitionMeta` — meaningless after\n * hydration; the client's hydration commit produces its own `transition`).\n * Keeps `name`, `params`, `path`, and `context` (plugin context namespaces are\n * preserved as-is — server's `state.context.data` from `ssr-data-plugin` and\n * any other plugin claims travel to the client untouched).\n *\n * Pass `options.excludeContext` to strip specific namespaces from the output —\n * required for plugins that publish non-JSON-serializable values (e.g., RSC\n * `ReactNode` trees from `@real-router/rsc-server-plugin`).\n *\n * @example\n * ```typescript\n * // Server\n * const state = await router.start(req.url);\n * const html = `<script>window.__SSR_STATE__=${serializeRouterState(state)}</script>`;\n *\n * // Client\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With RSC plugin: strip the \"rsc\" namespace before transport\n * const state = await router.start(url);\n * const json = serializeRouterState(state, { excludeContext: [\"rsc\"] });\n * ```\n *\n * @example\n * ```typescript\n * // Non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * // On the client:\n * await hydrateRouter(router, json, { deserialize: devalue.parse });\n * ```\n */\nexport function serializeRouterState(\n state: State,\n options?: SerializeRouterStateOptions,\n): string {\n const exclude = options?.excludeContext;\n\n let context = state.context;\n\n if (exclude?.length) {\n const filtered: Record<string, unknown> = {};\n const source = state.context;\n\n for (const [key, value] of Object.entries(source)) {\n if (!exclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n context = filtered;\n }\n\n const payload = {\n name: state.name,\n params: state.params,\n path: state.path,\n context,\n };\n\n return options?.serialize\n ? serializeState(payload, { serialize: options.serialize })\n : serializeState(payload);\n}\n"],"mappings":"6FAkDA,SAAS,EAAc,EAAqD,CAC1E,MACE,WAAY,GACZ,OAAQ,EAAiC,QAAW,UACnD,EAAiC,SAAW,IAAA,IAC7C,OAAO,EAAQ,OAAO,SAAY,SAEtC,CAqEA,SAAgB,EAGd,EACA,EACA,EAC4B,CAC5B,IAAI,EACA,EACA,EAEJ,GAAI,EAAc,CAAO,EACvB,EAAS,EAAQ,WACZ,CACL,IAAM,EAAa,IAAI,gBACjB,MAAsB,CAC1B,EAAW,MAAM,CACnB,EAEA,EAAS,EAAW,OAOpB,MAAe,CACb,EAAQ,GAAG,QAAS,CAAO,CAC7B,EACA,MAAe,CACb,EAAQ,iBAAiB,QAAS,CAAO,CAC3C,CACF,CAEA,IAAM,EAAS,EAAY,EAAM,CAC/B,GAAG,EACH,YAAa,CACf,CAAiB,EAIjB,IAAS,EAET,IAAI,EAAW,GAET,MACA,EACK,QAAQ,QAAQ,GAGzB,EAAW,GACX,IAAS,EACT,EAAO,QAAQ,EAER,QAAQ,QAAQ,GAGzB,MAAO,CACL,SACA,SACA,WAEC,OAAO,cAAe,CACzB,CACF,CCpLA,SAAS,EAAsB,EAAiB,EAAwB,CACtE,IAAK,IAAM,KAAS,EAAK,SAAS,OAAO,EACnC,EAAM,SAAS,OAAS,EAC1B,EAAO,KAAK,EAAM,QAAQ,EAQ1B,EAAsB,EAAO,CAAM,CAGzC,CAEA,SAAS,EAAkB,EAA2B,CACpD,IAAM,EAAmB,CAAC,EAI1B,OAFA,EAAsB,EAAM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,OAAO,GAAS,UACZ,EAAe,EAAS,CAAE,UAAW,EAAQ,SAAU,CAAC,EACxD,EAAe,CAAO,CAC5B"}
|
|
1
|
+
{"version":3,"file":"utils.mjs","names":[],"sources":["../../src/utils/createRequestScope.ts","../../src/utils/getStaticPaths.ts","../../src/utils/hydrateRouter.ts","../../src/utils/serializeState.ts","../../src/utils/serializeRouterState.ts"],"sourcesContent":["import { cloneRouter } from \"../api/cloneRouter\";\n\nimport type { Router as RouterClass } from \"../Router\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Subset of Node's `http.IncomingMessage` that `createRequestScope` relies on:\n * a `\"close\"` event indicating that the client disconnected (or the response\n * was fully sent) and the standard `removeListener` cleanup hook.\n */\nexport interface IncomingMessageLike {\n on: (event: \"close\", listener: () => void) => unknown;\n removeListener?: (event: \"close\", listener: () => void) => unknown;\n}\n\n/**\n * Web `Request`-shaped object — anything carrying an `AbortSignal`. Web\n * runtimes (Bun, Cloudflare Workers, Vite RSC) surface client-disconnect via\n * `request.signal` directly, so no listener attachment is needed.\n */\nexport interface RequestLike {\n signal: AbortSignal;\n}\n\nexport type RequestScopeSource = IncomingMessageLike | RequestLike;\n\nexport interface RequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> extends AsyncDisposable {\n /**\n * Per-request router clone. Carries `abortSignal` injected into its\n * dependencies — loaders can `getDep(\"abortSignal\")` and pass it to fetch /\n * `withTimeout` for cooperative cancellation when the client disconnects.\n */\n readonly router: RouterClass<Dependencies>;\n\n /**\n * Aborts when the request closes (Node `IncomingMessage`'s `\"close\"` event)\n * or when the upstream Web `Request.signal` aborts.\n */\n readonly signal: AbortSignal;\n\n /**\n * Detach the close listener (if attached to a Node `IncomingMessage`) and\n * dispose the cloned router. Idempotent — safe to call multiple times or in\n * combination with `Symbol.asyncDispose`.\n */\n dispose: () => Promise<void>;\n}\n\nfunction isRequestLike(request: RequestScopeSource): request is RequestLike {\n return (\n \"signal\" in request &&\n typeof (request as Partial<RequestLike>).signal === \"object\" &&\n (request as Partial<RequestLike>).signal !== undefined &&\n typeof request.signal.aborted === \"boolean\"\n );\n}\n\n/**\n * Build a per-request router scope: clones `base`, attaches an `AbortSignal`\n * tied to the request's lifetime, and exposes `dispose()` (plus\n * `Symbol.asyncDispose` for `await using` declarations).\n *\n * Replaces the four-step boilerplate that every server entry repeats:\n *\n * 1. `new AbortController()` per request\n * 2. `req.on(\"close\", () => controller.abort())`\n * 3. `cloneRouter(base, { ...deps, abortSignal: signal })`\n * 4. `try { ... } finally { router.dispose() }`\n *\n * The signal is injected into the router clone under `abortSignal` so existing\n * loaders that read `getDep(\"abortSignal\")` keep working without changes. If\n * `deps` already carries an `abortSignal`, the request-tied signal **wins** (it\n * is spread last) — a caller-supplied `abortSignal` is intentionally overridden,\n * since the scope's purpose is to own the request-lifecycle signal.\n *\n * ## `await using` compatibility\n *\n * The scope implements `Symbol.asyncDispose`, so `await using scope = …` is\n * supported on runtimes that ship the well-known `Symbol.asyncDispose`:\n *\n * - **Node.js 24+** (full support; partial in 20.4–20.17 only for `fs`/`stream`)\n * - **Bun 1.0.23+**, **Deno 1.37+**\n * - **Chrome / Edge 127+**, **Firefox 141+**\n * - **Safari**: not yet supported (irrelevant in practice — this helper is\n * server-side only and never reaches the browser)\n *\n * On Node.js 22 LTS the well-known symbol is unavailable, so `await using`\n * fails. **The bundled SSR examples therefore use the explicit\n * `try/finally` + `await scope.dispose()` form**, which works on every\n * runtime. Use `await using` only when you control the deployment target and\n * know it ships the symbol.\n *\n * @example\n * ```typescript\n * // Explicit dispose — works on Node 18+, all browsers, every CI image\n * export async function render(url: string, req: IncomingMessage) {\n * const scope = createRequestScope(req, baseRouter, { currentUser });\n * try {\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n *\n * // `await using` — Node 24+, Bun, Deno, modern browsers\n * export async function render(url: string, req: IncomingMessage) {\n * await using scope = createRequestScope(req, baseRouter, { currentUser });\n * scope.router.usePlugin(ssrDataPluginFactory(loaders));\n * return await renderShell(scope.router, url);\n * }\n *\n * // Web runtime (signal already on the request)\n * async function handler(request: Request) {\n * const scope = createRequestScope(request, baseRouter, { db });\n * try {\n * scope.router.usePlugin(rscServerPluginFactory(loaders));\n * return await render(scope.router, request.url);\n * } finally {\n * await scope.dispose();\n * }\n * }\n * ```\n */\nexport function createRequestScope<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n request: RequestScopeSource,\n base: Router<Dependencies>,\n deps?: Partial<Dependencies>,\n): RequestScope<Dependencies> {\n let detach: (() => void) | undefined;\n let attach: (() => void) | undefined;\n let signal: AbortSignal;\n\n if (isRequestLike(request)) {\n signal = request.signal;\n } else {\n const controller = new AbortController();\n const onClose = (): void => {\n controller.abort();\n };\n\n signal = controller.signal;\n // Clone-before-attach (#969): defer attaching the \"close\" listener until\n // after cloneRouter succeeds. cloneRouter is synchronous, so no \"close\"\n // macrotask can fire in the gap; and if it throws (e.g. ROUTER_DISPOSED on\n // an already-disposed base) the helper exits without returning a scope\n // handle — so a listener attached here would strand on the request with no\n // way to detach it.\n attach = () => {\n request.on(\"close\", onClose);\n };\n detach = () => {\n request.removeListener?.(\"close\", onClose);\n };\n }\n\n const router = cloneRouter(base, {\n ...deps,\n abortSignal: signal,\n } as Dependencies);\n\n // The clone exists — now it is safe to attach the close listener (Node path\n // only; `attach` is undefined for the Web path).\n attach?.();\n\n let disposed = false;\n\n const dispose = (): Promise<void> => {\n if (disposed) {\n return Promise.resolve();\n }\n\n disposed = true;\n detach?.();\n router.dispose();\n\n return Promise.resolve();\n };\n\n return {\n router,\n signal,\n dispose,\n // eslint-disable-next-line unicorn/no-nonstandard-builtin-properties -- Symbol.asyncDispose is a standard ES2023 well-known symbol (`await using`)\n [Symbol.asyncDispose]: dispose,\n };\n}\n","import { getPluginApi } from \"../api/getPluginApi\";\n\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\nimport type { RouteTree } from \"route-tree\";\n\nexport type StaticPathEntries = Record<\n string,\n () => Promise<Record<string, string>[]>\n>;\n\nfunction collectLeafRouteNames(node: RouteTree, result: string[]): void {\n for (const child of node.children.values()) {\n if (child.children.size === 0) {\n result.push(child.fullName);\n } else {\n // Accumulate into the shared array rather than\n // `result.push(...getLeafRouteNames(child))`: the spread passes one\n // argument per leaf, and V8 caps spread/apply arguments (~124k on Node 24),\n // so a section with that many static leaf routes threw\n // `RangeError: Maximum call stack size exceeded`. Accumulating also drops\n // the per-subtree intermediate-array allocation.\n collectLeafRouteNames(child, result);\n }\n }\n}\n\nfunction getLeafRouteNames(node: RouteTree): string[] {\n const result: string[] = [];\n\n collectLeafRouteNames(node, result);\n\n return result;\n}\n\nexport async function getStaticPaths<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n entries?: StaticPathEntries,\n): Promise<string[]> {\n const tree = getPluginApi(router).getTree();\n const leafRoutes = getLeafRouteNames(tree);\n const paths: string[] = [];\n\n for (const routeName of leafRoutes) {\n const entryFn = entries?.[routeName];\n\n if (entryFn) {\n const paramSets = await entryFn();\n\n for (const params of paramSets) {\n paths.push(router.buildPath(routeName, params));\n }\n } else {\n paths.push(router.buildPath(routeName, {}));\n }\n }\n\n return paths;\n}\n","import { getInternals } from \"../internals\";\n\nimport type { SerializedRouterState } from \"./serializeRouterState\";\nimport type { Router, State } from \"@real-router/types\";\n\n/**\n * Custom deserializer signature for {@link hydrateRouter} (#606). Compatible\n * with `JSON.parse` (default), `devalue.parse`, `superjson.parse`, or any\n * user-supplied function.\n */\nexport type Deserialize = (json: string) => unknown;\n\nexport interface HydrateRouterOptions {\n /**\n * Custom deserializer (e.g., `devalue.parse` / `superjson.parse`) for\n * matching the `serialize` passed to {@link serializeRouterState}. Defaults\n * to `JSON.parse`. Ignored when `source` is already an object.\n *\n * @default JSON.parse\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n * await hydrateRouter(router, ssrJson, { deserialize: devalue.parse });\n * ```\n */\n deserialize?: Deserialize;\n}\n\n/**\n * Hydrate a fresh router from server-serialized State (#563, #596).\n *\n * Accepts either a JSON string (parsed via `JSON.parse` by default, or\n * `options.deserialize` when provided) or a State-shaped object. Extracts\n * `state.path` and delegates to `router.start(state.path)` — the canonical\n * URL is the source of truth for the router on hydration.\n *\n * The full parsed state (incl. `state.context.<namespace>` payloads) is\n * deposited into a one-shot scratchpad on `RouterInternals.hydrationState`\n * before `start()` is invoked and cleared in the matching `finally`. SSR\n * loader plugins (`@real-router/ssr-data-plugin`,\n * `@real-router/rsc-server-plugin`) read this scratchpad to skip their loader\n * call when the server-resolved namespace value is already present — avoiding\n * the post-hydration loader re-run on first paint.\n *\n * Single-shot semantics: the scratchpad is consumed during the first `start()`\n * triggered by `hydrateRouter` regardless of route mismatch; subsequent\n * `start()` calls run loaders normally.\n *\n * @example\n * ```typescript\n * // Client\n * const router = createAppRouter();\n * router.usePlugin(browserPluginFactory());\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * await hydrateRouter(router, window.__SSR_STATE__, {\n * deserialize: devalue.parse,\n * });\n * ```\n */\nexport async function hydrateRouter(\n router: Router,\n source: string | { path: string },\n options?: HydrateRouterOptions,\n): Promise<State> {\n const deserialize: Deserialize = options?.deserialize ?? JSON.parse;\n const parsed =\n typeof source === \"string\"\n ? (deserialize(source) as SerializedRouterState)\n : (source as SerializedRouterState);\n\n const ctx = getInternals(router);\n const previous = ctx.hydrationState;\n\n ctx.hydrationState = parsed;\n\n try {\n return await router.start(parsed.path);\n } finally {\n ctx.hydrationState = previous;\n }\n}\n","/**\n * Custom serializer signature for {@link serializeState} (#606).\n *\n * Compatible with `JSON.stringify` (default) as well as `devalue.stringify`,\n * `superjson.stringify`, or any user-supplied function that returns a JSON\n * string. The output is run through XSS-safe character escapes regardless\n * of which serializer produced it.\n */\nexport type Serialize = (data: unknown) => string;\n\nexport interface SerializeStateOptions {\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types (Date / Map / Set / RegExp / BigInt). Defaults to\n * `JSON.stringify`. Output is still XSS-escaped.\n *\n * @default JSON.stringify\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization for embedding data in HTML `<script>` tags.\n *\n * Escapes `<`, `>`, and `&` to their Unicode equivalents to prevent\n * injection via `</script>` or HTML entities inside inline scripts.\n *\n * Pass `options.serialize` to use a custom serializer such as `devalue` or\n * `superjson` for non-JSON types (Date/Map/Set/RegExp/BigInt). The serializer\n * must return a string; XSS-escape is applied to its output.\n *\n * @example\n * ```typescript\n * const json = serializeState({ name: \"home\", path: \"/\" });\n * const html = `<script>window.__STATE__=${json}</script>`;\n * ```\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeState(\n * { date: new Date(), tags: new Set([\"a\", \"b\"]) },\n * { serialize: devalue.stringify },\n * );\n * ```\n */\nexport function serializeState(\n data: unknown,\n options?: SerializeStateOptions,\n): string {\n const serialize = options?.serialize ?? JSON.stringify;\n // JSON.stringify returns undefined for top-level `undefined`, Symbol,\n // function, and other non-serializable values (lib.d.ts types it as\n // `string` but the runtime can return undefined). A custom serializer\n // that returns undefined for unsupported input is normalized the same way.\n const serialized = (serialize(data) as string | undefined) ?? \"null\";\n\n return serialized\n .replaceAll(\"<\", String.raw`\\u003c`)\n .replaceAll(\">\", String.raw`\\u003e`)\n .replaceAll(\"&\", String.raw`\\u0026`);\n}\n","import { serializeState } from \"./serializeState\";\n\nimport type { Serialize } from \"./serializeState\";\nimport type { Params, State } from \"@real-router/types\";\n\n/**\n * Parsed shape produced by {@link serializeRouterState} (after `JSON.parse`).\n *\n * Identical to {@link State} minus `transition` (per-navigation `TransitionMeta`\n * is meaningless after hydration; the client builds its own on commit). Used as\n * the input shape for {@link hydrateRouter} and as the type of the one-shot\n * hydration scratchpad consumed by SSR loader plugins.\n */\nexport type SerializedRouterState<P extends Params = Params> = Omit<\n State<P>,\n \"transition\"\n>;\n\nexport interface SerializeRouterStateOptions {\n /**\n * Plugin context namespaces to strip from the serialized output.\n * Use when a plugin populates `state.context.<ns>` with non-JSON-serializable\n * values (e.g., RSC payload: ReactNode trees containing functions/symbols).\n *\n * @default []\n */\n excludeContext?: readonly string[];\n\n /**\n * Custom serializer (e.g., `devalue.stringify` / `superjson.stringify`) to\n * support non-JSON types in `state.params` and `state.context.<ns>` payloads\n * (Date / Map / Set / RegExp / BigInt). Defaults to `JSON.stringify`.\n *\n * Pair with the matching `deserialize` on `hydrateRouter` to round-trip the\n * extended types on the client.\n *\n * @default JSON.stringify\n *\n * @example\n * ```typescript\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * ```\n */\n serialize?: Serialize;\n}\n\n/**\n * XSS-safe JSON serialization of router State for SSR → client transport (#563).\n *\n * Strips `state.transition` (per-navigation `TransitionMeta` — meaningless after\n * hydration; the client's hydration commit produces its own `transition`).\n * Keeps `name`, `params`, `path`, and `context` (plugin context namespaces are\n * preserved as-is — server's `state.context.data` from `ssr-data-plugin` and\n * any other plugin claims travel to the client untouched).\n *\n * Pass `options.excludeContext` to strip specific namespaces from the output —\n * required for plugins that publish non-JSON-serializable values (e.g., RSC\n * `ReactNode` trees from `@real-router/rsc-server-plugin`).\n *\n * @example\n * ```typescript\n * // Server\n * const state = await router.start(req.url);\n * const html = `<script>window.__SSR_STATE__=${serializeRouterState(state)}</script>`;\n *\n * // Client\n * await hydrateRouter(router, window.__SSR_STATE__);\n * ```\n *\n * @example\n * ```typescript\n * // With RSC plugin: strip the \"rsc\" namespace before transport\n * const state = await router.start(url);\n * const json = serializeRouterState(state, { excludeContext: [\"rsc\"] });\n * ```\n *\n * @example\n * ```typescript\n * // Non-JSON types (Date / Map / Set / RegExp / BigInt) via devalue (#606)\n * import * as devalue from \"devalue\";\n *\n * const json = serializeRouterState(state, { serialize: devalue.stringify });\n * // On the client:\n * await hydrateRouter(router, json, { deserialize: devalue.parse });\n * ```\n */\nexport function serializeRouterState(\n state: State,\n options?: SerializeRouterStateOptions,\n): string {\n const exclude = options?.excludeContext;\n\n let context = state.context;\n\n if (exclude?.length) {\n // Null-proto target so a literal \"__proto__\" namespace (a real own key on\n // state.context, e.g. written by claimContextNamespace) is copied as a\n // genuine own entry by the plain assignment below — a `{}` target would\n // instead dispatch into the inherited Object.prototype.__proto__ setter and\n // silently drop the data (#1191, same hazard the write path guards).\n const filtered: Record<string, unknown> = Object.create(null) as Record<\n string,\n unknown\n >;\n const source = state.context;\n\n for (const [key, value] of Object.entries(source)) {\n if (!exclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n context = filtered;\n }\n\n const payload = {\n name: state.name,\n params: state.params,\n path: state.path,\n context,\n };\n\n return options?.serialize\n ? serializeState(payload, { serialize: options.serialize })\n : serializeState(payload);\n}\n"],"mappings":"6FAkDA,SAAS,EAAc,EAAqD,CAC1E,MACE,WAAY,GACZ,OAAQ,EAAiC,QAAW,UACnD,EAAiC,SAAW,IAAA,IAC7C,OAAO,EAAQ,OAAO,SAAY,SAEtC,CAqEA,SAAgB,EAGd,EACA,EACA,EAC4B,CAC5B,IAAI,EACA,EACA,EAEJ,GAAI,EAAc,CAAO,EACvB,EAAS,EAAQ,WACZ,CACL,IAAM,EAAa,IAAI,gBACjB,MAAsB,CAC1B,EAAW,MAAM,CACnB,EAEA,EAAS,EAAW,OAOpB,MAAe,CACb,EAAQ,GAAG,QAAS,CAAO,CAC7B,EACA,MAAe,CACb,EAAQ,iBAAiB,QAAS,CAAO,CAC3C,CACF,CAEA,IAAM,EAAS,EAAY,EAAM,CAC/B,GAAG,EACH,YAAa,CACf,CAAiB,EAIjB,IAAS,EAET,IAAI,EAAW,GAET,MACA,EACK,QAAQ,QAAQ,GAGzB,EAAW,GACX,IAAS,EACT,EAAO,QAAQ,EAER,QAAQ,QAAQ,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AU,GAAS,eAErB,EAAU,EAAM,QAEpB,GAAI,GAAS,OAAQ,CAMnB,IAAM,EAAoC,OAAO,OAAO,IAAI,EAItD,EAAS,EAAM,QAErB,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EACzC,EAAQ,SAAS,CAAG,IACvB,EAAS,GAAO,GAIpB,EAAU,CACZ,CAEA,IAAM,EAAU,CACd,KAAM,EAAM,KACZ,OAAQ,EAAM,OACd,KAAM,EAAM,KACZ,SACF,EAEA,OAAO,GAAS,UACZ,EAAe,EAAS,CAAE,UAAW,EAAQ,SAAU,CAAC,EACxD,EAAe,CAAO,CAC5B"}
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require("./Router-BX-JArfJ.js"),t=require("./esm-BIeQwCN9.js");function n(t){if(t())throw new e.n(e.C.ROUTER_DISPOSED)}function r(t){if(t())throw new e.n(e.C.REENTRANT_TREE_MUTATION)}const i=new WeakMap;function a(r){let a=i.get(r);if(a)return a;let o=t.l(r),s={makeState:(e,t,n,r)=>(o.validator?.state.validateMakeStateArgs(e,t,n),o.makeState(e,t,n,r?.params)),buildState:(e,t)=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=o.forwardState(e,t);return o.buildStateResolved(n,r)},forwardState:(e,t)=>(o.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),o.forwardState(e,t)),matchPath:e=>(o.validator?.routes.validateMatchPathArgs(e),o.matchPath(e,o.getOptions())),navigateToState:(e,t)=>(n(o.isDisposed),o.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&o.validator?.navigation.validateNavigationOptions(t,`navigateToState`),o.navigateToState(e,t)),setRootPath:e=>{n(o.isDisposed),o.validator?.routes.validateSetRootPathArgs(e),o.setRootPath(e)},getRootPath:o.getRootPath,addEventListener:(e,t)=>(n(o.isDisposed),o.validator?.eventBus.validateListenerArgs(e,t),o.addEventListener(e,t)),buildNavigationState:(e,t={})=>{o.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=o.forwardState(e,t),i=o.buildStateResolved(n,r);if(i)return o.makeState(i.name,i.params,o.buildPath(i.name,i.params),i.meta)},getOptions:o.getOptions,getTree:o.getTree,addInterceptor:(e,t)=>{n(o.isDisposed),o.validator?.plugins.validateAddInterceptorArgs(e,t);let r=o.interceptors.get(e);r||(r=[],o.interceptors.set(e,r)),r.push(t);let i=!1;return()=>{i||(i=!0,r.splice(r.indexOf(t),1))}},getRouteConfig:e=>{let t=o.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:t=>{n(o.isDisposed);let i=Object.keys(t);for(let t of i)if(t in r)throw new e.n(e.C.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${t}" already exists`});for(let e of i)r[e]=t[e];let a={keys:i};o.routerExtensions.push(a);let s=!1;return()=>{if(s)return;s=!0;for(let e of a.keys)delete r[e];let e=o.routerExtensions.indexOf(a);e!==-1&&o.routerExtensions.splice(e,1)}},emitTransitionError:e=>{n(o.isDisposed),o.emitTransitionError(e)},claimContextNamespace:t=>{if(n(o.isDisposed),o.contextClaimRecords.has(t))throw new e.n(e.C.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return o.contextClaimRecords.add(t),{write(e,n){e.context[t]=n},release(){o.contextClaimRecords.delete(t)}}}};return i.set(r,s),s}function o(e){let r=t.l(e),i=r.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addActivateGuard`),r.validator?.lifecycle.validateHandler(t,`addActivateGuard`),i.addCanActivate(e,t)},addDeactivateGuard(e,t){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`addDeactivateGuard`),r.validator?.lifecycle.validateHandler(t,`addDeactivateGuard`),i.addCanDeactivate(e,t)},removeActivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeActivateGuard`),i.clearCanActivate(e,`external`)},removeDeactivateGuard(e){n(r.isDisposed),r.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),i.clearCanDeactivate(e,`external`)}}}function s(n,r){let i=t.l(n);if(i.isDisposed())throw new e.n(e.C.ROUTER_DISPOSED);i.validator?.dependencies.validateCloneArgs(r);let a=i.routeGetStore(),s=t.r(a.tree),c=a.config,l=a.resolvedForwardMap,u=a.routeCustomFields,{options:d,dependencies:f,pluginFactories:p}=i.getCloneState(),{definition:m,external:h}=a.lifecycleNamespace.getFactoriesByOrigin(),g=new e.t(s,d,{...f,...r}),_=t.l(g),v=_.routeGetStore(),y=v.lifecycleNamespace;e._(v.config,c),Object.assign(v.resolvedForwardMap,l),Object.assign(v.routeCustomFields,u),a.rootPath!==``&&_.setRootPath(a.rootPath);let[b,x]=m,[S,C]=h;for(let[e,t]of Object.entries(b))y.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(x))y.addCanActivate(e,t,!0);let w=o(g);for(let[e,t]of Object.entries(S))w.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(C))w.addActivateGuard(e,t);let T=new Set(_.getCloneState().pluginFactories),E=p.filter(e=>!T.has(e));return E.length>0&&g.usePlugin(...E),g}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
2
|
-
//# sourceMappingURL=cloneRouter-SIYSVozu.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloneRouter-SIYSVozu.js","names":["RouterError","errorCodes","getInternals","RouterError","errorCodes","getInternals","getInternals","RouterError","errorCodes","routeTreeToDefinitions","RouterClass"],"sources":["../../src/api/helpers.ts","../../src/api/getPluginApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.ts"],"sourcesContent":["// packages/core/src/api/helpers.ts\n\nimport { errorCodes } from \"../constants\";\nimport { RouterError } from \"../RouterError\";\n\nexport function throwIfDisposed(isDisposed: () => boolean): void {\n if (isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n}\n\n/**\n * Bans synchronous reentrant route-CRUD: a CRUD op called while a `TREE_CHANGED`\n * emit is on the stack (i.e. from inside a `subscribeChanges` handler) throws\n * `REENTRANT_TREE_MUTATION` BEFORE mutating — the tree stays atomic (#1032).\n * Deferred CRUD (`queueMicrotask` / `await`) runs after the dispatch settles and\n * is unaffected; CRUD from a transition listener is not a TREE_CHANGED dispatch.\n */\nexport function throwIfReentrantTreeMutation(isEmitting: () => boolean): void {\n if (isEmitting()) {\n throw new RouterError(errorCodes.REENTRANT_TREE_MUTATION);\n }\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n State,\n} from \"@real-router/types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\n makeState: (name, params, path, meta) => {\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n return ctx.makeState(\n name,\n params,\n path,\n meta?.params as\n Record<string, Record<string, \"url\" | \"query\">> | undefined,\n );\n },\n buildState: (routeName, routeParams) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"buildState\",\n );\n\n const { name, params } = ctx.forwardState(routeName, routeParams);\n\n return ctx.buildStateResolved(name, params);\n },\n forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState(routeName, routeParams);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\n },\n setRootPath: (rootPath) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateSetRootPathArgs(rootPath);\n\n ctx.setRootPath(rootPath);\n },\n getRootPath: ctx.getRootPath,\n addEventListener: (eventName, cb) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.eventBus.validateListenerArgs(eventName, cb);\n\n return ctx.addEventListener(eventName, cb);\n },\n buildNavigationState: (name, params = {}) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params,\n );\n const routeInfo = ctx.buildStateResolved(resolvedName, resolvedParams);\n\n if (!routeInfo) {\n return;\n }\n\n return ctx.makeState(\n routeInfo.name,\n routeInfo.params,\n ctx.buildPath(routeInfo.name, routeInfo.params),\n routeInfo.meta,\n );\n },\n getOptions: ctx.getOptions,\n getTree: ctx.getTree,\n addInterceptor: (method, fn) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.validator?.plugins.validateAddInterceptorArgs(method, fn);\n let list = ctx.interceptors.get(method);\n\n if (!list) {\n list = [];\n ctx.interceptors.set(method, list);\n }\n\n list.push(fn);\n\n // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n return store.routeCustomFields[name];\n },\n extendRouter: (extensions: Record<string, unknown>) => {\n throwIfDisposed(ctx.isDisposed);\n\n const keys = Object.keys(extensions);\n\n for (const key of keys) {\n if (key in router) {\n throw new RouterError(errorCodes.PLUGIN_CONFLICT, {\n message: `Cannot extend router: property \"${key}\" already exists`,\n });\n }\n }\n\n for (const key of keys) {\n (router as Record<string, unknown>)[key] = extensions[key];\n }\n\n const extensionRecord = { keys };\n\n ctx.routerExtensions.push(extensionRecord);\n\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n\n for (const key of extensionRecord.keys) {\n delete (router as Record<string, unknown>)[key];\n }\n\n const idx = ctx.routerExtensions.indexOf(extensionRecord);\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n state.context[namespace] = value;\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { LifecycleApi } from \"./types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\nexport function getLifecycleApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): LifecycleApi<Dependencies> {\n const ctx = getInternals(router);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycleNamespace = ctx.routeGetStore().lifecycleNamespace!;\n\n return {\n addActivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addActivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addActivateGuard\");\n\n // Handler-limit enforcement lives at the namespace registration choke point\n // (RouteLifecycleNamespace.#registerHandler) so all paths are bounded\n // uniformly — see #961.\n lifecycleNamespace.addCanActivate(name, handler);\n },\n\n addDeactivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addDeactivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addDeactivateGuard\");\n\n lifecycleNamespace.addCanDeactivate(name, handler);\n },\n\n removeActivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeActivateGuard\");\n\n // Inverse of addActivateGuard (external): clears only the external guard;\n // a route-config (definition) canActivate survives (#1171).\n lifecycleNamespace.clearCanActivate(name, \"external\");\n },\n\n removeDeactivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeDeactivateGuard\");\n\n // Inverse of addDeactivateGuard (external): clears only the external guard;\n // a route-config (definition) canDeactivate survives (#1171).\n lifecycleNamespace.clearCanDeactivate(name, \"external\");\n },\n };\n}\n","import { routeTreeToDefinitions } from \"route-tree\";\n\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { assignConfigEntries } from \"../namespaces/RoutesNamespace/helpers\";\nimport { Router as RouterClass } from \"../Router\";\nimport { RouterError } from \"../RouterError\";\nimport { getLifecycleApi } from \"./getLifecycleApi\";\n\nimport type { Route } from \"../types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Build an independent router instance that shares the route tree, options,\n * lifecycle guards, and plugin factories of `router`. The primary use case\n * is **SSR multi-tenancy** — one base router per process, one clone per\n * request.\n *\n * @param router - Source router (must not be disposed).\n * @param dependencies - Optional per-clone overrides merged on top of the\n * base router's dependencies. Always **fresh per call** in the documented\n * SSR pattern: pass per-request state here, never store it in the base.\n *\n * @remarks\n *\n * **Dependency merge — shallow by design.** `base.dependencies` are spread\n * into the clone via `{ ...sourceDeps, ...dependencies }`. Top-level keys\n * are new objects, but **values are shared by reference**: a `Map`, `Set`,\n * class instance, function, or nested plain object stored in\n * `base.dependencies` is the **same instance** in every clone. Mutations\n * in one clone are visible in the base and in every sibling clone.\n *\n * This is intentional. `structuredClone` of dep values is **not** applied\n * because it would:\n * - strip class prototypes (`new DbClient()` → plain object, methods lost)\n * - reject functions and symbols (`DataCloneError`)\n * - fragment singleton pools (one connection pool per request — pool\n * semantics destroyed)\n * - reject circular references\n *\n * **SSR rule of thumb.** Place values in `base.dependencies` according to\n * their lifecycle:\n *\n * - **Singletons / shared services** → `base.dependencies`. Examples: DB\n * client, connection pool, logger, config, feature-flag client. Process-\n * wide pooling depends on sharing these by reference.\n * - **Per-request state** → the `dependencies` override parameter (or\n * `createRequestScope`'s `deps` argument). Examples: `currentUser`,\n * `traceId`, `sessionId`, `abortSignal`. The override is applied last,\n * so it wins over base keys; pass a fresh object per call.\n *\n * Cross-request data leaks are **only possible** when per-request mutable\n * state is incorrectly placed in `base.dependencies`. The override slot is\n * the safe channel.\n *\n * @example\n * ```typescript\n * // Server boot — singletons only\n * const base = createRouter(routes, options, {\n * db: new DbClient(dbUrl),\n * logger,\n * });\n *\n * // Per request — fresh override per call\n * const clone = cloneRouter(base, {\n * currentUser,\n * traceId,\n * });\n * // clone.deps.db === base.deps.db ✓ shared pool (intentional)\n * // clone.deps.currentUser ✓ unique per request\n * ```\n *\n * @see createRequestScope — `@real-router/core/utils` SSR helper that\n * wraps this function and injects `abortSignal` automatically.\n */\nexport function cloneRouter<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n dependencies?: Dependencies,\n): RouterClass<Dependencies> {\n const ctx = getInternals(router);\n\n if (ctx.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n ctx.validator?.dependencies.validateCloneArgs(dependencies);\n\n // Get source store directly\n const sourceStore = ctx.routeGetStore();\n const routes = routeTreeToDefinitions(sourceStore.tree);\n const routeConfig = sourceStore.config;\n const resolvedForwardMap = sourceStore.resolvedForwardMap;\n const routeCustomFields = sourceStore.routeCustomFields;\n\n const {\n options,\n dependencies: sourceDeps,\n pluginFactories,\n } = ctx.getCloneState();\n // Origin-aware factory snapshot — definition guards are re-registered with\n // `isFromDefinition=true` on the clone so `replace()` can still strip them\n // via `clearDefinitionGuards()`. External guards take the public lifecycle\n // API path so they survive `replace()` symmetric with the base.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const sourceLifecycleNamespace = sourceStore.lifecycleNamespace!;\n const { definition: definitionFactories, external: externalFactories } =\n sourceLifecycleNamespace.getFactoriesByOrigin();\n\n const mergedDeps = {\n ...sourceDeps,\n ...dependencies,\n } as Dependencies;\n\n const newRouter = new RouterClass<Dependencies>(\n routes as Route<Dependencies>[],\n options,\n mergedDeps,\n );\n\n const newCtx = getInternals(newRouter);\n const newStore = newCtx.routeGetStore();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const newLifecycleNamespace = newStore.lifecycleNamespace!;\n\n // Copy the source config + store-level maps BEFORE re-registering guards\n // (#1331 review): the definition-guard factories re-executed below must\n // observe the fully-built clone (encoders/decoders/defaultParams/custom\n // fields), mirroring the constructor where flushPendingGuards runs after the\n // store is complete. The five RouteConfig sub-maps go through a single\n // enumeration so a newly added config field is carried over automatically\n // (#965); resolvedForwardMap and routeCustomFields are store-level (not part\n // of RouteConfig) and stay explicit.\n assignConfigEntries(newStore.config, routeConfig);\n Object.assign(newStore.resolvedForwardMap, resolvedForwardMap);\n Object.assign(newStore.routeCustomFields, routeCustomFields);\n\n // #1175: carry the source rootPath. It lives in the store (not options/config),\n // and neither routeTreeToDefinitions nor getCloneState include it — so a clone\n // of a base configured with `setRootPath(\"/app\")` would otherwise build/match\n // under \"\" and 404 every request of a sub-path SSR deployment. setRootPath\n // rebuilds the tree in place with the just-copied config; the rebuild is only\n // paid when a rootPath is actually set, and it runs before the definition-guard\n // factories below so they observe the fully-built clone (rootPath included).\n if (sourceStore.rootPath !== \"\") {\n newCtx.setRootPath(sourceStore.rootPath);\n }\n\n const [definitionDeactivate, definitionActivate] = definitionFactories;\n const [externalDeactivate, externalActivate] = externalFactories;\n\n for (const [name, handler] of Object.entries(definitionDeactivate)) {\n newLifecycleNamespace.addCanDeactivate(name, handler, true);\n }\n\n for (const [name, handler] of Object.entries(definitionActivate)) {\n newLifecycleNamespace.addCanActivate(name, handler, true);\n }\n\n const lifecycle = getLifecycleApi(newRouter);\n\n for (const [name, handler] of Object.entries(externalDeactivate)) {\n lifecycle.addDeactivateGuard(name, handler);\n }\n\n for (const [name, handler] of Object.entries(externalActivate)) {\n lifecycle.addActivateGuard(name, handler);\n }\n\n // Plugin replay runs last and skips factories that a (contract-violating)\n // definition-guard factory already registered on the clone during the\n // re-compilation above — without the filter every clone would double-apply\n // such a plugin: once via the factory, once via this replay (#1331 review).\n const alreadyRegistered = new Set(newCtx.getCloneState().pluginFactories);\n const pluginsToReplay = pluginFactories.filter(\n (factory) => !alreadyRegistered.has(factory),\n );\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `usePlugin(...[])` with an empty spread is a no-op, so entering the block on an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips a real plugin list and is killable.)\n if (pluginsToReplay.length > 0) {\n newRouter.usePlugin(...pluginsToReplay);\n }\n\n return newRouter;\n}\n"],"mappings":"uEAKA,SAAgB,EAAgB,EAAiC,CAC/D,GAAI,EAAW,EACb,MAAM,IAAIA,EAAAA,EAAYC,EAAAA,EAAW,eAAe,CAEpD,CASA,SAAgB,EAA6B,EAAiC,CAC5E,GAAI,EAAW,EACb,MAAM,IAAID,EAAAA,EAAYC,EAAAA,EAAW,uBAAuB,CAE5D,CCFA,MAAM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAAM,IAAI,CAAM,EAE/B,GAAI,EACF,OAAO,EAGT,IAAM,EAAMC,EAAAA,EAAa,CAAM,EACzB,EAAiB,CACrB,WAAY,EAAM,EAAQ,EAAM,KAC9B,EAAI,WAAW,MAAM,sBAAsB,EAAM,EAAQ,CAAI,EAEtD,EAAI,UACT,EACA,EACA,EACA,GAAM,MAER,GAEF,YAAa,EAAW,IAAgB,CACtC,EAAI,WAAW,OAAO,yBACpB,EACA,EACA,YACF,EAEA,GAAM,CAAE,OAAM,UAAW,EAAI,aAAa,EAAW,CAAW,EAEhE,OAAO,EAAI,mBAAmB,EAAM,CAAM,CAC5C,EACA,cACE,EACA,KAEA,EAAI,WAAW,OAAO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J,EAAAA,EAAa,CAAS,EAC/B,EAAW,EAAO,cAAc,EAEhC,EAAwB,EAAS,mBAUvC,EAAA,EAAoB,EAAS,OAAQ,CAAW,EAChD,OAAO,OAAO,EAAS,mBAAoB,CAAkB,EAC7D,OAAO,OAAO,EAAS,kBAAmB,CAAiB,EASvD,EAAY,WAAa,IAC3B,EAAO,YAAY,EAAY,QAAQ,EAGzC,GAAM,CAAC,EAAsB,GAAsB,EAC7C,CAAC,EAAoB,GAAoB,EAE/C,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAoB,EAC/D,EAAsB,iBAAiB,EAAM,EAAS,EAAI,EAG5D,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAkB,EAC7D,EAAsB,eAAe,EAAM,EAAS,EAAI,EAG1D,IAAM,EAAY,EAAgB,CAAS,EAE3C,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAkB,EAC7D,EAAU,mBAAmB,EAAM,CAAO,EAG5C,IAAK,GAAM,CAAC,EAAM,KAAY,OAAO,QAAQ,CAAgB,EAC3D,EAAU,iBAAiB,EAAM,CAAO,EAO1C,IAAM,EAAoB,IAAI,IAAI,EAAO,cAAc,CAAC,CAAC,eAAe,EAClE,EAAkB,EAAgB,OACrC,GAAY,CAAC,EAAkB,IAAI,CAAO,CAC7C,EAOA,OAJI,EAAgB,OAAS,GAC3B,EAAU,UAAU,GAAG,CAAe,EAGjC,CACT"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{C as e,_ as t,n,t as r}from"./Router-07LbiPS7.mjs";import{l as i,r as a}from"./esm-CLeBo4Hk.mjs";function o(t){if(t())throw new n(e.ROUTER_DISPOSED)}function s(t){if(t())throw new n(e.REENTRANT_TREE_MUTATION)}const c=new WeakMap;function l(t){let r=c.get(t);if(r)return r;let a=i(t),s={makeState:(e,t,n,r)=>(a.validator?.state.validateMakeStateArgs(e,t,n),a.makeState(e,t,n,r?.params)),buildState:(e,t)=>{a.validator?.routes.validateStateBuilderArgs(e,t,`buildState`);let{name:n,params:r}=a.forwardState(e,t);return a.buildStateResolved(n,r)},forwardState:(e,t)=>(a.validator?.routes.validateStateBuilderArgs(e,t,`forwardState`),a.forwardState(e,t)),matchPath:e=>(a.validator?.routes.validateMatchPathArgs(e),a.matchPath(e,a.getOptions())),navigateToState:(e,t)=>(o(a.isDisposed),a.validator?.navigation.validateNavigateToStateArgs(e),t!==void 0&&a.validator?.navigation.validateNavigationOptions(t,`navigateToState`),a.navigateToState(e,t)),setRootPath:e=>{o(a.isDisposed),a.validator?.routes.validateSetRootPathArgs(e),a.setRootPath(e)},getRootPath:a.getRootPath,addEventListener:(e,t)=>(o(a.isDisposed),a.validator?.eventBus.validateListenerArgs(e,t),a.addEventListener(e,t)),buildNavigationState:(e,t={})=>{a.validator?.routes.validateStateBuilderArgs(e,t,`buildNavigationState`);let{name:n,params:r}=a.forwardState(e,t),i=a.buildStateResolved(n,r);if(i)return a.makeState(i.name,i.params,a.buildPath(i.name,i.params),i.meta)},getOptions:a.getOptions,getTree:a.getTree,addInterceptor:(e,t)=>{o(a.isDisposed),a.validator?.plugins.validateAddInterceptorArgs(e,t);let n=a.interceptors.get(e);n||(n=[],a.interceptors.set(e,n)),n.push(t);let r=!1;return()=>{r||(r=!0,n.splice(n.indexOf(t),1))}},getRouteConfig:e=>{let t=a.routeGetStore();if(t.matcher.hasRoute(e))return t.routeCustomFields[e]},extendRouter:r=>{o(a.isDisposed);let i=Object.keys(r);for(let r of i)if(r in t)throw new n(e.PLUGIN_CONFLICT,{message:`Cannot extend router: property "${r}" already exists`});for(let e of i)t[e]=r[e];let s={keys:i};a.routerExtensions.push(s);let c=!1;return()=>{if(c)return;c=!0;for(let e of s.keys)delete t[e];let e=a.routerExtensions.indexOf(s);e!==-1&&a.routerExtensions.splice(e,1)}},emitTransitionError:e=>{o(a.isDisposed),a.emitTransitionError(e)},claimContextNamespace:t=>{if(o(a.isDisposed),a.contextClaimRecords.has(t))throw new n(e.CONTEXT_NAMESPACE_ALREADY_CLAIMED,{message:`Cannot claim context namespace: "${t}" is already claimed by another plugin`});return a.contextClaimRecords.add(t),{write(e,n){e.context[t]=n},release(){a.contextClaimRecords.delete(t)}}}};return c.set(t,s),s}function u(e){let t=i(e),n=t.routeGetStore().lifecycleNamespace;return{addActivateGuard(e,r){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`addActivateGuard`),t.validator?.lifecycle.validateHandler(r,`addActivateGuard`),n.addCanActivate(e,r)},addDeactivateGuard(e,r){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`addDeactivateGuard`),t.validator?.lifecycle.validateHandler(r,`addDeactivateGuard`),n.addCanDeactivate(e,r)},removeActivateGuard(e){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`removeActivateGuard`),n.clearCanActivate(e,`external`)},removeDeactivateGuard(e){o(t.isDisposed),t.validator?.routes.validateRouteName(e,`removeDeactivateGuard`),n.clearCanDeactivate(e,`external`)}}}function d(o,s){let c=i(o);if(c.isDisposed())throw new n(e.ROUTER_DISPOSED);c.validator?.dependencies.validateCloneArgs(s);let l=c.routeGetStore(),d=a(l.tree),f=l.config,p=l.resolvedForwardMap,m=l.routeCustomFields,{options:h,dependencies:g,pluginFactories:_}=c.getCloneState(),{definition:v,external:y}=l.lifecycleNamespace.getFactoriesByOrigin(),b=new r(d,h,{...g,...s}),x=i(b),S=x.routeGetStore(),C=S.lifecycleNamespace;t(S.config,f),Object.assign(S.resolvedForwardMap,p),Object.assign(S.routeCustomFields,m),l.rootPath!==``&&x.setRootPath(l.rootPath);let[w,T]=v,[E,D]=y;for(let[e,t]of Object.entries(w))C.addCanDeactivate(e,t,!0);for(let[e,t]of Object.entries(T))C.addCanActivate(e,t,!0);let O=u(b);for(let[e,t]of Object.entries(E))O.addDeactivateGuard(e,t);for(let[e,t]of Object.entries(D))O.addActivateGuard(e,t);let k=new Set(x.getCloneState().pluginFactories),A=_.filter(e=>!k.has(e));return A.length>0&&b.usePlugin(...A),b}export{s as a,o as i,u as n,l as r,d as t};
|
|
2
|
-
//# sourceMappingURL=cloneRouter-DEU1GjSY.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cloneRouter-DEU1GjSY.mjs","names":["routeTreeToDefinitions","RouterClass"],"sources":["../../src/api/helpers.ts","../../src/api/getPluginApi.ts","../../src/api/getLifecycleApi.ts","../../src/api/cloneRouter.ts"],"sourcesContent":["// packages/core/src/api/helpers.ts\n\nimport { errorCodes } from \"../constants\";\nimport { RouterError } from \"../RouterError\";\n\nexport function throwIfDisposed(isDisposed: () => boolean): void {\n if (isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n}\n\n/**\n * Bans synchronous reentrant route-CRUD: a CRUD op called while a `TREE_CHANGED`\n * emit is on the stack (i.e. from inside a `subscribeChanges` handler) throws\n * `REENTRANT_TREE_MUTATION` BEFORE mutating — the tree stays atomic (#1032).\n * Deferred CRUD (`queueMicrotask` / `await`) runs after the dispatch settles and\n * is unaffected; CRUD from a transition listener is not a TREE_CHANGED dispatch.\n */\nexport function throwIfReentrantTreeMutation(isEmitting: () => boolean): void {\n if (isEmitting()) {\n throw new RouterError(errorCodes.REENTRANT_TREE_MUTATION);\n }\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { RouterError } from \"../RouterError\";\n\nimport type { PluginApi } from \"./types\";\nimport type {\n ContextNamespaceClaim,\n DefaultDependencies,\n Params,\n Router,\n State,\n} from \"@real-router/types\";\n\n// Cache the assembled PluginApi per router — mirrors getNavigator() (#525):\n// avoids re-allocating the closure-bag on each call (plugins call this once\n// at init, but tests + nested plugins poll it), and gives spy/stub helpers\n// a stable object identity to attach to (e.g. spying on\n// `getPluginApi(router).navigateToState` to inject errors in popstate\n// recovery tests).\nconst cache = new WeakMap<object, PluginApi>();\n\nexport function getPluginApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): PluginApi {\n const cached = cache.get(router);\n\n if (cached) {\n return cached;\n }\n\n const ctx = getInternals(router);\n const api: PluginApi = {\n makeState: (name, params, path, meta) => {\n ctx.validator?.state.validateMakeStateArgs(name, params, path);\n\n return ctx.makeState(\n name,\n params,\n path,\n meta?.params as\n Record<string, Record<string, \"url\" | \"query\">> | undefined,\n );\n },\n buildState: (routeName, routeParams) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"buildState\",\n );\n\n const { name, params } = ctx.forwardState(routeName, routeParams);\n\n return ctx.buildStateResolved(name, params);\n },\n forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n routeName,\n routeParams,\n \"forwardState\",\n );\n\n return ctx.forwardState(routeName, routeParams);\n },\n matchPath: (path) => {\n ctx.validator?.routes.validateMatchPathArgs(path);\n\n return ctx.matchPath(path, ctx.getOptions());\n },\n navigateToState: (state, options) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.navigation.validateNavigateToStateArgs(state);\n\n if (options !== undefined) {\n ctx.validator?.navigation.validateNavigationOptions(\n options,\n \"navigateToState\",\n );\n }\n\n return ctx.navigateToState(state, options);\n },\n setRootPath: (rootPath) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateSetRootPathArgs(rootPath);\n\n ctx.setRootPath(rootPath);\n },\n getRootPath: ctx.getRootPath,\n addEventListener: (eventName, cb) => {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.eventBus.validateListenerArgs(eventName, cb);\n\n return ctx.addEventListener(eventName, cb);\n },\n buildNavigationState: (name, params = {}) => {\n ctx.validator?.routes.validateStateBuilderArgs(\n name,\n params,\n \"buildNavigationState\",\n );\n\n const { name: resolvedName, params: resolvedParams } = ctx.forwardState(\n name,\n params,\n );\n const routeInfo = ctx.buildStateResolved(resolvedName, resolvedParams);\n\n if (!routeInfo) {\n return;\n }\n\n return ctx.makeState(\n routeInfo.name,\n routeInfo.params,\n ctx.buildPath(routeInfo.name, routeInfo.params),\n routeInfo.meta,\n );\n },\n getOptions: ctx.getOptions,\n getTree: ctx.getTree,\n addInterceptor: (method, fn) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.validator?.plugins.validateAddInterceptorArgs(method, fn);\n let list = ctx.interceptors.get(method);\n\n if (!list) {\n list = [];\n ctx.interceptors.set(method, list);\n }\n\n list.push(fn);\n\n // Idempotency flag (#1198). Without it, a double call would `indexOf(fn)`\n // again and splice a DUPLICATE registration of the same fn — silently\n // deactivating another plugin's interceptor whose own unsubscribe was never\n // called. The `Unsubscribe` contract is documented idempotent. The flag\n // guarantees exactly one splice of a still-present `fn`, so no `index !== -1`\n // guard is needed (it would be dead — the second call returns above).\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n list.splice(list.indexOf(fn), 1);\n };\n },\n getRouteConfig: (name) => {\n const store = ctx.routeGetStore();\n\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — a missing route yields routeCustomFields[name] === undefined, identical to this early return\n if (!store.matcher.hasRoute(name)) {\n return;\n }\n\n return store.routeCustomFields[name];\n },\n extendRouter: (extensions: Record<string, unknown>) => {\n throwIfDisposed(ctx.isDisposed);\n\n const keys = Object.keys(extensions);\n\n for (const key of keys) {\n if (key in router) {\n throw new RouterError(errorCodes.PLUGIN_CONFLICT, {\n message: `Cannot extend router: property \"${key}\" already exists`,\n });\n }\n }\n\n for (const key of keys) {\n (router as Record<string, unknown>)[key] = extensions[key];\n }\n\n const extensionRecord = { keys };\n\n ctx.routerExtensions.push(extensionRecord);\n\n let removed = false;\n\n return () => {\n if (removed) {\n return;\n }\n\n removed = true;\n\n for (const key of extensionRecord.keys) {\n delete (router as Record<string, unknown>)[key];\n }\n\n const idx = ctx.routerExtensions.indexOf(extensionRecord);\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,UnaryOperator,BlockStatement: equivalent — this splice only tidies the `routerExtensions` TRACKING array; the router INSTANCE is cleaned by the `delete router[key]` loop above, and dispose()'s safety-net re-deletes any leaked key harmlessly. So no mutation of this guard/splice is behaviourally observable (full suite green with `===`, `+1`, and an empty body). Contrast the addInterceptor splice, which IS observable through buildPath and is killed behaviourally by invariantGuardMutants.test.ts.\n if (idx !== -1) {\n ctx.routerExtensions.splice(idx, 1);\n }\n };\n },\n emitTransitionError: (error) => {\n throwIfDisposed(ctx.isDisposed);\n ctx.emitTransitionError(error);\n },\n claimContextNamespace: (namespace: string) => {\n throwIfDisposed(ctx.isDisposed);\n\n if (ctx.contextClaimRecords.has(namespace)) {\n throw new RouterError(errorCodes.CONTEXT_NAMESPACE_ALREADY_CLAIMED, {\n message: `Cannot claim context namespace: \"${namespace}\" is already claimed by another plugin`,\n });\n }\n\n ctx.contextClaimRecords.add(namespace);\n\n return {\n write(state: State, value: unknown) {\n state.context[namespace] = value;\n },\n release() {\n ctx.contextClaimRecords.delete(namespace);\n },\n } satisfies ContextNamespaceClaim;\n },\n };\n\n cache.set(router, api);\n\n return api;\n}\n","import { throwIfDisposed } from \"./helpers\";\nimport { getInternals } from \"../internals\";\n\nimport type { LifecycleApi } from \"./types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\nexport function getLifecycleApi<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): LifecycleApi<Dependencies> {\n const ctx = getInternals(router);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const lifecycleNamespace = ctx.routeGetStore().lifecycleNamespace!;\n\n return {\n addActivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addActivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addActivateGuard\");\n\n // Handler-limit enforcement lives at the namespace registration choke point\n // (RouteLifecycleNamespace.#registerHandler) so all paths are bounded\n // uniformly — see #961.\n lifecycleNamespace.addCanActivate(name, handler);\n },\n\n addDeactivateGuard(name, handler) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"addDeactivateGuard\");\n ctx.validator?.lifecycle.validateHandler(handler, \"addDeactivateGuard\");\n\n lifecycleNamespace.addCanDeactivate(name, handler);\n },\n\n removeActivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeActivateGuard\");\n\n // Inverse of addActivateGuard (external): clears only the external guard;\n // a route-config (definition) canActivate survives (#1171).\n lifecycleNamespace.clearCanActivate(name, \"external\");\n },\n\n removeDeactivateGuard(name) {\n throwIfDisposed(ctx.isDisposed);\n\n ctx.validator?.routes.validateRouteName(name, \"removeDeactivateGuard\");\n\n // Inverse of addDeactivateGuard (external): clears only the external guard;\n // a route-config (definition) canDeactivate survives (#1171).\n lifecycleNamespace.clearCanDeactivate(name, \"external\");\n },\n };\n}\n","import { routeTreeToDefinitions } from \"route-tree\";\n\nimport { errorCodes } from \"../constants\";\nimport { getInternals } from \"../internals\";\nimport { assignConfigEntries } from \"../namespaces/RoutesNamespace/helpers\";\nimport { Router as RouterClass } from \"../Router\";\nimport { RouterError } from \"../RouterError\";\nimport { getLifecycleApi } from \"./getLifecycleApi\";\n\nimport type { Route } from \"../types\";\nimport type { DefaultDependencies, Router } from \"@real-router/types\";\n\n/**\n * Build an independent router instance that shares the route tree, options,\n * lifecycle guards, and plugin factories of `router`. The primary use case\n * is **SSR multi-tenancy** — one base router per process, one clone per\n * request.\n *\n * @param router - Source router (must not be disposed).\n * @param dependencies - Optional per-clone overrides merged on top of the\n * base router's dependencies. Always **fresh per call** in the documented\n * SSR pattern: pass per-request state here, never store it in the base.\n *\n * @remarks\n *\n * **Dependency merge — shallow by design.** `base.dependencies` are spread\n * into the clone via `{ ...sourceDeps, ...dependencies }`. Top-level keys\n * are new objects, but **values are shared by reference**: a `Map`, `Set`,\n * class instance, function, or nested plain object stored in\n * `base.dependencies` is the **same instance** in every clone. Mutations\n * in one clone are visible in the base and in every sibling clone.\n *\n * This is intentional. `structuredClone` of dep values is **not** applied\n * because it would:\n * - strip class prototypes (`new DbClient()` → plain object, methods lost)\n * - reject functions and symbols (`DataCloneError`)\n * - fragment singleton pools (one connection pool per request — pool\n * semantics destroyed)\n * - reject circular references\n *\n * **SSR rule of thumb.** Place values in `base.dependencies` according to\n * their lifecycle:\n *\n * - **Singletons / shared services** → `base.dependencies`. Examples: DB\n * client, connection pool, logger, config, feature-flag client. Process-\n * wide pooling depends on sharing these by reference.\n * - **Per-request state** → the `dependencies` override parameter (or\n * `createRequestScope`'s `deps` argument). Examples: `currentUser`,\n * `traceId`, `sessionId`, `abortSignal`. The override is applied last,\n * so it wins over base keys; pass a fresh object per call.\n *\n * Cross-request data leaks are **only possible** when per-request mutable\n * state is incorrectly placed in `base.dependencies`. The override slot is\n * the safe channel.\n *\n * @example\n * ```typescript\n * // Server boot — singletons only\n * const base = createRouter(routes, options, {\n * db: new DbClient(dbUrl),\n * logger,\n * });\n *\n * // Per request — fresh override per call\n * const clone = cloneRouter(base, {\n * currentUser,\n * traceId,\n * });\n * // clone.deps.db === base.deps.db ✓ shared pool (intentional)\n * // clone.deps.currentUser ✓ unique per request\n * ```\n *\n * @see createRequestScope — `@real-router/core/utils` SSR helper that\n * wraps this function and injects `abortSignal` automatically.\n */\nexport function cloneRouter<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n dependencies?: Dependencies,\n): RouterClass<Dependencies> {\n const ctx = getInternals(router);\n\n if (ctx.isDisposed()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n ctx.validator?.dependencies.validateCloneArgs(dependencies);\n\n // Get source store directly\n const sourceStore = ctx.routeGetStore();\n const routes = routeTreeToDefinitions(sourceStore.tree);\n const routeConfig = sourceStore.config;\n const resolvedForwardMap = sourceStore.resolvedForwardMap;\n const routeCustomFields = sourceStore.routeCustomFields;\n\n const {\n options,\n dependencies: sourceDeps,\n pluginFactories,\n } = ctx.getCloneState();\n // Origin-aware factory snapshot — definition guards are re-registered with\n // `isFromDefinition=true` on the clone so `replace()` can still strip them\n // via `clearDefinitionGuards()`. External guards take the public lifecycle\n // API path so they survive `replace()` symmetric with the base.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const sourceLifecycleNamespace = sourceStore.lifecycleNamespace!;\n const { definition: definitionFactories, external: externalFactories } =\n sourceLifecycleNamespace.getFactoriesByOrigin();\n\n const mergedDeps = {\n ...sourceDeps,\n ...dependencies,\n } as Dependencies;\n\n const newRouter = new RouterClass<Dependencies>(\n routes as Route<Dependencies>[],\n options,\n mergedDeps,\n );\n\n const newCtx = getInternals(newRouter);\n const newStore = newCtx.routeGetStore();\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed set after wiring\n const newLifecycleNamespace = newStore.lifecycleNamespace!;\n\n // Copy the source config + store-level maps BEFORE re-registering guards\n // (#1331 review): the definition-guard factories re-executed below must\n // observe the fully-built clone (encoders/decoders/defaultParams/custom\n // fields), mirroring the constructor where flushPendingGuards runs after the\n // store is complete. The five RouteConfig sub-maps go through a single\n // enumeration so a newly added config field is carried over automatically\n // (#965); resolvedForwardMap and routeCustomFields are store-level (not part\n // of RouteConfig) and stay explicit.\n assignConfigEntries(newStore.config, routeConfig);\n Object.assign(newStore.resolvedForwardMap, resolvedForwardMap);\n Object.assign(newStore.routeCustomFields, routeCustomFields);\n\n // #1175: carry the source rootPath. It lives in the store (not options/config),\n // and neither routeTreeToDefinitions nor getCloneState include it — so a clone\n // of a base configured with `setRootPath(\"/app\")` would otherwise build/match\n // under \"\" and 404 every request of a sub-path SSR deployment. setRootPath\n // rebuilds the tree in place with the just-copied config; the rebuild is only\n // paid when a rootPath is actually set, and it runs before the definition-guard\n // factories below so they observe the fully-built clone (rootPath included).\n if (sourceStore.rootPath !== \"\") {\n newCtx.setRootPath(sourceStore.rootPath);\n }\n\n const [definitionDeactivate, definitionActivate] = definitionFactories;\n const [externalDeactivate, externalActivate] = externalFactories;\n\n for (const [name, handler] of Object.entries(definitionDeactivate)) {\n newLifecycleNamespace.addCanDeactivate(name, handler, true);\n }\n\n for (const [name, handler] of Object.entries(definitionActivate)) {\n newLifecycleNamespace.addCanActivate(name, handler, true);\n }\n\n const lifecycle = getLifecycleApi(newRouter);\n\n for (const [name, handler] of Object.entries(externalDeactivate)) {\n lifecycle.addDeactivateGuard(name, handler);\n }\n\n for (const [name, handler] of Object.entries(externalActivate)) {\n lifecycle.addActivateGuard(name, handler);\n }\n\n // Plugin replay runs last and skips factories that a (contract-violating)\n // definition-guard factory already registered on the clone during the\n // re-compilation above — without the filter every clone would double-apply\n // such a plugin: once via the factory, once via this replay (#1331 review).\n const alreadyRegistered = new Set(newCtx.getCloneState().pluginFactories);\n const pluginsToReplay = pluginFactories.filter(\n (factory) => !alreadyRegistered.has(factory),\n );\n\n // Stryker disable next-line EqualityOperator: equivalent — `>= 0` is always true, but `usePlugin(...[])` with an empty spread is a no-op, so entering the block on an empty list behaves identically to skipping it. (ConditionalExpression stays live: `→false` skips a real plugin list and is killable.)\n if (pluginsToReplay.length > 0) {\n newRouter.usePlugin(...pluginsToReplay);\n }\n\n return newRouter;\n}\n"],"mappings":"wGAKA,SAAgB,EAAgB,EAAiC,CAC/D,GAAI,EAAW,EACb,MAAM,IAAI,EAAY,EAAW,eAAe,CAEpD,CASA,SAAgB,EAA6B,EAAiC,CAC5E,GAAI,EAAW,EACb,MAAM,IAAI,EAAY,EAAW,uBAAuB,CAE5D,CCFA,MAAM,EAAQ,IAAI,QAElB,SAAgB,EAEd,EAAyC,CACzC,IAAM,EAAS,EAAM,IAAI,CAAM,EAE/B,GAAI,EACF,OAAO,EAGT,IAAM,EAAM,EAAa,CAAM,EACzB,EAAiB,CACrB,WAAY,EAAM,EAAQ,EAAM,KAC9B,EAAI,WAAW,MAAM,sBAAsB,EAAM,EAAQ,CAAI,EAEtD,EAAI,UACT,EACA,EACA,EACA,GAAM,M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