@real-router/core 0.78.0 → 0.79.1
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/README.md +1 -1
- package/dist/cjs/Router-DGUed2F4.js +2 -0
- package/dist/cjs/Router-DGUed2F4.js.map +1 -0
- package/dist/cjs/{Router-BG5yNYUG.d.ts → Router.d.ts} +5 -4
- package/dist/cjs/Router.d.ts.map +1 -0
- package/dist/cjs/Router.js +2 -0
- package/dist/cjs/Router.js.map +1 -0
- package/dist/cjs/RouterError.d.ts +182 -0
- package/dist/cjs/RouterError.d.ts.map +1 -0
- package/dist/cjs/RouterError.js +2 -0
- package/dist/cjs/RouterError.js.map +1 -0
- package/dist/cjs/api/cloneRouter.d.ts +86 -0
- package/dist/cjs/api/cloneRouter.d.ts.map +1 -0
- package/dist/cjs/api/cloneRouter.js +2 -0
- package/dist/cjs/api/cloneRouter.js.map +1 -0
- package/dist/cjs/api/getDependenciesApi.d.ts +7 -0
- package/dist/cjs/api/getDependenciesApi.d.ts.map +1 -0
- package/dist/cjs/api/getDependenciesApi.js +2 -0
- package/dist/cjs/api/getDependenciesApi.js.map +1 -0
- package/dist/cjs/api/getLifecycleApi.d.ts +7 -0
- package/dist/cjs/api/getLifecycleApi.d.ts.map +1 -0
- package/dist/cjs/api/getLifecycleApi.js +2 -0
- package/dist/cjs/api/getLifecycleApi.js.map +1 -0
- package/dist/cjs/api/getPluginApi.d.ts +7 -0
- package/dist/cjs/api/getPluginApi.d.ts.map +1 -0
- package/dist/cjs/api/getPluginApi.js +2 -0
- package/dist/cjs/api/getPluginApi.js.map +1 -0
- package/dist/cjs/api/getRoutesApi.d.ts +7 -0
- package/dist/cjs/api/getRoutesApi.d.ts.map +1 -0
- package/dist/cjs/api/getRoutesApi.js +2 -0
- package/dist/cjs/api/getRoutesApi.js.map +1 -0
- package/dist/cjs/api/helpers.js +2 -0
- package/dist/cjs/api/helpers.js.map +1 -0
- package/dist/cjs/api/types.d.ts +9 -0
- package/dist/cjs/api/types.d.ts.map +1 -0
- package/dist/cjs/api.d.ts +8 -105
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/api.js.map +1 -1
- package/dist/cjs/buildParamMeta-DniluAIV.js +2 -0
- package/dist/cjs/buildParamMeta-DniluAIV.js.map +1 -0
- package/dist/cjs/{cloneRouter-a6LJt-zh.js → cloneRouter-Ch25z3Z2.js} +2 -2
- package/dist/cjs/{cloneRouter-a6LJt-zh.js.map → cloneRouter-Ch25z3Z2.js.map} +1 -1
- package/dist/cjs/constants.d.ts +25 -0
- package/dist/cjs/constants.d.ts.map +1 -0
- package/dist/cjs/constants.js +2 -0
- package/dist/cjs/constants.js.map +1 -0
- package/dist/cjs/createRouter.d.ts +23 -0
- package/dist/cjs/createRouter.d.ts.map +1 -0
- package/dist/cjs/createRouter.js +2 -0
- package/dist/cjs/createRouter.js.map +1 -0
- package/dist/cjs/engine/builder/buildTree.js +2 -0
- package/dist/cjs/engine/builder/buildTree.js.map +1 -0
- package/dist/cjs/engine/builder/computeCaches.js +2 -0
- package/dist/cjs/engine/builder/computeCaches.js.map +1 -0
- package/dist/cjs/engine/builder/createRouteTree.js +2 -0
- package/dist/cjs/engine/builder/createRouteTree.js.map +1 -0
- package/dist/cjs/engine/builder/types.d.ts +48 -0
- package/dist/cjs/engine/builder/types.d.ts.map +1 -0
- package/dist/cjs/engine/createMatcher.d.ts +29 -0
- package/dist/cjs/engine/createMatcher.d.ts.map +1 -0
- package/dist/cjs/engine/createMatcher.js +2 -0
- package/dist/cjs/engine/createMatcher.js.map +1 -0
- package/dist/cjs/engine/operations/routeTreeToDefinitions.js +2 -0
- package/dist/cjs/engine/operations/routeTreeToDefinitions.js.map +1 -0
- package/dist/cjs/engine/path-matcher/SegmentMatcher.d.ts +16 -0
- package/dist/cjs/engine/path-matcher/SegmentMatcher.d.ts.map +1 -0
- package/dist/cjs/engine/path-matcher/SegmentMatcher.js +2 -0
- package/dist/cjs/engine/path-matcher/SegmentMatcher.js.map +1 -0
- package/dist/cjs/engine/path-matcher/buildParamMeta.js +2 -0
- package/dist/cjs/engine/path-matcher/buildParamMeta.js.map +1 -0
- package/dist/cjs/engine/path-matcher/encoding.js +2 -0
- package/dist/cjs/engine/path-matcher/encoding.js.map +1 -0
- package/dist/cjs/engine/path-matcher/parseSegment.js +2 -0
- package/dist/cjs/engine/path-matcher/parseSegment.js.map +1 -0
- package/dist/cjs/engine/path-matcher/pathUtils.js +2 -0
- package/dist/cjs/engine/path-matcher/pathUtils.js.map +1 -0
- package/dist/cjs/engine/path-matcher/percentEncoding.js +2 -0
- package/dist/cjs/engine/path-matcher/percentEncoding.js.map +1 -0
- package/dist/cjs/engine/path-matcher/registration/buildParts.js +2 -0
- package/dist/cjs/engine/path-matcher/registration/buildParts.js.map +1 -0
- package/dist/cjs/engine/path-matcher/registration/context.js +2 -0
- package/dist/cjs/engine/path-matcher/registration/context.js.map +1 -0
- package/dist/cjs/engine/path-matcher/registration/errors.js +2 -0
- package/dist/cjs/engine/path-matcher/registration/errors.js.map +1 -0
- package/dist/cjs/engine/path-matcher/registration/index.js +2 -0
- package/dist/cjs/engine/path-matcher/registration/index.js.map +1 -0
- package/dist/cjs/engine/path-matcher/registration/trie.js +2 -0
- package/dist/cjs/engine/path-matcher/registration/trie.js.map +1 -0
- package/dist/cjs/engine/path-matcher/registration/trieNodes.js +2 -0
- package/dist/cjs/engine/path-matcher/registration/trieNodes.js.map +1 -0
- package/dist/cjs/{types-xg2zHVF6.d.ts → engine/path-matcher/types.d.ts} +2 -80
- package/dist/cjs/engine/path-matcher/types.d.ts.map +1 -0
- package/dist/cjs/engine/search-params/decode.js +2 -0
- package/dist/cjs/engine/search-params/decode.js.map +1 -0
- package/dist/cjs/engine/search-params/encode.js +2 -0
- package/dist/cjs/engine/search-params/encode.js.map +1 -0
- package/dist/cjs/engine/search-params/searchParams.js +2 -0
- package/dist/cjs/engine/search-params/searchParams.js.map +1 -0
- package/dist/cjs/engine/search-params/strategies/array.js +2 -0
- package/dist/cjs/engine/search-params/strategies/array.js.map +1 -0
- package/dist/cjs/engine/search-params/strategies/boolean.js +2 -0
- package/dist/cjs/engine/search-params/strategies/boolean.js.map +1 -0
- package/dist/cjs/engine/search-params/strategies/index.js +2 -0
- package/dist/cjs/engine/search-params/strategies/index.js.map +1 -0
- package/dist/cjs/engine/search-params/strategies/null.js +2 -0
- package/dist/cjs/engine/search-params/strategies/null.js.map +1 -0
- package/dist/cjs/engine/search-params/strategies/number.js +2 -0
- package/dist/cjs/engine/search-params/strategies/number.js.map +1 -0
- package/dist/cjs/engine/search-params/types.d.ts +72 -0
- package/dist/cjs/engine/search-params/types.d.ts.map +1 -0
- package/dist/cjs/engine/search-params/utils.js +2 -0
- package/dist/cjs/engine/search-params/utils.js.map +1 -0
- package/dist/cjs/engine/validation/route-batch.d.ts +38 -0
- package/dist/cjs/engine/validation/route-batch.d.ts.map +1 -0
- package/dist/cjs/engine/validation/route-batch.js +2 -0
- package/dist/cjs/engine/validation/route-batch.js.map +1 -0
- package/dist/cjs/engine/validation/routes.js +2 -0
- package/dist/cjs/engine/validation/routes.js.map +1 -0
- package/dist/cjs/foundation/event-emitter/EventEmitter.js +2 -0
- package/dist/cjs/foundation/event-emitter/EventEmitter.js.map +1 -0
- package/dist/cjs/foundation/fsm/fsm.js +2 -0
- package/dist/cjs/foundation/fsm/fsm.js.map +1 -0
- package/dist/cjs/foundation/logger/RouterLogger.js +2 -0
- package/dist/cjs/foundation/logger/RouterLogger.js.map +1 -0
- package/dist/cjs/foundation/logger/constants.js +2 -0
- package/dist/cjs/foundation/logger/constants.js.map +1 -0
- package/dist/cjs/getNavigator.d.ts +6 -0
- package/dist/cjs/getNavigator.d.ts.map +1 -0
- package/dist/cjs/getNavigator.js +2 -0
- package/dist/cjs/getNavigator.js.map +1 -0
- package/dist/cjs/guards.js +2 -0
- package/dist/cjs/guards.js.map +1 -0
- package/dist/cjs/helpers.js +2 -0
- package/dist/cjs/helpers.js.map +1 -0
- package/dist/cjs/index.d.ts +17 -239
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/internals.d.ts +99 -0
- package/dist/cjs/internals.d.ts.map +1 -0
- package/dist/cjs/internals.js +2 -0
- package/dist/cjs/internals.js.map +1 -0
- package/dist/cjs/namespaces/DependenciesNamespace/dependenciesStore.d.ts +10 -0
- package/dist/cjs/namespaces/DependenciesNamespace/dependenciesStore.d.ts.map +1 -0
- package/dist/cjs/namespaces/DependenciesNamespace/dependenciesStore.js +2 -0
- package/dist/cjs/namespaces/DependenciesNamespace/dependenciesStore.js.map +1 -0
- package/dist/cjs/namespaces/EventBusNamespace/EventBusNamespace.js +2 -0
- package/dist/cjs/namespaces/EventBusNamespace/EventBusNamespace.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/constants.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/constants.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/completeTransition.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/completeTransition.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/errorHandling.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/errorHandling.js.map +1 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/guardPhase.js +2 -0
- package/dist/cjs/namespaces/NavigationNamespace/transition/guardPhase.js.map +1 -0
- package/dist/cjs/namespaces/OptionsNamespace/OptionsNamespace.js +2 -0
- package/dist/cjs/namespaces/OptionsNamespace/OptionsNamespace.js.map +1 -0
- package/dist/cjs/namespaces/OptionsNamespace/constants.js +2 -0
- package/dist/cjs/namespaces/OptionsNamespace/constants.js.map +1 -0
- package/dist/cjs/namespaces/OptionsNamespace/helpers.js +2 -0
- package/dist/cjs/namespaces/OptionsNamespace/helpers.js.map +1 -0
- package/dist/cjs/namespaces/OptionsNamespace/validators.js +2 -0
- package/dist/cjs/namespaces/OptionsNamespace/validators.js.map +1 -0
- package/dist/cjs/namespaces/PluginsNamespace/PluginsNamespace.js +2 -0
- package/dist/cjs/namespaces/PluginsNamespace/PluginsNamespace.js.map +1 -0
- package/dist/cjs/namespaces/PluginsNamespace/constants.js +2 -0
- package/dist/cjs/namespaces/PluginsNamespace/constants.js.map +1 -0
- package/dist/cjs/namespaces/PluginsNamespace/validators.js +2 -0
- package/dist/cjs/namespaces/PluginsNamespace/validators.js.map +1 -0
- package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.ts +174 -0
- package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.ts.map +1 -0
- package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.js +2 -0
- package/dist/cjs/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.js.map +1 -0
- package/dist/cjs/namespaces/RouteLifecycleNamespace/types.d.ts +17 -0
- package/dist/cjs/namespaces/RouteLifecycleNamespace/types.d.ts.map +1 -0
- package/dist/cjs/namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js +2 -0
- package/dist/cjs/namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.js.map +1 -0
- package/dist/cjs/namespaces/RouterLifecycleNamespace/constants.js +2 -0
- package/dist/cjs/namespaces/RouterLifecycleNamespace/constants.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js +2 -0
- package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/constants.js +2 -0
- package/dist/cjs/namespaces/RoutesNamespace/constants.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/forwardChain.d.ts +5 -0
- package/dist/cjs/namespaces/RoutesNamespace/forwardChain.d.ts.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/forwardChain.js +2 -0
- package/dist/cjs/namespaces/RoutesNamespace/forwardChain.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js +2 -0
- package/dist/cjs/namespaces/RoutesNamespace/helpers.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/routeGuards.js +2 -0
- package/dist/cjs/namespaces/RoutesNamespace/routeGuards.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts +42 -0
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js +2 -0
- package/dist/cjs/namespaces/RoutesNamespace/routesStore.js.map +1 -0
- package/dist/cjs/namespaces/RoutesNamespace/types.d.ts +57 -0
- package/dist/cjs/namespaces/RoutesNamespace/types.d.ts.map +1 -0
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js +2 -0
- package/dist/cjs/namespaces/StateNamespace/StateNamespace.js.map +1 -0
- package/dist/cjs/namespaces/StateNamespace/helpers.js +2 -0
- package/dist/cjs/namespaces/StateNamespace/helpers.js.map +1 -0
- package/dist/cjs/routerFSM.js +2 -0
- package/dist/cjs/routerFSM.js.map +1 -0
- package/dist/cjs/stateMetaStore.js +2 -0
- package/dist/cjs/stateMetaStore.js.map +1 -0
- package/dist/cjs/transitionPath.js +2 -0
- package/dist/cjs/transitionPath.js.map +1 -0
- package/dist/cjs/{RouterValidator-CZ8kPkrI.d.ts → types/RouterValidator.d.ts} +2 -2
- package/dist/cjs/types/RouterValidator.d.ts.map +1 -0
- package/dist/cjs/types/api.d.ts +184 -0
- package/dist/cjs/types/api.d.ts.map +1 -0
- package/dist/cjs/types/base.d.ts +86 -0
- package/dist/cjs/types/base.d.ts.map +1 -0
- package/dist/cjs/types/constants.d.ts +72 -0
- package/dist/cjs/types/constants.d.ts.map +1 -0
- package/dist/cjs/types/internal.d.ts +9 -0
- package/dist/cjs/types/internal.d.ts.map +1 -0
- package/dist/cjs/types/limits.d.ts +45 -0
- package/dist/cjs/types/limits.d.ts.map +1 -0
- package/dist/cjs/types/route-node-types.d.ts +46 -0
- package/dist/cjs/types/route-node-types.d.ts.map +1 -0
- package/dist/cjs/types/router.d.ts +313 -0
- package/dist/cjs/types/router.d.ts.map +1 -0
- package/dist/cjs/types/tree-changed.d.ts +55 -0
- package/dist/cjs/types/tree-changed.d.ts.map +1 -0
- package/dist/cjs/types.d.ts +208 -2
- package/dist/cjs/types.d.ts.map +1 -0
- package/dist/cjs/utils/createRequestScope.d.ts +111 -0
- package/dist/cjs/utils/createRequestScope.d.ts.map +1 -0
- package/dist/cjs/utils/createRequestScope.js +2 -0
- package/dist/cjs/utils/createRequestScope.js.map +1 -0
- package/dist/cjs/utils/getStaticPaths.d.ts +7 -0
- package/dist/cjs/utils/getStaticPaths.d.ts.map +1 -0
- package/dist/cjs/utils/getStaticPaths.js +2 -0
- package/dist/cjs/utils/getStaticPaths.js.map +1 -0
- package/dist/cjs/utils/hydrateRouter.d.ts +69 -0
- package/dist/cjs/utils/hydrateRouter.d.ts.map +1 -0
- package/dist/cjs/utils/hydrateRouter.js +2 -0
- package/dist/cjs/utils/hydrateRouter.js.map +1 -0
- package/dist/cjs/utils/serializeRouterState.d.ts +84 -0
- package/dist/cjs/utils/serializeRouterState.d.ts.map +1 -0
- package/dist/cjs/utils/serializeRouterState.js +2 -0
- package/dist/cjs/utils/serializeRouterState.js.map +1 -0
- package/dist/cjs/utils/serializeState.d.ts +50 -0
- package/dist/cjs/utils/serializeState.d.ts.map +1 -0
- package/dist/cjs/utils/serializeState.js +2 -0
- package/dist/cjs/utils/serializeState.js.map +1 -0
- package/dist/cjs/utils.d.ts +5 -1
- package/dist/cjs/utils.js +1 -1
- package/dist/cjs/validation.d.ts +6 -518
- package/dist/cjs/validation.js +1 -1
- package/dist/cjs/validation.js.map +1 -1
- package/dist/cjs/wiring/wireNamespaces.js +2 -0
- package/dist/cjs/wiring/wireNamespaces.js.map +1 -0
- package/dist/esm/Router-Bk6PfSE8.mjs +2 -0
- package/dist/esm/Router-Bk6PfSE8.mjs.map +1 -0
- package/dist/esm/{Router-Cy75qbgU.d.mts → Router.d.mts} +5 -4
- package/dist/esm/Router.d.mts.map +1 -0
- package/dist/esm/RouterError.d.mts +182 -0
- package/dist/esm/RouterError.d.mts.map +1 -0
- package/dist/esm/api/cloneRouter.d.mts +86 -0
- package/dist/esm/api/cloneRouter.d.mts.map +1 -0
- package/dist/esm/api/getDependenciesApi.d.mts +7 -0
- package/dist/esm/api/getDependenciesApi.d.mts.map +1 -0
- package/dist/esm/api/getLifecycleApi.d.mts +7 -0
- package/dist/esm/api/getLifecycleApi.d.mts.map +1 -0
- package/dist/esm/api/getPluginApi.d.mts +7 -0
- package/dist/esm/api/getPluginApi.d.mts.map +1 -0
- package/dist/esm/api/getRoutesApi.d.mts +7 -0
- package/dist/esm/api/getRoutesApi.d.mts.map +1 -0
- package/dist/esm/api/types.d.mts +9 -0
- package/dist/esm/api/types.d.mts.map +1 -0
- package/dist/esm/api.d.mts +8 -105
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/api.mjs.map +1 -1
- package/dist/esm/buildParamMeta-bOLhLF9h.mjs +2 -0
- package/dist/esm/buildParamMeta-bOLhLF9h.mjs.map +1 -0
- package/dist/esm/{cloneRouter-CqS4kTs8.mjs → cloneRouter-D4rnqmi9.mjs} +2 -2
- package/dist/esm/{cloneRouter-CqS4kTs8.mjs.map → cloneRouter-D4rnqmi9.mjs.map} +1 -1
- package/dist/esm/constants.d.mts +25 -0
- package/dist/esm/constants.d.mts.map +1 -0
- package/dist/esm/createRouter.d.mts +23 -0
- package/dist/esm/createRouter.d.mts.map +1 -0
- package/dist/esm/engine/builder/types.d.mts +48 -0
- package/dist/esm/engine/builder/types.d.mts.map +1 -0
- package/dist/esm/engine/createMatcher.d.mts +29 -0
- package/dist/esm/engine/createMatcher.d.mts.map +1 -0
- package/dist/esm/engine/path-matcher/SegmentMatcher.d.mts +16 -0
- package/dist/esm/engine/path-matcher/SegmentMatcher.d.mts.map +1 -0
- package/dist/esm/{types-xg2zHVF6.d.mts → engine/path-matcher/types.d.mts} +2 -80
- package/dist/esm/engine/path-matcher/types.d.mts.map +1 -0
- package/dist/esm/engine/search-params/types.d.mts +72 -0
- package/dist/esm/engine/search-params/types.d.mts.map +1 -0
- package/dist/esm/engine/validation/route-batch.d.mts +38 -0
- package/dist/esm/engine/validation/route-batch.d.mts.map +1 -0
- package/dist/esm/getNavigator.d.mts +6 -0
- package/dist/esm/getNavigator.d.mts.map +1 -0
- package/dist/esm/index.d.mts +17 -239
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/internals.d.mts +99 -0
- package/dist/esm/internals.d.mts.map +1 -0
- package/dist/esm/namespaces/DependenciesNamespace/dependenciesStore.d.mts +10 -0
- package/dist/esm/namespaces/DependenciesNamespace/dependenciesStore.d.mts.map +1 -0
- package/dist/esm/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.mts +174 -0
- package/dist/esm/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.mts.map +1 -0
- package/dist/esm/namespaces/RouteLifecycleNamespace/types.d.mts +17 -0
- package/dist/esm/namespaces/RouteLifecycleNamespace/types.d.mts.map +1 -0
- package/dist/esm/namespaces/RoutesNamespace/forwardChain.d.mts +5 -0
- package/dist/esm/namespaces/RoutesNamespace/forwardChain.d.mts.map +1 -0
- package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts +42 -0
- package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts.map +1 -0
- package/dist/esm/namespaces/RoutesNamespace/types.d.mts +57 -0
- package/dist/esm/namespaces/RoutesNamespace/types.d.mts.map +1 -0
- package/dist/esm/{RouterValidator-CZ8kPkrI.d.mts → types/RouterValidator.d.mts} +2 -2
- package/dist/esm/types/RouterValidator.d.mts.map +1 -0
- package/dist/esm/types/api.d.mts +184 -0
- package/dist/esm/types/api.d.mts.map +1 -0
- package/dist/esm/types/base.d.mts +86 -0
- package/dist/esm/types/base.d.mts.map +1 -0
- package/dist/esm/types/constants.d.mts +72 -0
- package/dist/esm/types/constants.d.mts.map +1 -0
- package/dist/esm/types/internal.d.mts +9 -0
- package/dist/esm/types/internal.d.mts.map +1 -0
- package/dist/esm/types/limits.d.mts +45 -0
- package/dist/esm/types/limits.d.mts.map +1 -0
- package/dist/esm/types/route-node-types.d.mts +46 -0
- package/dist/esm/types/route-node-types.d.mts.map +1 -0
- package/dist/esm/types/router.d.mts +313 -0
- package/dist/esm/types/router.d.mts.map +1 -0
- package/dist/esm/types/tree-changed.d.mts +55 -0
- package/dist/esm/types/tree-changed.d.mts.map +1 -0
- package/dist/esm/types.d.mts +208 -2
- package/dist/esm/types.d.mts.map +1 -0
- package/dist/esm/utils/createRequestScope.d.mts +111 -0
- package/dist/esm/utils/createRequestScope.d.mts.map +1 -0
- package/dist/esm/utils/getStaticPaths.d.mts +7 -0
- package/dist/esm/utils/getStaticPaths.d.mts.map +1 -0
- package/dist/esm/utils/hydrateRouter.d.mts +69 -0
- package/dist/esm/utils/hydrateRouter.d.mts.map +1 -0
- package/dist/esm/utils/serializeRouterState.d.mts +84 -0
- package/dist/esm/utils/serializeRouterState.d.mts.map +1 -0
- package/dist/esm/utils/serializeState.d.mts +50 -0
- package/dist/esm/utils/serializeState.d.mts.map +1 -0
- package/dist/esm/utils.d.mts +5 -1
- package/dist/esm/utils.mjs +1 -1
- package/dist/esm/validation.d.mts +6 -518
- package/dist/esm/validation.mjs +1 -1
- package/dist/esm/validation.mjs.map +1 -1
- package/package.json +2 -2
- package/dist/cjs/Router-BG5yNYUG.d.ts.map +0 -1
- package/dist/cjs/Router-D6NzRxBA.js +0 -2
- package/dist/cjs/Router-D6NzRxBA.js.map +0 -1
- package/dist/cjs/RouterValidator-CZ8kPkrI.d.ts.map +0 -1
- package/dist/cjs/api.d.ts.map +0 -1
- package/dist/cjs/buildParamMeta-CkG6cUIl.js +0 -2
- package/dist/cjs/buildParamMeta-CkG6cUIl.js.map +0 -1
- package/dist/cjs/index-CAnGQpnz.d.ts +0 -974
- package/dist/cjs/index-CAnGQpnz.d.ts.map +0 -1
- package/dist/cjs/index-DDrryY2U.d.ts +0 -309
- package/dist/cjs/index-DDrryY2U.d.ts.map +0 -1
- package/dist/cjs/index.d.ts.map +0 -1
- package/dist/cjs/types-xg2zHVF6.d.ts.map +0 -1
- package/dist/cjs/validation.d.ts.map +0 -1
- package/dist/esm/Router-Cy75qbgU.d.mts.map +0 -1
- package/dist/esm/Router-De0Gr9Ll.mjs +0 -2
- package/dist/esm/Router-De0Gr9Ll.mjs.map +0 -1
- package/dist/esm/RouterValidator-CZ8kPkrI.d.mts.map +0 -1
- package/dist/esm/api.d.mts.map +0 -1
- package/dist/esm/buildParamMeta-Bl0uORu6.mjs +0 -2
- package/dist/esm/buildParamMeta-Bl0uORu6.mjs.map +0 -1
- package/dist/esm/index-CAnGQpnz.d.mts +0 -974
- package/dist/esm/index-CAnGQpnz.d.mts.map +0 -1
- package/dist/esm/index-DnSU6huX.d.mts +0 -309
- package/dist/esm/index-DnSU6huX.d.mts.map +0 -1
- package/dist/esm/index.d.mts.map +0 -1
- package/dist/esm/types-xg2zHVF6.d.mts.map +0 -1
- package/dist/esm/validation.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"NavigationNamespace.js","names":["constants","#deps","CACHED_NOT_STARTED_REJECTION","CACHED_ROUTE_NOT_FOUND_ERROR","CACHED_ROUTE_NOT_FOUND_REJECTION","#executeNavigation","RouterError","errorCodes","getStateMetaParams","#abortPreviousNavigation","nameToIDs","EMPTY_PARAMS","#currentController","CACHED_SAME_STATES_ERROR","CACHED_SAME_STATES_REJECTION","#navigationId","getTransitionPath","#handleNoGuardsLeave","executeGuardPipeline","#finishAsyncNavigation","#cleanupController","completeTransition","#handleNavigateError"],"sources":["../../../../src/namespaces/NavigationNamespace/NavigationNamespace.ts"],"sourcesContent":["import {\n CACHED_NOT_STARTED_REJECTION,\n CACHED_ROUTE_NOT_FOUND_ERROR,\n CACHED_ROUTE_NOT_FOUND_REJECTION,\n CACHED_SAME_STATES_ERROR,\n CACHED_SAME_STATES_REJECTION,\n} from \"./constants\";\nimport { completeTransition } from \"./transition/completeTransition\";\nimport { routeTransitionError } from \"./transition/errorHandling\";\nimport { executeGuardPipeline } from \"./transition/guardPhase\";\nimport { EMPTY_PARAMS, errorCodes, constants } from \"../../constants\";\nimport { RouterError } from \"../../RouterError\";\nimport { getStateMetaParams, setStateMetaParams } from \"../../stateMetaStore\";\nimport { getTransitionPath, nameToIDs } from \"../../transitionPath\";\n\nimport type { NavigationContext, NavigationDependencies } from \"./types\";\nimport type { TransitionPath } from \"../../transitionPath\";\nimport type {\n GuardFn,\n NavigationOptions,\n Params,\n State,\n TransitionMeta,\n} from \"../../types\";\n\nconst FROZEN_ACTIVATED: string[] = Object.freeze([\n constants.UNKNOWN_ROUTE,\n]) as unknown as string[];\nconst FROZEN_REPLACE_OPTS: NavigationOptions = Object.freeze({ replace: true });\n\nfunction forceReplaceFromUnknown(\n opts: NavigationOptions,\n fromState: State | undefined,\n): NavigationOptions {\n return fromState?.name === constants.UNKNOWN_ROUTE && !opts.replace\n ? { ...opts, replace: true }\n : opts;\n}\n\nfunction isSameNavigation(\n fromState: State | undefined,\n opts: NavigationOptions,\n toState: State,\n): boolean {\n return (\n !!fromState &&\n !opts.reload &&\n !opts.force &&\n fromState.path === toState.path\n );\n}\n\n/**\n * Independent namespace for managing navigation.\n *\n * Handles navigate(), navigateToDefault(), navigateToNotFound(), and transition state.\n *\n * Performance: navigate() uses optimistic sync execution — guards run synchronously\n * until one returns a Promise, then switches to async. This eliminates Promise/AbortController\n * overhead for the common case (no guards or sync guards).\n */\nexport class NavigationNamespace {\n // Stryker disable next-line BooleanLiteral: equivalent — reset to false at the top of every navigate()/navigateToState()/navigateToDefault(), so the initializer value is never observed.\n lastSyncResolved = false;\n lastSyncRejected = false;\n #deps!: NavigationDependencies;\n #currentController: AbortController | null = null;\n #navigationId = 0;\n\n // =========================================================================\n // Dependency injection\n // =========================================================================\n\n setDependencies(deps: NavigationDependencies): void {\n this.#deps = deps;\n }\n\n // =========================================================================\n // Instance methods\n // =========================================================================\n\n navigate(\n name: string,\n params: Params,\n opts: NavigationOptions,\n ): Promise<State> {\n this.lastSyncResolved = false;\n const deps = this.#deps;\n\n // Fast-path sync rejections: cached error + cached Promise.reject\n // No allocations, no throw/catch overhead, facade skips .catch() suppression\n if (!deps.canNavigate()) {\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag, not a correctness gate. Not flagging the cached (pre-suppressed) rejection routes the facade to the else-branch, which re-attaches a harmless .catch; no observable difference.\n this.lastSyncRejected = true;\n\n return CACHED_NOT_STARTED_REJECTION;\n }\n\n let toState: State | undefined;\n\n try {\n toState = deps.buildNavigateState(name, params);\n } catch (error) {\n /* v8 ignore next 3 -- @preserve: reachable only via validator-driven\n throws from buildNavigateState (validateStateBuilderArgs) — covered\n in @real-router/validation-plugin's suite, not in core. */\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided buildNavigateState\n return Promise.reject(error);\n }\n\n if (!toState) {\n deps.emitTransitionError(\n undefined,\n deps.getState(),\n CACHED_ROUTE_NOT_FOUND_ERROR,\n );\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag (see L95): the cached rejection is suppressed by the facade else-branch regardless of the flag.\n this.lastSyncRejected = true;\n\n return CACHED_ROUTE_NOT_FOUND_REJECTION;\n }\n\n return this.#executeNavigation(toState, opts);\n }\n\n /**\n * Navigate to a fully-built `State` directly, skipping `buildNavigateState`\n * (forwardState + buildPath + meta lookup). Used by URL plugins after they\n * have already produced a `State` from a browser-initiated event via\n * `api.matchPath(url)` — see issue #525.\n *\n * Semantics vs. `navigate(name, params, opts)`:\n * - `forwardState` is NOT re-applied. matchPath already runs it; reapplying\n * is redundant in the idempotent case and can race in the dynamic case.\n * - `buildPath` is NOT re-run. The caller's `state.path` is used as-is —\n * so `trailingSlash:\"preserve\"` matchedState paths flow through unchanged\n * (closes #525 Q2). `buildPath` interceptors do NOT run; the URL the\n * user navigated to is the source of truth for this code path.\n * - All other pipeline steps run unchanged: SAME_STATES check, FSM\n * transition, guards, `subscribeLeave`, `completeTransition`,\n * plugin lifecycle hooks.\n */\n navigateToState(state: State, opts: NavigationOptions): Promise<State> {\n this.lastSyncResolved = false;\n const deps = this.#deps;\n\n if (!deps.canNavigate()) {\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag (see L95): the cached rejection is suppressed by the facade else-branch regardless of the flag.\n this.lastSyncRejected = true;\n\n return CACHED_NOT_STARTED_REJECTION;\n }\n\n // Reject states whose route no longer exists (e.g. the route tree was\n // mutated between matchPath and navigateToState). UNKNOWN_ROUTE is\n // structurally legal — it is the navigateToNotFound output shape.\n if (state.name !== constants.UNKNOWN_ROUTE && !deps.hasRoute(state.name)) {\n const err = new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: state.name,\n });\n\n deps.emitTransitionError(undefined, deps.getState(), err);\n\n // This is a FRESH reject (carries `routeName`), not one of the\n // pre-suppressed CACHED_*_REJECTION singletons. `lastSyncRejected`\n // contractually means \"I returned a pre-suppressed cached rejection —\n // skip your .catch()\", so leaving it unset lets the facade attach its\n // own suppression. Setting it here leaked an unhandledRejection on\n // fire-and-forget calls (#721).\n return Promise.reject(err);\n }\n\n // States from `matchPath` are deeply frozen (`freezeStateInPlace`).\n // `completeTransition` mutates `toState.transition` and `context` is\n // intentionally extensible for plugin claim writes, so we hand the\n // pipeline a writable shell — same shape `makeState(skipFreeze=true)`\n // produces. `params` stays referentially shared (already frozen).\n // `transition` is omitted so completeTransition can assign it.\n const writableState = {\n name: state.name,\n params: state.params,\n path: state.path,\n context: { ...state.context },\n } as State;\n\n // Carry the route-meta binding (#1170). `matchPath` / `makeState` attach it\n // to the frozen source `state` via a WeakMap keyed by object reference, so\n // the fresh writable shell would otherwise be meta-less. Without it, two\n // consecutive popstate navigations make both `toState` AND `fromState`\n // meta-less, dropping `getTransitionPath` to FAST PATH 3 (full chains):\n // ancestor guards re-run and browser-back can block where `navigate()`\n // succeeds.\n const meta = getStateMetaParams(state);\n\n if (meta !== undefined) {\n setStateMetaParams(writableState, meta);\n }\n\n return this.#executeNavigation(writableState, opts);\n }\n\n navigateToDefault(opts: NavigationOptions): Promise<State> {\n // Reset the sync-resolution flag on entry, mirroring navigate() and\n // navigateToState(). start() leaves `lastSyncResolved = true`, and the\n // early reject paths below return before delegating to navigate(), so a\n // stale `true` would make the facade take the \"already resolved\" branch\n // and skip .catch() suppression — leaking an unhandledRejection on\n // fire-and-forget calls (#721).\n this.lastSyncResolved = false;\n const deps = this.#deps;\n const options = deps.getOptions();\n\n if (!options.defaultRoute) {\n return Promise.reject(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: \"defaultRoute not configured\",\n }),\n );\n }\n\n let route: string;\n let params: Params;\n\n try {\n ({ route, params } = deps.resolveDefault());\n } catch (error) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from user-provided resolveDefault callback\n return Promise.reject(error);\n }\n\n if (!route) {\n return Promise.reject(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: \"defaultRoute resolved to empty\",\n }),\n );\n }\n\n return this.navigate(route, params, opts);\n }\n\n navigateToNotFound(path: string): State {\n // #1186 — liveness gate. This internal commit primitive has no FSM\n // transition of its own, so without this check a `dispose()` that lands\n // while a start-interceptor is parked (FSM already DISPOSED) would let the\n // resuming pipeline commit an UNKNOWN_ROUTE state on the disposed router and\n // `start()` resolve. Symmetric with `navigateToState`'s `canNavigate()` gate\n // (the matched-route branch is already protected). `!isActive()` also covers\n // a merely-stopped (IDLE) router: the only reachable path to that is a direct\n // `router.navigateToNotFound()` on a stopped instance (internal callers run\n // during STARTING, which is active), so the ROUTER_DISPOSED code is slightly\n // broad there — fail-closed is deliberate (committing on a stopped router is\n // out of contract), and the disposed race is the case that matters.\n if (!this.#deps.isActive()) {\n throw new RouterError(errorCodes.ROUTER_DISPOSED);\n }\n\n this.#abortPreviousNavigation();\n\n const fromState = this.#deps.getState();\n const deactivated: string[] = fromState\n ? nameToIDs(fromState.name).toReversed()\n : [];\n\n Object.freeze(deactivated);\n\n const segments: TransitionMeta[\"segments\"] = {\n deactivated,\n activated: FROZEN_ACTIVATED,\n intersection: \"\",\n };\n\n Object.freeze(segments);\n\n const transitionMeta: TransitionMeta = {\n phase: \"activating\",\n ...(fromState && { from: fromState.name }),\n reason: \"success\",\n replace: true,\n segments,\n };\n\n Object.freeze(transitionMeta);\n\n const state: State = {\n name: constants.UNKNOWN_ROUTE,\n params: EMPTY_PARAMS,\n path,\n transition: transitionMeta,\n context: {},\n };\n\n Object.freeze(state);\n\n this.#deps.setState(state);\n this.#deps.emitTransitionSuccess(state, fromState, FROZEN_REPLACE_OPTS);\n\n return state;\n }\n\n /**\n * Aborts and releases the in-flight navigation's `AbortController` (waking the\n * parked async pipeline via `onInternalAbort`). This is the\n * **effect** of the FSM `CANCEL` action (`handleCancel` → injected\n * `deps.abortCurrentController`), not something cancellation sources call\n * directly — so \"FSM `CANCEL` ⟹ controller aborted\" holds in one place (RFC\n * navigation-cancellation-unification §5). `reason` (e.g. an external\n * `opts.signal`'s reason, #943) becomes the controller's `signal.reason`;\n * defaults to `TRANSITION_CANCELLED`.\n */\n abortCurrentController(reason?: unknown): void {\n this.#currentController?.abort(\n reason ?? new RouterError(errorCodes.TRANSITION_CANCELLED),\n );\n this.#currentController = null;\n }\n\n #executeNavigation(toState: State, opts: NavigationOptions): Promise<State> {\n const deps = this.#deps;\n let fromState: State | undefined;\n let transitionStarted = false;\n let controller: AbortController | null = null;\n\n try {\n fromState = deps.getState();\n opts = forceReplaceFromUnknown(opts, fromState);\n\n if (isSameNavigation(fromState, opts, toState)) {\n deps.emitTransitionError(toState, fromState, CACHED_SAME_STATES_ERROR);\n // Stryker disable next-line BooleanLiteral: equivalent — #721 optimization flag (see L95): the cached rejection is suppressed by the facade else-branch regardless of the flag.\n this.lastSyncRejected = true;\n\n return CACHED_SAME_STATES_REJECTION;\n }\n\n this.#abortPreviousNavigation(opts.signal);\n\n // Stryker disable next-line UpdateOperator: equivalent — `#navigationId` is only ever compared by identity (`!== myId`) to detect supersession; uniqueness per navigation is all that matters, so `--` (decreasing ids) is indistinguishable from `++`.\n const myId = ++this.#navigationId;\n\n // #1169 commit-gate — liveness snapshot captured BEFORE the pre-commit\n // listener windows. A listener's `stop()`/`dispose()` runs `clearAll()`,\n // which empties the listener lists, so the marker must be read now, not at\n // the commit site (that self-destruct was the QB/QE hole, RFC §5-bis).\n // `suspendable` is true only when a synchronous supersede is reachable — an\n // external `opts.signal`, `subscribeLeave` listeners, or a pre-commit\n // plugin listener (`onTransitionStart` / `onTransitionLeaveApprove`); the\n // pure synchronous navigate (none of these) is uncancellable and skips the\n // gate, keeping the #307 hot path perf-neutral.\n const suspendable =\n opts.signal !== undefined ||\n deps.hasLeaveListeners() ||\n deps.hasPreCommitListeners();\n\n deps.startTransition(toState, fromState);\n transitionStarted = true;\n\n // Post-`startTransition` supersession is now caught at the commit-gate\n // below (before `completeTransition`'s setState): a `stop()`/`dispose()`/\n // external-abort from the TRANSITION_START listener leaves the FSM in\n // IDLE/DISPOSED, which `!deps.isActive()` detects. (Async supersession is\n // additionally caught in `#finishAsyncNavigation` / the guard pipeline's\n // `isCurrentNav`; a reentrant navigate() is banned — REENTRANT_NAVIGATION.)\n\n const [canDeactivateFunctions, canActivateFunctions] =\n deps.getLifecycleFunctions();\n const isUnknownRoute = toState.name === constants.UNKNOWN_ROUTE;\n\n const transitionPath = getTransitionPath(toState, fromState);\n const { toDeactivate, toActivate, intersection } = transitionPath;\n\n const shouldDeactivate =\n fromState && !opts.forceDeactivate && toDeactivate.length > 0;\n const shouldActivate = !isUnknownRoute && toActivate.length > 0;\n const hasGuards =\n canDeactivateFunctions.size > 0 || canActivateFunctions.size > 0;\n\n const confirmedToState = toState;\n\n if (!hasGuards) {\n const asyncLeave = this.#handleNoGuardsLeave(\n confirmedToState,\n fromState,\n myId,\n opts,\n transitionPath,\n canDeactivateFunctions,\n );\n\n if (asyncLeave !== undefined) {\n return asyncLeave;\n }\n }\n\n // Stryker disable next-line ConditionalExpression: equivalent — running the guard pipeline on the no-guards path does not double-emit LEAVE_APPROVE (full suite green with `if (true)`); the BlockStatement mutant stays live (killed by guarded-route tests).\n // eslint-disable-next-line unicorn/prefer-else-if -- two exhaustive `if`s read clearer here than an else-if; merging cascades into no-negated-condition / no-unnecessary-condition in this hot guard-setup branch\n if (hasGuards) {\n controller = new AbortController();\n this.#currentController = controller;\n const isCurrentNav = () =>\n this.#navigationId === myId && deps.isActive();\n\n const signal = controller.signal;\n\n const emitLeaveApproveCallback = (): Promise<void> | undefined => {\n deps.sendLeaveApprove(confirmedToState, fromState);\n\n if (deps.hasLeaveListeners()) {\n return deps.awaitLeaveListeners(\n confirmedToState,\n fromState,\n signal,\n );\n }\n\n return undefined;\n };\n\n const guardCompletion = executeGuardPipeline(\n canDeactivateFunctions,\n canActivateFunctions,\n toDeactivate,\n toActivate,\n !!shouldDeactivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isCurrentNav,\n emitLeaveApproveCallback,\n );\n\n if (guardCompletion !== undefined) {\n return this.#finishAsyncNavigation(\n guardCompletion,\n {\n toState,\n fromState,\n opts,\n toDeactivate,\n toActivate,\n intersection,\n canDeactivateFunctions,\n },\n controller,\n myId,\n );\n }\n\n if (!isCurrentNav()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n this.#cleanupController(controller, false);\n }\n\n // #1169 commit-gate — refuse to commit a navigation cancelled or\n // terminated during a listener window, BEFORE `completeTransition`'s\n // setState. The FSM table (D-full) already prevents the forceState\n // resurrection; this prevents the state commit that precedes the emit.\n // Gated on `suspendable` so the pure sync hot path pays nothing. A\n // `stop()`/`dispose()` from the listener lands the FSM in IDLE/DISPOSED\n // (caught by `!isActive()`); an external `opts.signal` abort is caught\n // directly. No `#navigationId` check: a reentrant navigate() (the only\n // thing that could bump it synchronously) is banned (REENTRANT_NAVIGATION,\n // §4), so on this sync path `#navigationId === myId` always holds — async\n // supersede is caught in `#finishAsyncNavigation`'s `isCurrentNav`.\n if (suspendable && (!deps.isActive() || opts.signal?.aborted === true)) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const finalState = completeTransition(deps, {\n toState,\n fromState,\n opts,\n toDeactivate,\n toActivate,\n intersection,\n canDeactivateFunctions,\n });\n\n // Mark sync-resolution only AFTER completeTransition returns. It emits\n // TRANSITION_SUCCESS; listener throws are all isolated via onListenerError\n // (the emitter re-throws nothing now that re-entrant emits are coalesced,\n // #1033, and reentrant navigate/CRUD are banned), so the emit itself does\n // not throw. Should completeTransition throw for any other reason, setting\n // the flag optimistically BEFORE it would leave the flag stale-true, so the\n // facade would read lastSyncResolved and skip its suppressing `.catch()` —\n // the rejection would then leak as a Node unhandledRejection. Post-emit\n // placement keeps the flag false on a throw, so control falls to catch and\n // the facade attaches its `.catch`.\n // Stryker disable next-line BooleanLiteral: equivalent — flipping to false routes the facade to the else-branch, which attaches a harmless .catch to an already-resolved promise; there is no rejection to suppress.\n this.lastSyncResolved = true;\n\n return Promise.resolve(finalState);\n } catch (error) {\n this.#handleNavigateError(\n error,\n controller,\n transitionStarted,\n toState,\n fromState,\n );\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- preserve original throw shape from guards or transition pipeline\n return Promise.reject(error);\n }\n }\n\n async #finishAsyncNavigation(\n guardCompletion: Promise<void>,\n nav: NavigationContext,\n controller: AbortController,\n myId: number,\n ): Promise<State> {\n const deps = this.#deps;\n const isActive = () =>\n this.#navigationId === myId &&\n !controller.signal.aborted &&\n deps.isActive();\n\n const externalSignal = nav.opts.signal;\n let onExternalAbort: (() => void) | undefined;\n let onInternalAbort: (() => void) | undefined;\n let succeeded = false;\n let failureReason: unknown;\n\n // #1018: race the guard completion against the controller's abort so a\n // non-cooperative guard whose Promise never settles (and ignores `signal`)\n // cannot wedge navigate() forever. `abortRace` RESOLVES on abort, so the\n // post-race `isActive()` check below throws TRANSITION_CANCELLED — the same\n // path that already handles a guard which swallows the abort and resolves\n // `true`. `stop()`/`dispose()`/supersede all abort the controller. Mirrors\n // the leave-path protection `settleLeavePromises` (#663/#673).\n const abortRace = new Promise<void>((resolve) => {\n if (controller.signal.aborted) {\n resolve();\n\n return;\n }\n\n onInternalAbort = () => {\n resolve();\n };\n\n controller.signal.addEventListener(\"abort\", onInternalAbort, {\n once: true,\n });\n });\n\n // Consume `guardCompletion` when the abort wins the race: a slow or\n // never-settling guard that settles later then has no awaiter, which would\n // surface as an unhandled rejection without this catch.\n guardCompletion.catch(() => {\n /* settlement consumed — the race already decided the navigation */\n });\n\n try {\n if (externalSignal) {\n if (externalSignal.aborted) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED, {\n reason: externalSignal.reason,\n });\n }\n\n // Bridge an external `{ signal }` abort onto the internal controller.\n // It is NOT scoped to `controller.signal` (the old `{ signal }` option)\n // because success no longer aborts the controller (#722) — the listener\n // is detached explicitly in `finally` instead.\n onExternalAbort = () => {\n // (#1030): route the external abort through the FSM. The\n // `CANCEL` action aborts the internal controller (waking THIS pipeline)\n // with the external `reason` (#943 — surfaces via the leave signal) AND\n // returns the FSM to READY, atomically. No direct `controller.abort`\n // here — \"FSM CANCEL ⟹ controller aborted\" lives in one place\n // (handleCancel). onExternalAbort only fires while the navigation is in\n // flight (the listener is removed in `finally` once it settles), so the\n // FSM is always cancellable here.\n deps.cancelNavigation(externalSignal.reason);\n };\n // Stryker disable next-line ObjectLiteral: equivalent — `{ once: true }` is redundant: the per-navigation signal aborts at most once and is discarded unaborted on success, and the `finally` block explicitly removeEventListener's it.\n externalSignal.addEventListener(\"abort\", onExternalAbort, {\n // Stryker disable next-line BooleanLiteral: equivalent — `once` redundant (see ObjectLiteral above); the listener is explicitly removed in `finally`.\n once: true,\n });\n }\n\n await Promise.race([guardCompletion, abortRace]);\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const state = completeTransition(deps, nav);\n\n succeeded = true;\n\n return state;\n } catch (error) {\n failureReason = error;\n\n routeTransitionError(deps, error, nav.toState, nav.fromState);\n\n throw error;\n // NB: the `} finally {}` BlockStatement mutant SURVIVES but is EQUIVALENT —\n // emptying the finally only skips #cleanupController, which is unobservable\n // (defense-in-depth: on a CANCEL the FSM CANCEL action already aborted+nulled\n // the controller via abortCurrentController, RFC §5; the success-path\n // ref-release is proven unobservable — see #cleanupController's disable). It\n // cannot be inline-`Stryker disable`d: the catch `}` and finally `{` share one\n // line, so there is no comment position that targets the finally body. Left documented.\n } finally {\n // Stryker disable next-line ConditionalExpression,BlockStatement: equivalent — listener cleanup is redundant: the per-navigation signal is discarded on completion, so skipping the removeEventListener leaks nothing observable.\n if (onExternalAbort) {\n // Stryker disable next-line StringLiteral: equivalent — cleanup event name is redundant (listener is `{ once: true }` and the signal is discarded), so a wrong name removes nothing observable.\n externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n }\n\n // Detach the abort-race listener before #cleanupController aborts the\n // controller below, so the cleanup abort cannot re-fire it. `undefined`\n // only when the controller was already aborted at setup (the early-resolve\n // branch above registered no listener).\n if (onInternalAbort) {\n controller.signal.removeEventListener(\"abort\", onInternalAbort);\n }\n\n // Success drops the controller without aborting (the subscribeLeave signal\n // must stay unaborted); cancel/error aborts it with the originating reason\n // so captured signals expose the real cause via `signal.reason` (#943).\n this.#cleanupController(controller, !succeeded, failureReason);\n }\n }\n\n #handleNavigateError(\n error: unknown,\n controller: AbortController | null,\n transitionStarted: boolean,\n toState: State | undefined,\n fromState: State | undefined,\n ): void {\n if (controller) {\n this.#cleanupController(controller, true, error);\n }\n\n if (transitionStarted && toState) {\n routeTransitionError(this.#deps, error, toState, fromState);\n }\n }\n\n #handleNoGuardsLeave(\n toState: State,\n fromState: State | undefined,\n myId: number,\n opts: NavigationOptions,\n transitionPath: TransitionPath,\n canDeactivateFunctions: Map<string, GuardFn>,\n ): Promise<State> | undefined {\n const deps = this.#deps;\n\n deps.sendLeaveApprove(toState, fromState);\n\n if (deps.hasLeaveListeners()) {\n const controller = new AbortController();\n\n // Track as the current navigation BEFORE listeners run so a reentrant\n // navigate() / stop() / dispose() from a sync listener aborts THIS leave\n // signal — parity with the guard path (#722). On success the controller is\n // released without aborting (see #cleanupController).\n this.#currentController = controller;\n\n let leaveResult: Promise<void> | undefined;\n\n try {\n leaveResult = deps.awaitLeaveListeners(\n toState,\n fromState,\n controller.signal,\n );\n } catch (error) {\n // A sync listener threw — the navigation fails; abort the leave signal\n // with the thrown value so a listener that captured the signal sees the\n // real cause via `signal.reason`, not a generic AbortError (#943).\n this.#cleanupController(controller, true, error);\n\n throw error;\n }\n\n if (leaveResult !== undefined) {\n return this.#finishAsyncNavigation(\n leaveResult,\n {\n toState,\n fromState,\n opts,\n toDeactivate: transitionPath.toDeactivate,\n toActivate: transitionPath.toActivate,\n intersection: transitionPath.intersection,\n canDeactivateFunctions,\n },\n controller,\n myId,\n );\n }\n\n // Sync listeners settled. A synchronous reentrant navigate() can no longer\n // supersede here (banned, RFC §4), so the leave always succeeds: release the\n // controller WITHOUT aborting (the subscribeLeave signal must stay live).\n this.#cleanupController(controller, false);\n\n return undefined;\n }\n\n // No leave listeners: nothing synchronous could have superseded this\n // navigation during the LEAVE_APPROVE emit (reentrant navigate is banned).\n return undefined;\n }\n\n /**\n * Release a navigation's AbortController. The same `controller.signal` is\n * handed to `subscribeLeave` listeners, so it must abort **only** when the\n * navigation is cancelled or errors — never on success (#722). On the success\n * path pass `cancelled = false`: the reference is dropped without aborting, so\n * a listener that captured the signal still sees `aborted === false`.\n *\n * On the failure/cancellation path (`cancelled = true`) pass the originating\n * `reason` so `signal.reason` carries router/error context (a `RouterError`,\n * or the value a sync leave listener threw) — consistent with the cancellation\n * abort `RouterError(TRANSITION_CANCELLED)`, not a generic `AbortError` (#943).\n * `abort()` is idempotent: a controller already aborted by a superseding\n * navigation keeps its first (also-meaningful) reason.\n */\n #cleanupController(\n controller: AbortController,\n cancelled: boolean,\n reason?: unknown,\n ): void {\n if (cancelled) {\n controller.abort(reason);\n }\n\n // Stryker disable next-line ConditionalExpression,EqualityOperator,BlockStatement: equivalent — controller identity-guard; cleanup correctness is enforced by #abortPreviousNavigation + the navigationId/isCurrentNav checks. Full suite stays green with `=== → !==` (nulls the wrong controller) and with the body removed (ref never nulled), so no mutant here is observable.\n if (this.#currentController === controller) {\n this.#currentController = null;\n }\n }\n\n #abortPreviousNavigation(externalSignal?: AbortSignal): void {\n if (this.#deps.isTransitioning()) {\n this.#deps.logger.warn(\n \"router.navigate\",\n \"Concurrent navigation detected on shared router instance. \" +\n \"For SSR, use cloneRouter() to create isolated instance per request.\",\n );\n // The FSM CANCEL action aborts the previous controller — no\n // direct controller.abort here (RFC navigation-cancellation-unification §5).\n this.#deps.cancelNavigation();\n }\n\n if (externalSignal?.aborted) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED, {\n reason: externalSignal.reason,\n });\n }\n }\n}\n"],"mappings":"iTAyBM,EAA6B,OAAO,OAAO,CAC/CA,EAAAA,UAAU,aACZ,CAAC,EACK,EAAyC,OAAO,OAAO,CAAE,QAAS,EAAK,CAAC,EAE9E,SAAS,EACP,EACA,EACmB,CACnB,OAAO,GAAW,OAASA,EAAAA,UAAU,eAAiB,CAAC,EAAK,QACxD,CAAE,GAAG,EAAM,QAAS,EAAK,EACzB,CACN,CAEA,SAAS,EACP,EACA,EACA,EACS,CACT,MACE,CAAC,CAAC,GACF,CAAC,EAAK,QACN,CAAC,EAAK,OACN,EAAU,OAAS,EAAQ,IAE/B,CAWA,IAAa,EAAb,KAAiC,CAE/B,iBAAmB,GACnB,iBAAmB,GACnB,GACA,GAA6C,KAC7C,GAAgB,EAMhB,gBAAgB,EAAoC,CAClD,KAAKC,GAAQ,CACf,CAMA,SACE,EACA,EACA,EACgB,CAChB,KAAK,iBAAmB,GACxB,IAAM,EAAO,KAAKA,GAIlB,GAAI,CAAC,EAAK,YAAY,EAIpB,M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1B,GAAgB,QAClB,MAAM,IAAIK,EAAAA,YAAYC,EAAAA,WAAW,qBAAsB,CACrD,OAAQ,EAAe,MACzB,CAAC,CAEL,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../constants.js"),t=require("../../RouterError.js"),n=new t.RouterError(e.errorCodes.ROUTER_NOT_STARTED),r=new t.RouterError(e.errorCodes.ROUTE_NOT_FOUND),i=new t.RouterError(e.errorCodes.SAME_STATES),a=Promise.reject(n),o=Promise.reject(r),s=Promise.reject(i);a.catch(()=>{}),o.catch(()=>{}),s.catch(()=>{}),exports.CACHED_NOT_STARTED_ERROR=n,exports.CACHED_NOT_STARTED_REJECTION=a,exports.CACHED_ROUTE_NOT_FOUND_ERROR=r,exports.CACHED_ROUTE_NOT_FOUND_REJECTION=o,exports.CACHED_SAME_STATES_ERROR=i,exports.CACHED_SAME_STATES_REJECTION=s;
|
|
2
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":["RouterError","errorCodes"],"sources":["../../../../src/namespaces/NavigationNamespace/constants.ts"],"sourcesContent":["// packages/core/src/namespaces/NavigationNamespace/constants.ts\n\nimport { errorCodes } from \"../../constants\";\nimport { RouterError } from \"../../RouterError\";\n\nimport type { State } from \"../../types\";\n\n// =============================================================================\n// Cached Errors & Rejected Promises (Performance Optimization)\n// =============================================================================\n// Pre-create error instances and rejected promises for sync error paths\n// in navigate(). Eliminates per-call allocations:\n// - new RouterError() — object + stack trace capture (~500ns-2μs)\n// - Promise.reject() — promise allocation\n// - .catch(handler) — derived promise from suppression\n//\n// Trade-off: All error instances share the same stack trace (points here).\n// This is acceptable because:\n// 1. These errors indicate expected conditions, not internal bugs\n// 2. Error code and message are sufficient for debugging\n// 3. The facade skips .catch() suppression for cached promises (zero alloc)\n// =============================================================================\n\nexport const CACHED_NOT_STARTED_ERROR = new RouterError(\n errorCodes.ROUTER_NOT_STARTED,\n);\n\nexport const CACHED_ROUTE_NOT_FOUND_ERROR = new RouterError(\n errorCodes.ROUTE_NOT_FOUND,\n);\n\nexport const CACHED_SAME_STATES_ERROR = new RouterError(errorCodes.SAME_STATES);\n\n// Pre-suppressed rejected promises — .catch() at module load prevents\n// unhandled rejection warnings. The facade skips additional .catch() calls\n// via the lastSyncRejected flag (zero derived-promise allocation).\nexport const CACHED_NOT_STARTED_REJECTION: Promise<State> = Promise.reject(\n CACHED_NOT_STARTED_ERROR,\n);\n\nexport const CACHED_ROUTE_NOT_FOUND_REJECTION: Promise<State> = Promise.reject(\n CACHED_ROUTE_NOT_FOUND_ERROR,\n);\n\nexport const CACHED_SAME_STATES_REJECTION: Promise<State> = Promise.reject(\n CACHED_SAME_STATES_ERROR,\n);\n\n// Suppress once at module load — prevents unhandled rejection events.\n// Subsequent .catch() / await by user code still works correctly:\n// a rejected promise stays rejected forever, each .catch() creates\n// its own derived promise and fires its handler.\nCACHED_NOT_STARTED_REJECTION.catch(() => {}); // NOSONAR -- intentional suppression, not a promise chain\nCACHED_ROUTE_NOT_FOUND_REJECTION.catch(() => {}); // NOSONAR\nCACHED_SAME_STATES_REJECTION.catch(() => {}); // NOSONAR\n"],"mappings":"wEAuBa,EAA2B,IAAIA,EAAAA,YAC1CC,EAAAA,WAAW,kBACb,EAEa,EAA+B,IAAID,EAAAA,YAC9CC,EAAAA,WAAW,eACb,EAEa,EAA2B,IAAID,EAAAA,YAAYC,EAAAA,WAAW,WAAW,EAKjE,EAA+C,QAAQ,OAClE,CACF,EAEa,EAAmD,QAAQ,OACtE,CACF,EAEa,EAA+C,QAAQ,OAClE,CACF,EAMA,EAA6B,UAAY,CAAC,CAAC,EAC3C,EAAiC,UAAY,CAAC,CAAC,EAC/C,EAA6B,UAAY,CAAC,CAAC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../RouterError.js");function n(e,t,n,r,i){Object.freeze(n),Object.freeze(r);let a={phase:`activating`,reason:`success`,segments:Object.freeze({deactivated:n,activated:r,intersection:i})};return e?.name!==void 0&&(a.from=e.name),t.reload!==void 0&&(a.reload=t.reload),t.replace!==void 0&&(a.replace=t.replace),t.redirected!==void 0&&(a.redirected=t.redirected),Object.freeze(a)}function r({signal:e,...t}){return t}function i(i,a){let{toState:o,fromState:s,opts:c,toDeactivate:l,toActivate:u,intersection:d}=a;if(o.name!==e.constants.UNKNOWN_ROUTE&&!i.hasRoute(o.name)){let n=new t.RouterError(e.errorCodes.ROUTE_NOT_FOUND,{routeName:o.name});throw i.sendTransitionFail(o,s,n),n}if(s)for(let e of l)!u.includes(e)&&a.canDeactivateFunctions.has(e)&&i.clearCanDeactivate(e);o.transition=n(s,c,l,u,d);let f=Object.freeze(o);i.setState(f);let p=c.signal===void 0?c:r(c);return i.sendTransitionDone(f,s,p),f}exports.completeTransition=i;
|
|
2
|
+
//# sourceMappingURL=completeTransition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"completeTransition.js","names":["constants","RouterError","errorCodes"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/completeTransition.ts"],"sourcesContent":["import { errorCodes, constants } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { NavigationOptions, State, TransitionMeta } from \"../../../types\";\nimport type { NavigationDependencies, NavigationContext } from \"../types\";\n\ntype MutableTransitionMeta = {\n -readonly [K in keyof TransitionMeta]: TransitionMeta[K];\n};\n\nfunction buildTransitionMeta(\n fromState: State | undefined,\n opts: NavigationOptions,\n toDeactivate: string[],\n toActivate: string[],\n intersection: string,\n): TransitionMeta {\n Object.freeze(toDeactivate);\n Object.freeze(toActivate);\n\n const segments = Object.freeze({\n deactivated: toDeactivate,\n activated: toActivate,\n intersection,\n });\n\n const meta: MutableTransitionMeta = {\n phase: \"activating\",\n reason: \"success\",\n segments,\n };\n\n if (fromState?.name !== undefined) {\n meta.from = fromState.name;\n }\n\n if (opts.reload !== undefined) {\n meta.reload = opts.reload;\n }\n\n if (opts.replace !== undefined) {\n meta.replace = opts.replace;\n }\n\n if (opts.redirected !== undefined) {\n meta.redirected = opts.redirected;\n }\n\n return Object.freeze(meta);\n}\n\nfunction stripSignal({\n signal: _,\n ...rest\n}: NavigationOptions): NavigationOptions {\n return rest;\n}\n\nexport function completeTransition(\n deps: NavigationDependencies,\n nav: NavigationContext,\n): State {\n const { toState, fromState, opts, toDeactivate, toActivate, intersection } =\n nav;\n\n if (\n toState.name !== constants.UNKNOWN_ROUTE &&\n !deps.hasRoute(toState.name)\n ) {\n const err = new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: toState.name,\n });\n\n deps.sendTransitionFail(toState, fromState, err);\n\n throw err;\n }\n\n if (fromState) {\n for (const name of toDeactivate) {\n if (!toActivate.includes(name) && nav.canDeactivateFunctions.has(name)) {\n deps.clearCanDeactivate(name);\n }\n }\n }\n\n (toState as { transition: TransitionMeta }).transition = buildTransitionMeta(\n fromState,\n opts,\n toDeactivate,\n toActivate,\n intersection,\n );\n\n const finalState = Object.freeze(toState);\n\n deps.setState(finalState);\n\n const transitionOpts = opts.signal === undefined ? opts : stripSignal(opts);\n\n deps.sendTransitionDone(finalState, fromState, transitionOpts);\n\n return finalState;\n}\n"],"mappings":"8EAUA,SAAS,EACP,EACA,EACA,EACA,EACA,EACgB,CAChB,OAAO,OAAO,CAAY,EAC1B,OAAO,OAAO,CAAU,EAQxB,IAAM,EAA8B,CAClC,MAAO,aACP,OAAQ,UACR,SATe,OAAO,OAAO,CAC7B,YAAa,EACb,UAAW,EACX,cACF,CAKS,CACT,EAkBA,OAhBI,GAAW,OAAS,IAAA,KACtB,EAAK,KAAO,EAAU,MAGpB,EAAK,SAAW,IAAA,KAClB,EAAK,OAAS,EAAK,QAGjB,EAAK,UAAY,IAAA,KACnB,EAAK,QAAU,EAAK,SAGlB,EAAK,aAAe,IAAA,KACtB,EAAK,WAAa,EAAK,YAGlB,OAAO,OAAO,CAAI,CAC3B,CAEA,SAAS,EAAY,CACnB,OAAQ,EACR,GAAG,GACoC,CACvC,OAAO,CACT,CAEA,SAAgB,EACd,EACA,EACO,CACP,GAAM,CAAE,UAAS,YAAW,OAAM,eAAc,aAAY,gBAC1D,EAEF,GACE,EAAQ,OAASA,EAAAA,UAAU,eAC3B,CAAC,EAAK,SAAS,EAAQ,IAAI,EAC3B,CACA,IAAM,EAAM,IAAIC,EAAAA,YAAYC,EAAAA,WAAW,gBAAiB,CACtD,UAAW,EAAQ,IACrB,CAAC,EAID,MAFA,EAAK,mBAAmB,EAAS,EAAW,CAAG,EAEzC,CACR,CAEA,GAAI,EACG,IAAA,IAAM,KAAQ,EACb,CAAC,EAAW,SAAS,CAAI,GAAK,EAAI,uBAAuB,IAAI,CAAI,GACnE,EAAK,mBAAmB,CAAI,EAKlC,EAA4C,WAAa,EACvD,EACA,EACA,EACA,EACA,CACF,EAEA,IAAM,EAAa,OAAO,OAAO,CAAO,EAExC,EAAK,SAAS,CAAU,EAExB,IAAM,EAAiB,EAAK,SAAW,IAAA,GAAY,EAAO,EAAY,CAAI,EAI1E,OAFA,EAAK,mBAAmB,EAAY,EAAW,CAAc,EAEtD,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../RouterError.js");function n(t,n,r,i){let a=n;a.code!==e.errorCodes.TRANSITION_CANCELLED&&a.code!==e.errorCodes.ROUTE_NOT_FOUND&&t.sendTransitionFail(r,i,a)}function r(n,r,a){if(n instanceof DOMException&&n.name===`AbortError`)throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);if(n instanceof t.RouterError&&n.code===e.errorCodes.TRANSITION_CANCELLED)throw n;i(n,r,a)}function i(e,n,r){throw e instanceof t.RouterError?(e.setCode(n),e):new t.RouterError(n,o(e,r))}const a=new Set([`code`,`segment`,`path`,`then`]);function o(e,t){let n={segment:t};if(e instanceof Error)return{...n,message:e.message,stack:e.stack,...`cause`in e&&e.cause!==void 0&&{cause:e.cause}};if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))a.has(n)||(t[n]=r);return{...n,...t}}return n}exports.handleGuardError=r,exports.rethrowAsRouterError=i,exports.routeTransitionError=n,exports.wrapSyncError=o;
|
|
2
|
+
//# sourceMappingURL=errorHandling.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errorHandling.js","names":["errorCodes","RouterError"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/errorHandling.ts"],"sourcesContent":["// packages/core/src/namespaces/NavigationNamespace/transition/errorHandling.ts\n\nimport { errorCodes } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { State } from \"../../../types\";\nimport type { NavigationDependencies } from \"../types\";\n\nexport function routeTransitionError(\n deps: NavigationDependencies,\n error: unknown,\n toState: State,\n fromState: State | undefined,\n): void {\n const routerError = error as RouterError;\n\n if (\n routerError.code === errorCodes.TRANSITION_CANCELLED ||\n routerError.code === errorCodes.ROUTE_NOT_FOUND\n ) {\n return;\n }\n\n deps.sendTransitionFail(toState, fromState, routerError);\n}\n\nexport function handleGuardError(\n error: unknown,\n errorCode: string,\n segment: string,\n): never {\n if (error instanceof DOMException && error.name === \"AbortError\") {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n // A guard can also signal a quiet cancel by throwing\n // RouterError(TRANSITION_CANCELLED) directly — the same intent as a thrown\n // AbortError. Preserve it as-is instead of letting rethrowAsRouterError\n // overwrite the code with CANNOT_ACTIVATE / CANNOT_DEACTIVATE: that code\n // drives the downstream suppression (routeTransitionError early-returns,\n // fire-and-forget stays silent), so re-coding would surface the intended\n // quiet cancel as a reported transition error (#933).\n if (\n error instanceof RouterError &&\n error.code === errorCodes.TRANSITION_CANCELLED\n ) {\n throw error;\n }\n\n rethrowAsRouterError(error, errorCode, segment);\n}\n\n/**\n * Error metadata structure for transition errors.\n * Contains information extracted from caught exceptions.\n */\nexport interface SyncErrorMetadata {\n [key: string]: unknown;\n message?: string;\n stack?: string | undefined;\n cause?: unknown;\n segment?: string;\n}\n\n/**\n * Re-throws a caught error as a RouterError with the given error code.\n * If the error is already a RouterError, sets the code directly.\n * Otherwise wraps it with wrapSyncError metadata.\n */\nexport function rethrowAsRouterError(\n error: unknown,\n errorCode: string,\n segment: string,\n): never {\n if (error instanceof RouterError) {\n error.setCode(errorCode);\n\n throw error;\n }\n\n throw new RouterError(errorCode, wrapSyncError(error, segment));\n}\n\n// Own-enumerable keys that must never be copied from a thrown object onto the\n// RouterError metadata:\n// - `code` / `segment` / `path` are reserved — the RouterError constructor\n// throws a TypeError on them (#39).\n// - `then` would make the RouterError itself thenable, so a consumer that\n// awaits it (or passes it through Promise.resolve / returns it from an async\n// function) would have it assimilated as a Promise instead of treated as a\n// plain rejection reason (#947).\nconst reservedRouterErrorProps = new Set([\"code\", \"segment\", \"path\", \"then\"]);\n\n/**\n * Wraps a synchronously thrown value into structured error metadata.\n *\n * This helper extracts useful debugging information from various thrown values:\n * - Error instances: extracts message, stack, and cause (ES2022+)\n * - Plain objects: spreads properties into metadata\n * - Primitives (string, number, etc.): returns minimal metadata\n *\n * @param thrown - The value caught in a try-catch block\n * @param segment - Route segment name (for lifecycle hooks)\n * @returns Structured error metadata for RouterError\n */\nexport function wrapSyncError(\n thrown: unknown,\n segment: string,\n): SyncErrorMetadata {\n const base: SyncErrorMetadata = { segment };\n\n // Handle Error instances - extract all useful properties\n if (thrown instanceof Error) {\n return {\n ...base,\n message: thrown.message,\n stack: thrown.stack,\n // Error.cause requires ES2022+ - safely access if present\n ...(\"cause\" in thrown &&\n thrown.cause !== undefined && { cause: thrown.cause }),\n };\n }\n\n // Handle plain objects - spread properties into metadata, filtering reserved props\n if (thrown && typeof thrown === \"object\") {\n const filtered: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(thrown)) {\n // Skip reserved / hazardous keys: #39 (constructor TypeError on code/\n // segment/path) and #947 (`then` would make the error thenable).\n if (!reservedRouterErrorProps.has(key)) {\n filtered[key] = value;\n }\n }\n\n return { ...base, ...filtered };\n }\n\n // Primitives (string, number, boolean, null, undefined, symbol, bigint)\n // Return base metadata only - the primitive value isn't useful as metadata\n return base;\n}\n"],"mappings":"8EAQA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,IAAM,EAAc,EAGlB,EAAY,OAASA,EAAAA,WAAW,sBAChC,EAAY,OAASA,EAAAA,WAAW,iBAKlC,EAAK,mBAAmB,EAAS,EAAW,CAAW,CACzD,CAEA,SAAgB,EACd,EACA,EACA,EACO,CACP,GAAI,aAAiB,cAAgB,EAAM,OAAS,aAClD,MAAM,IAAIC,EAAAA,YAAYD,EAAAA,WAAW,oBAAoB,EAUvD,GACE,aAAiBC,EAAAA,aACjB,EAAM,OAASD,EAAAA,WAAW,qBAE1B,MAAM,EAGR,EAAqB,EAAO,EAAW,CAAO,CAChD,CAmBA,SAAgB,EACd,EACA,EACA,EACO,CAOP,MANI,aAAiBC,EAAAA,aACnB,EAAM,QAAQ,CAAS,EAEjB,GAGF,IAAIA,EAAAA,YAAY,EAAW,EAAc,EAAO,CAAO,CAAC,CAChE,CAUA,MAAM,EAA2B,IAAI,IAAI,CAAC,OAAQ,UAAW,OAAQ,MAAM,CAAC,EAc5E,SAAgB,EACd,EACA,EACmB,CACnB,IAAM,EAA0B,CAAE,SAAQ,EAG1C,GAAI,aAAkB,MACpB,MAAO,CACL,GAAG,EACH,QAAS,EAAO,QAChB,MAAO,EAAO,MAEd,GAAI,UAAW,GACb,EAAO,QAAU,IAAA,IAAa,CAAE,MAAO,EAAO,KAAM,CACxD,EAIF,GAAI,GAAU,OAAO,GAAW,SAAU,CACxC,IAAM,EAAoC,CAAC,EAE3C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAM,EAGzC,EAAyB,IAAI,CAAG,IACnC,EAAS,GAAO,GAIpB,MAAO,CAAE,GAAG,EAAM,GAAG,CAAS,CAChC,CAIA,OAAO,CACT"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../../constants.js"),t=require("../../../RouterError.js"),n=require("./errorHandling.js");async function r(e,r,i){let a;try{a=await e}catch(e){n.handleGuardError(e,r,i);return}if(!a)throw new t.RouterError(r,{segment:i})}async function i(i,a,o,s,c,l,u,d,f,p){await r(f,o,p);for(let f=d;f<a.length;f++){if(!u())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);let d=a[f],p=i.get(d);if(!p)continue;let m=!1;try{m=p(s,c,l)}catch(e){n.handleGuardError(e,o,d)}if(m instanceof Promise){await r(m,o,d);continue}if(!m)throw new t.RouterError(o,{segment:d})}}async function a(n,r,i,a,o,s,l,u,d){if(await n,!u())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);let f=d();if(f!==void 0&&(await f,!u()))throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);if(a){let n=c(r,i,e.errorCodes.CANNOT_ACTIVATE,o,s,l,u);if(n!==void 0&&await n,!u())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED)}}function o(n,r,i,o,l,u,d,f,p,m,h){if(l){let t=c(n,i,e.errorCodes.CANNOT_DEACTIVATE,d,f,p,m);if(t!==void 0)return a(t,r,o,u,d,f,p,m,h)}if(!m())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);let g=h();if(g!==void 0)return s(g,u?r:void 0,o,d,f,p,m);if(u)return c(r,o,e.errorCodes.CANNOT_ACTIVATE,d,f,p,m)}async function s(n,r,i,a,o,s,l){if(await n,!l())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);if(r!==void 0){let n=c(r,i,e.errorCodes.CANNOT_ACTIVATE,a,o,s,l);if(n!==void 0&&await n,!l())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED)}}function c(r,a,o,s,c,l,u){for(let[d,f]of a.entries()){if(!u())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);let p=r.get(f);if(!p)continue;let m=!1;try{m=p(s,c,l)}catch(e){n.handleGuardError(e,o,f)}if(m instanceof Promise)return i(r,a,o,s,c,l,u,d+1,m,f);if(!m)throw new t.RouterError(o,{segment:f})}}exports.executeGuardPipeline=o;
|
|
2
|
+
//# sourceMappingURL=guardPhase.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guardPhase.js","names":["RouterError","errorCodes"],"sources":["../../../../../src/namespaces/NavigationNamespace/transition/guardPhase.ts"],"sourcesContent":["import { handleGuardError } from \"./errorHandling\";\nimport { errorCodes } from \"../../../constants\";\nimport { RouterError } from \"../../../RouterError\";\n\nimport type { GuardFn, State } from \"../../../types\";\n\nasync function resolveAsyncGuard(\n promise: Promise<boolean>,\n errorCode: string,\n segment: string,\n): Promise<void> {\n let result: boolean;\n\n try {\n result = await promise;\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n\n return; // unreachable — handleGuardError returns never\n }\n\n if (!result) {\n throw new RouterError(errorCode, { segment });\n }\n}\n\nasync function resolveRemainingGuards( // NOSONAR -- params kept flat to avoid object allocation on hot path\n guards: Map<string, GuardFn>,\n segments: string[],\n errorCode: string,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n startIndex: number,\n firstResult: Promise<boolean>,\n firstSegment: string,\n): Promise<void> {\n await resolveAsyncGuard(firstResult, errorCode, firstSegment);\n\n for (let i = startIndex; i < segments.length; i++) {\n // Stryker disable next-line BlockStatement: equivalent — emptying the body drops the async-tail cancellation throw, but supersession is independently enforced by the navigationId/isCurrentNav checks in NavigationNamespace, so the navigation still rejects with TRANSITION_CANCELLED (full suite green). The ConditionalExpression sibling stays live (its →true variant always-cancels and is killed by async-guard tests).\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const segment = segments[i];\n const guardFn = guards.get(segment);\n\n if (!guardFn) {\n continue;\n }\n\n // Stryker disable next-line BooleanLiteral: equivalent — guardResult is unconditionally reassigned by guardFn() on the next line, or the catch calls handleGuardError() (returns never), so the init value is never read.\n let guardResult: boolean | Promise<boolean> = false;\n\n try {\n guardResult = guardFn(toState, fromState, signal);\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n }\n\n if (guardResult instanceof Promise) {\n await resolveAsyncGuard(guardResult, errorCode, segment);\n continue;\n }\n\n if (!guardResult) {\n throw new RouterError(errorCode, { segment });\n }\n }\n}\n\nasync function finishAsyncPipeline( // NOSONAR\n deactivateCompletion: Promise<void>,\n activateGuards: Map<string, GuardFn>,\n toActivate: string[],\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Promise<void> {\n await deactivateCompletion;\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const leaveResult = emitLeaveApprove();\n\n if (leaveResult !== undefined) {\n await leaveResult;\n\n // Stryker disable next-line BlockStatement: equivalent — defensive-redundancy: this post-leave cancellation re-check is already enforced upstream (navigationId / isCurrentNav supersession in NavigationNamespace), so emptying the throw is unobservable. Mirrors the disabled L42/L115/L228 cancel-checks.\n /* v8 ignore next 3 -- @preserve: V8 cannot track cancellation check through async leave continuation after Promise.allSettled */\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n }\n\n if (shouldActivate) {\n const pending = runGuards(\n activateGuards,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n\n if (pending !== undefined) {\n await pending;\n }\n\n // Stryker disable next-line BlockStatement: equivalent — same async-tail cancellation throw as L42; dropping it is covered by the outer navigationId guard (full suite green). CE sibling stays live (→true killed by async-guard tests).\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n }\n}\n\nexport function executeGuardPipeline( // NOSONAR\n deactivateGuards: Map<string, GuardFn>,\n activateGuards: Map<string, GuardFn>,\n toDeactivate: string[],\n toActivate: string[],\n shouldDeactivate: boolean,\n shouldActivate: boolean,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n emitLeaveApprove: () => Promise<void> | undefined,\n): Promise<void> | undefined {\n if (shouldDeactivate) {\n const pending = runGuards(\n deactivateGuards,\n toDeactivate,\n errorCodes.CANNOT_DEACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n\n if (pending !== undefined) {\n return finishAsyncPipeline(\n pending,\n activateGuards,\n toActivate,\n shouldActivate,\n toState,\n fromState,\n signal,\n isActive,\n emitLeaveApprove,\n );\n }\n }\n\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const leaveResult = emitLeaveApprove();\n\n if (leaveResult !== undefined) {\n return finishAfterAsyncLeave(\n leaveResult,\n /* v8 ignore next -- @preserve: false-branch unreachable — navigateToNotFound bypasses guards pipeline */\n shouldActivate ? activateGuards : undefined,\n toActivate,\n toState,\n fromState,\n signal,\n isActive,\n );\n }\n\n if (shouldActivate) {\n return runGuards(\n activateGuards,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n }\n\n return undefined;\n}\n\nasync function finishAfterAsyncLeave(\n leaveCompletion: Promise<void>,\n activateGuards: Map<string, GuardFn> | undefined,\n toActivate: string[],\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal,\n isActive: () => boolean,\n): Promise<void> {\n await leaveCompletion;\n\n // Stryker disable next-line BlockStatement: equivalent — defensive-redundancy: same post-leave cancellation re-check as guardPhase's other `!isActive()` guards; supersession is enforced upstream (navigationId / isCurrentNav), so emptying the throw is unobservable.\n /* v8 ignore next 3 -- @preserve: unreachable after #663 — signal abort\n mid-leave rejects via settleLeavePromises, so `await leaveCompletion`\n throws directly instead of completing with a stale isActive() */\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n /* v8 ignore next -- @preserve: false-branch unreachable — navigateToNotFound bypasses guards pipeline */\n if (activateGuards !== undefined) {\n const pending = runGuards(\n activateGuards,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n toState,\n fromState,\n signal,\n isActive,\n );\n\n if (pending !== undefined) {\n await pending;\n }\n\n // Stryker disable next-line BlockStatement: equivalent — same async-tail cancellation throw as L42; dropping it is covered by the outer navigationId guard (full suite green). CE sibling stays live (→true killed by async-guard tests).\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n }\n}\n\nfunction runGuards(\n guards: Map<string, GuardFn>,\n segments: string[],\n errorCode: string,\n toState: State,\n fromState: State | undefined,\n signal: AbortSignal | undefined,\n isActive: () => boolean,\n): Promise<void> | undefined {\n for (const [i, segment] of segments.entries()) {\n if (!isActive()) {\n throw new RouterError(errorCodes.TRANSITION_CANCELLED);\n }\n\n const guardFn = guards.get(segment);\n\n if (!guardFn) {\n continue;\n }\n\n // Stryker disable next-line BooleanLiteral: equivalent — guardResult is unconditionally reassigned by guardFn() on the next line, or the catch calls handleGuardError() (returns never), so the init value is never read.\n let guardResult: boolean | Promise<boolean> = false;\n\n try {\n guardResult = guardFn(toState, fromState, signal);\n } catch (error: unknown) {\n handleGuardError(error, errorCode, segment);\n }\n\n if (guardResult instanceof Promise) {\n return resolveRemainingGuards(\n guards,\n segments,\n errorCode,\n toState,\n fromState,\n signal,\n isActive,\n i + 1,\n guardResult,\n segment,\n );\n }\n\n if (!guardResult) {\n throw new RouterError(errorCode, { segment });\n }\n }\n\n return undefined;\n}\n"],"mappings":"8GAMA,eAAe,EACb,EACA,EACA,EACe,CACf,IAAI,EAEJ,GAAI,CACF,EAAS,MAAM,CACjB,OAAS,EAAgB,CACvB,EAAA,iBAAiB,EAAO,EAAW,CAAO,EAE1C,MACF,CAEA,GAAI,CAAC,EACH,MAAM,IAAIA,EAAAA,YAAY,EAAW,CAAE,SAAQ,CAAC,CAEhD,CAEA,eAAe,EACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACe,CACf,MAAM,EAAkB,EAAa,EAAW,CAAY,EAE5D,IAAK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
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants.js"),t=require("./helpers.js"),n=require("./validators.js");var r=class{#e;constructor(n={}){this.#e=t.deepFreeze({...e.defaultOptions,...n})}static validateOptionsIsObject(e){n.validateOptionsIsObject(e)}get(){return this.#e}};exports.OptionsNamespace=r;
|
|
2
|
+
//# sourceMappingURL=OptionsNamespace.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OptionsNamespace.js","names":["#options","deepFreeze","defaultOptions"],"sources":["../../../../src/namespaces/OptionsNamespace/OptionsNamespace.ts"],"sourcesContent":["// packages/core/src/namespaces/OptionsNamespace/OptionsNamespace.ts\n\nimport { defaultOptions } from \"./constants\";\nimport { deepFreeze } from \"./helpers\";\nimport { validateOptionsIsObject } from \"./validators\";\n\nimport type { Options } from \"../../types\";\n\nexport class OptionsNamespace {\n readonly #options: Readonly<Options>;\n\n constructor(initialOptions: Partial<Options> = {}) {\n this.#options = deepFreeze({\n ...defaultOptions,\n ...initialOptions,\n });\n }\n\n static validateOptionsIsObject(\n options: unknown,\n ): asserts options is Record<string, unknown> {\n validateOptionsIsObject(options);\n }\n\n get(): Readonly<Options> {\n return this.#options;\n }\n}\n"],"mappings":"yFAQA,IAAa,EAAb,KAA8B,CAC5B,GAEA,YAAY,EAAmC,CAAC,EAAG,CACjD,KAAKA,GAAWC,EAAAA,WAAW,CACzB,GAAGC,EAAAA,eACH,GAAG,CACL,CAAC,CACH,CAEA,OAAO,wBACL,EAC4C,CAC5C,EAAA,wBAAwB,CAAO,CACjC,CAEA,KAAyB,CACvB,OAAO,KAAKF,EACd,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={defaultRoute:``,defaultParams:{},trailingSlash:`preserve`,caseSensitive:!0,queryParamsMode:`loose`,queryParams:require("../../engine/search-params/encode.js").DEFAULT_QUERY_PARAMS,urlParamsEncoding:`default`,allowNotFound:!0,rewritePathOnMatch:!0};exports.defaultOptions=e;
|
|
2
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":["DEFAULT_QUERY_PARAMS"],"sources":["../../../../src/namespaces/OptionsNamespace/constants.ts"],"sourcesContent":["// packages/core/src/namespaces/OptionsNamespace/constants.ts\n\nimport { DEFAULT_QUERY_PARAMS } from \"../../engine\";\n\nimport type { Options } from \"../../types\";\n\n/**\n * Default options for the router.\n */\nexport const defaultOptions: Options = {\n defaultRoute: \"\",\n defaultParams: {},\n trailingSlash: \"preserve\",\n caseSensitive: true,\n queryParamsMode: \"loose\",\n queryParams: DEFAULT_QUERY_PARAMS,\n urlParamsEncoding: \"default\",\n allowNotFound: true,\n rewritePathOnMatch: true,\n} satisfies Options;\n"],"mappings":"AASA,MAAa,EAA0B,CACrC,aAAc,GACd,cAAe,CAAC,EAChB,cAAe,WACf,cAAe,GACf,gBAAiB,QACjB,0DAAaA,CAAAA,CAAAA,qBACb,kBAAmB,UACnB,cAAe,GACf,mBAAoB,EACtB"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.js","names":[],"sources":["../../../../src/namespaces/OptionsNamespace/helpers.ts"],"sourcesContent":["// packages/core/src/namespaces/OptionsNamespace/helpers.ts\n\nimport type { Options, Params } from \"../../types\";\n\n/**\n * Recursively freezes an object and all nested objects.\n * Only freezes plain objects, not primitives or special objects.\n */\nexport function deepFreeze<T extends object>(obj: T): Readonly<T> {\n Object.freeze(obj);\n\n for (const value of Object.values(obj as Record<string, unknown>)) {\n if (value && typeof value === \"object\" && value.constructor === Object) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\n/**\n * Resolves an option value that can be static or a callback.\n * If the value is a function, calls it with getDependency and returns the result.\n * Otherwise, returns the value as-is.\n */\nexport function resolveOption(\n value: Options[\"defaultRoute\"],\n getDependency: (name: string) => unknown,\n): string;\n\nexport function resolveOption(\n value: Options[\"defaultParams\"],\n getDependency: (name: string) => unknown,\n): Params;\n\nexport function resolveOption(\n value: Options[\"defaultRoute\"] | Options[\"defaultParams\"],\n getDependency: (name: string) => unknown,\n): string | Params {\n if (typeof value === \"function\") {\n // Runtime getDependency is (name: string) => unknown, but DefaultRouteCallback<object>\n // expects <K extends keyof object>(name: K) => object[K] where keyof object = never.\n // Cast needed to bridge generic constraint mismatch.\n return value(getDependency as never);\n }\n\n return value;\n}\n"],"mappings":"AAQA,SAAgB,EAA6B,EAAqB,CAChE,OAAO,OAAO,CAAG,EAEjB,IAAK,IAAM,KAAS,OAAO,OAAO,CAA8B,EAC1D,GAAS,OAAO,GAAU,UAAY,EAAM,cAAgB,QAC9D,EAAW,CAAK,EAIpB,OAAO,CACT,CAiBA,SAAgB,EACd,EACA,EACiB,CAQjB,OAPI,OAAO,GAAU,WAIZ,EAAM,CAAsB,EAG9B,CACT"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.js","names":[],"sources":["../../../../src/namespaces/OptionsNamespace/validators.ts"],"sourcesContent":["// packages/core/src/namespaces/OptionsNamespace/validators.ts\n\n/**\n * Minimal crash guard for options.\n * Full DX validation moved to @real-router/validation-plugin (retrospective pattern).\n */\nexport function validateOptionsIsObject(\n options: unknown,\n): asserts options is Record<string, unknown> {\n if (!options || typeof options !== \"object\" || Array.isArray(options)) {\n throw new TypeError(\"[router.constructor] options must be a plain object\");\n }\n}\n"],"mappings":"AAMA,SAAgB,EACd,EAC4C,CAC5C,GAAI,CAAC,GAAW,OAAO,GAAY,UAAY,MAAM,QAAQ,CAAO,EAClE,MAAU,UAAU,qDAAqD,CAE7E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./constants.js"),t=require("./validators.js");var n=class n{#e=new Set;#t=new Set;#n;static validatePlugin(e){t.validatePlugin(e)}setDependencies(e){this.#n=e}count(){return this.#e.size}use(...t){if(this.#n.getValidator()?.plugins.validateCountThresholds(this.#e.size+t.length),t.length===1){let n=t[0],r=this.#i(n);this.#e.add(n);let i=!1,a=()=>{if(!i){i=!0,this.#e.delete(n),this.#t.delete(a);try{r()}catch(t){this.#n.logger.error(e.LOGGER_CONTEXT,`Error during cleanup:`,t)}}};return this.#t.add(a),a}let n=this.#r(t),r=[];try{for(let e of n){let t=this.#i(e);r.push({factory:e,cleanup:t})}}catch(t){for(let{cleanup:t}of r)try{t()}catch(t){this.#n.logger.error(e.LOGGER_CONTEXT,`Cleanup error:`,t)}throw t}for(let{factory:e}of r)this.#e.add(e);let i=!1,a=()=>{if(!i){i=!0,this.#t.delete(a);for(let{factory:e}of r)this.#e.delete(e);for(let{cleanup:t}of r)try{t()}catch(t){this.#n.logger.error(e.LOGGER_CONTEXT,`Error during cleanup:`,t)}}};return this.#t.add(a),a}getAll(){return[...this.#e]}has(e){return this.#e.has(e)}disposeAll(){for(let e of this.#t)e();this.#e.clear(),this.#t.clear()}#r(e){let t=new Set;for(let n of e)t.has(n)?this.#n.getValidator()?.plugins.warnBatchDuplicates(e):t.add(n);return t}#i(t){let r=this.#n.compileFactory(t);n.validatePlugin(r),this.#n.getValidator()?.plugins.validatePluginKeys(r),Object.freeze(r);let i=[];for(let t of e.EVENT_METHOD_NAMES)t in r&&(typeof r[t]==`function`?(i.push(this.#n.addEventListener(e.EVENTS_MAP[t],r[t])),t===`onStart`&&this.#n.canNavigate()&&this.#n.getValidator()?.plugins.warnPluginAfterStart(t)):this.#n.getValidator()?.plugins.warnPluginMethodType(t));return()=>{for(let e of i)e();typeof r.teardown==`function`&&r.teardown()}}};exports.PluginsNamespace=n;
|
|
2
|
+
//# sourceMappingURL=PluginsNamespace.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"PluginsNamespace.js","names":["#plugins","#unsubscribes","#deps","#startPlugin","LOGGER_CONTEXT","#deduplicateBatch","EVENT_METHOD_NAMES","EVENTS_MAP"],"sources":["../../../../src/namespaces/PluginsNamespace/PluginsNamespace.ts"],"sourcesContent":["// packages/core/src/namespaces/PluginsNamespace/PluginsNamespace.ts\n\nimport { EVENTS_MAP, EVENT_METHOD_NAMES, LOGGER_CONTEXT } from \"./constants\";\nimport { validatePlugin } from \"./validators\";\n\nimport type { PluginsDependencies } from \"./types\";\nimport type {\n DefaultDependencies,\n Plugin,\n Unsubscribe,\n PluginFactory,\n} from \"../../types\";\n\n/**\n * Independent namespace for managing plugins.\n *\n * Static methods handle validation (called by facade).\n * Instance methods handle storage and business logic.\n */\nexport class PluginsNamespace<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> {\n readonly #plugins = new Set<PluginFactory<Dependencies>>();\n readonly #unsubscribes = new Set<Unsubscribe>();\n\n #deps!: PluginsDependencies<Dependencies>;\n\n // =========================================================================\n // Static validation methods (called by facade before instance methods)\n // Proxy to functions in validators.ts for separation of concerns\n // =========================================================================\n\n static validatePlugin(plugin: Plugin): void {\n validatePlugin(plugin);\n }\n\n // =========================================================================\n // Dependency injection\n // =========================================================================\n\n setDependencies(deps: PluginsDependencies<Dependencies>): void {\n this.#deps = deps;\n }\n\n // =========================================================================\n // Instance methods (trust input - already validated by facade)\n // =========================================================================\n\n /**\n * Returns the number of registered plugins.\n * Used by facade for limit validation.\n */\n /* v8 ignore next 3 -- @preserve: only called via validator interface (ctx.validator?.plugins.validatePluginLimit), not reachable without validation plugin */\n count(): number {\n return this.#plugins.size;\n }\n\n /**\n * Registers one or more plugin factories.\n * Returns unsubscribe function to remove all added plugins.\n * Input already validated by facade (limit, duplicates).\n *\n * @param factories - Already validated by facade\n */\n use(...factories: PluginFactory<Dependencies>[]): Unsubscribe {\n // Emit warnings for count thresholds (not validation, just warnings)\n this.#deps\n .getValidator()\n ?.plugins.validateCountThresholds(this.#plugins.size + factories.length);\n\n // Fast path for single plugin (common case)\n if (factories.length === 1) {\n const factory = factories[0];\n const cleanup = this.#startPlugin(factory);\n\n this.#plugins.add(factory);\n\n let unsubscribed = false;\n\n const unsubscribe: Unsubscribe = () => {\n if (unsubscribed) {\n return;\n }\n\n unsubscribed = true;\n this.#plugins.delete(factory);\n this.#unsubscribes.delete(unsubscribe);\n try {\n cleanup();\n } catch (error) {\n this.#deps.logger.error(\n LOGGER_CONTEXT,\n \"Error during cleanup:\",\n error,\n );\n }\n };\n\n this.#unsubscribes.add(unsubscribe);\n\n return unsubscribe;\n }\n\n // Deduplicate batch with warning (validation already done by facade)\n const seenInBatch = this.#deduplicateBatch(factories);\n\n // Track successfully initialized plugins for cleanup\n const initializedPlugins: {\n factory: PluginFactory<Dependencies>;\n cleanup: Unsubscribe;\n }[] = [];\n\n // Initialize deduplicated plugins sequentially\n try {\n for (const plugin of seenInBatch) {\n const cleanup = this.#startPlugin(plugin);\n\n initializedPlugins.push({ factory: plugin, cleanup });\n }\n } catch (error) {\n // Rollback on failure - cleanup all initialized plugins\n for (const { cleanup } of initializedPlugins) {\n try {\n cleanup();\n } catch (cleanupError) {\n this.#deps.logger.error(\n LOGGER_CONTEXT,\n \"Cleanup error:\",\n cleanupError,\n );\n }\n }\n\n throw error;\n }\n\n // Commit phase - add to registry\n for (const { factory } of initializedPlugins) {\n this.#plugins.add(factory);\n }\n\n // Return unsubscribe function\n let unsubscribed = false;\n\n const unsubscribe: Unsubscribe = () => {\n if (unsubscribed) {\n return;\n }\n\n unsubscribed = true;\n this.#unsubscribes.delete(unsubscribe);\n\n for (const { factory } of initializedPlugins) {\n this.#plugins.delete(factory);\n }\n\n for (const { cleanup } of initializedPlugins) {\n try {\n cleanup();\n } catch (error) {\n this.#deps.logger.error(\n LOGGER_CONTEXT,\n \"Error during cleanup:\",\n error,\n );\n }\n }\n };\n\n this.#unsubscribes.add(unsubscribe);\n\n return unsubscribe;\n }\n\n /**\n * Returns registered plugin factories.\n */\n getAll(): PluginFactory<Dependencies>[] {\n return [...this.#plugins];\n }\n\n /**\n * Checks if a plugin factory is registered.\n * Used internally by validation to avoid array allocation.\n */\n /* v8 ignore next 3 -- @preserve: only called via validator interface, not reachable without validation plugin */\n has(factory: PluginFactory<Dependencies>): boolean {\n return this.#plugins.has(factory);\n }\n\n /**\n * Disposes all registered plugins by running their teardown callbacks\n * and removing event listener subscriptions.\n * Active disposal is required because plugins have an active lifecycle\n * (event subscriptions, teardown hooks).\n * Named \"dispose\" (not \"clear\") because there is active cleanup to perform.\n */\n disposeAll(): void {\n for (const unsubscribe of this.#unsubscribes) {\n unsubscribe();\n }\n\n this.#plugins.clear();\n this.#unsubscribes.clear();\n }\n\n // =========================================================================\n // Private methods\n // =========================================================================\n\n /**\n * Deduplicates batch with warning for duplicates within batch.\n * Validation (existing duplicates) is done by facade.\n */\n #deduplicateBatch(\n plugins: PluginFactory<Dependencies>[],\n ): Set<PluginFactory<Dependencies>> {\n const seenInBatch = new Set<PluginFactory<Dependencies>>();\n\n for (const plugin of plugins) {\n if (seenInBatch.has(plugin)) {\n this.#deps.getValidator()?.plugins.warnBatchDuplicates(plugins);\n } else {\n seenInBatch.add(plugin);\n }\n }\n\n return seenInBatch;\n }\n\n #startPlugin(pluginFactory: PluginFactory<Dependencies>): Unsubscribe {\n const appliedPlugin = this.#deps.compileFactory(pluginFactory);\n\n PluginsNamespace.validatePlugin(appliedPlugin);\n this.#deps.getValidator()?.plugins.validatePluginKeys(appliedPlugin);\n\n Object.freeze(appliedPlugin);\n\n // Collect all unsubscribe functions\n const removeEventListeners: Unsubscribe[] = [];\n\n // Subscribe plugin methods to corresponding router events\n for (const methodName of EVENT_METHOD_NAMES) {\n if (methodName in appliedPlugin) {\n if (typeof appliedPlugin[methodName] === \"function\") {\n removeEventListeners.push(\n this.#deps.addEventListener(\n EVENTS_MAP[methodName],\n appliedPlugin[methodName],\n ),\n );\n\n if (methodName === \"onStart\" && this.#deps.canNavigate()) {\n this.#deps.getValidator()?.plugins.warnPluginAfterStart(methodName);\n }\n } else {\n this.#deps.getValidator()?.plugins.warnPluginMethodType(methodName);\n }\n }\n }\n\n // Return composite cleanup function\n return () => {\n for (const removeListener of removeEventListeners) {\n removeListener();\n }\n\n if (typeof appliedPlugin.teardown === \"function\") {\n appliedPlugin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GAMxE,UAAa,CACX,IAAK,IAAM,KAAkB,EAC3B,EAAe,EAGb,OAAO,EAAc,UAAa,YACpC,EAAc,SAAS,CAE3B,CACF,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../constants.js"),t={[e.plugins.ROUTER_START]:e.events.ROUTER_START,[e.plugins.ROUTER_STOP]:e.events.ROUTER_STOP,[e.plugins.TRANSITION_SUCCESS]:e.events.TRANSITION_SUCCESS,[e.plugins.TRANSITION_START]:e.events.TRANSITION_START,[e.plugins.TRANSITION_LEAVE_APPROVE]:e.events.TRANSITION_LEAVE_APPROVE,[e.plugins.TRANSITION_ERROR]:e.events.TRANSITION_ERROR,[e.plugins.TRANSITION_CANCEL]:e.events.TRANSITION_CANCEL},n=Object.keys(t);exports.EVENTS_MAP=t,exports.EVENT_METHOD_NAMES=n,exports.LOGGER_CONTEXT=`router.usePlugin`;
|
|
2
|
+
//# sourceMappingURL=constants.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.js","names":["PLUGINS_CONST","EVENTS_CONST"],"sources":["../../../../src/namespaces/PluginsNamespace/constants.ts"],"sourcesContent":["// packages/core/src/namespaces/PluginsNamespace/constants.ts\n\nimport {\n events as EVENTS_CONST,\n plugins as PLUGINS_CONST,\n} from \"../../constants\";\n\nimport type { EventName } from \"../../types\";\n\n/**\n * Maps plugin method names to router event names.\n */\nexport const EVENTS_MAP = {\n [PLUGINS_CONST.ROUTER_START]: EVENTS_CONST.ROUTER_START,\n [PLUGINS_CONST.ROUTER_STOP]: EVENTS_CONST.ROUTER_STOP,\n [PLUGINS_CONST.TRANSITION_SUCCESS]: EVENTS_CONST.TRANSITION_SUCCESS,\n [PLUGINS_CONST.TRANSITION_START]: EVENTS_CONST.TRANSITION_START,\n [PLUGINS_CONST.TRANSITION_LEAVE_APPROVE]:\n EVENTS_CONST.TRANSITION_LEAVE_APPROVE,\n [PLUGINS_CONST.TRANSITION_ERROR]: EVENTS_CONST.TRANSITION_ERROR,\n [PLUGINS_CONST.TRANSITION_CANCEL]: EVENTS_CONST.TRANSITION_CANCEL,\n} as const satisfies Record<\n (typeof PLUGINS_CONST)[keyof typeof PLUGINS_CONST],\n EventName\n>;\n\n/**\n * Plugin method names that correspond to router events.\n */\nexport const EVENT_METHOD_NAMES = Object.keys(\n EVENTS_MAP,\n) as (keyof typeof EVENTS_MAP)[];\n\nexport const LOGGER_CONTEXT = \"router.usePlugin\";\n"],"mappings":"sCAYa,EAAa,EACvBA,EAAAA,QAAc,cAAeC,EAAAA,OAAa,cAC1CD,EAAAA,QAAc,aAAcC,EAAAA,OAAa,aACzCD,EAAAA,QAAc,oBAAqBC,EAAAA,OAAa,oBAChDD,EAAAA,QAAc,kBAAmBC,EAAAA,OAAa,kBAC9CD,EAAAA,QAAc,0BACbC,EAAAA,OAAa,0BACdD,EAAAA,QAAc,kBAAmBC,EAAAA,OAAa,kBAC9CD,EAAAA,QAAc,mBAAoBC,EAAAA,OAAa,iBAClD,EAQa,EAAqB,OAAO,KACvC,CACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){if(!(e&&typeof e==`object`)||Array.isArray(e))throw TypeError(`[router.usePlugin] Plugin factory must return an object, got ${typeof e}`);if(typeof e.then==`function`)throw TypeError(`[router.usePlugin] Async plugin factories are not supported. Factory returned a Promise instead of a plugin object.`)}exports.validatePlugin=e;
|
|
2
|
+
//# sourceMappingURL=validators.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validators.js","names":[],"sources":["../../../../src/namespaces/PluginsNamespace/validators.ts"],"sourcesContent":["// packages/core/src/namespaces/PluginsNamespace/validators.ts\n\n/**\n * Static validation functions for PluginsNamespace.\n * Called by Router facade before instance methods.\n */\n\nimport type { Plugin } from \"../../types\";\n\n/**\n * Validates that a plugin factory returned a valid plugin object.\n */\nexport function validatePlugin(plugin: Plugin): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!(plugin && typeof plugin === \"object\") || Array.isArray(plugin)) {\n throw new TypeError(\n `[router.usePlugin] Plugin factory must return an object, got ${typeof plugin}`,\n );\n }\n\n // Detect async factory (returns Promise)\n if (typeof (plugin as unknown as { then?: unknown }).then === \"function\") {\n throw new TypeError(\n `[router.usePlugin] Async plugin factories are not supported. ` +\n `Factory returned a Promise instead of a plugin object.`,\n );\n }\n}\n"],"mappings":"AAYA,SAAgB,EAAe,EAAsB,CAEnD,GAAI,EAAE,GAAU,OAAO,GAAW,WAAa,MAAM,QAAQ,CAAM,EACjE,MAAU,UACR,gEAAgE,OAAO,GACzE,EAIF,GAAI,OAAQ,EAAyC,MAAS,WAC5D,MAAU,UACR,qHAEF,CAEJ"}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { State } from "../../types/base.js";
|
|
2
|
+
import { DefaultDependencies, GuardFn, GuardFnFactory } from "../../types/router.js";
|
|
3
|
+
import { RouteLifecycleDependencies } from "./types.js";
|
|
4
|
+
//#region src/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Origin lane for a guard clear. Every `clearCanActivate` / `clearCanDeactivate`
|
|
7
|
+
* caller names its lane — there is no origin-blind default — so a new call site
|
|
8
|
+
* cannot silently wipe both the route-config and the external guard (#1171):
|
|
9
|
+
*
|
|
10
|
+
* - `"definition"` — clear only the route-config guard (`update(name, {…: null})`, #952).
|
|
11
|
+
* - `"external"` — clear only the external, component-managed guard
|
|
12
|
+
* (`removeXGuard()` and post-leave auto-cleanup — the inverse of `addXGuard()`).
|
|
13
|
+
* - `"both"` — clear both (route removal / router teardown; the route is gone).
|
|
14
|
+
*/
|
|
15
|
+
type GuardClearScope = "definition" | "external" | "both";
|
|
16
|
+
/**
|
|
17
|
+
* Source of truth for `canActivate` / `canDeactivate` guards.
|
|
18
|
+
*
|
|
19
|
+
* Storage is split by origin into four factory Maps (definition vs external,
|
|
20
|
+
* each ×activate/deactivate); a single compiled-function Map per kind backs
|
|
21
|
+
* navigation ("external wins" — when a route holds both a definition and an
|
|
22
|
+
* external guard, the compiled guard is the external one, regardless of
|
|
23
|
+
* registration order; #1174). `getFunctions()` returns a cached
|
|
24
|
+
* `[deactivate, activate]` tuple for the hot path (stable reference, no
|
|
25
|
+
* per-navigate allocation).
|
|
26
|
+
*
|
|
27
|
+
* All input validation is handled upstream by `getLifecycleApi` and
|
|
28
|
+
* `getRoutesApi` — this class has no static methods.
|
|
29
|
+
*
|
|
30
|
+
* **Ordering convention.** Every paired surface lists **deactivate before
|
|
31
|
+
* activate**: `getFunctions()` / `getFactories()` return `[deactivate,
|
|
32
|
+
* activate]`, `getFactoriesByOrigin()` returns that tuple per origin, and
|
|
33
|
+
* `canNavigateTo(toDeactivate, toActivate, …)` takes deactivate first. Keep
|
|
34
|
+
* any new paired surface consistent with this order.
|
|
35
|
+
*/
|
|
36
|
+
declare class RouteLifecycleNamespace<Dependencies extends DefaultDependencies = DefaultDependencies> {
|
|
37
|
+
#private;
|
|
38
|
+
setDependencies(deps: RouteLifecycleDependencies<Dependencies>): void;
|
|
39
|
+
getHandlerCount(type: "activate" | "deactivate"): number;
|
|
40
|
+
/**
|
|
41
|
+
* Pre-flights the #961 handler-limit `RangeError` into the route-CRUD PREPARE
|
|
42
|
+
* phase (#1046). `#registerHandler`'s per-slot limit check throws AFTER the
|
|
43
|
+
* tree/config swap, so `add`/`replace`/`update` tore post-commit when the
|
|
44
|
+
* validator was installed and the per-type count was at `maxLifecycleHandlers`.
|
|
45
|
+
* Running the same check here — before any store mutation — restores atomicity
|
|
46
|
+
* (#951/#956/#698): a batch that would exceed the limit aborts before a single
|
|
47
|
+
* write.
|
|
48
|
+
*
|
|
49
|
+
* Only NEW slots count (an overwrite leaves the union count unchanged, mirroring
|
|
50
|
+
* `#registerHandler`). For `replace` (`clearsDefinition = true`) the definition
|
|
51
|
+
* guards are about to be cleared, so the projection runs against the surviving
|
|
52
|
+
* EXTERNAL guards only — exactly the post-clear state the install loop sees.
|
|
53
|
+
* Plugin-gated: a no-op without the validator (the limit is opt-in).
|
|
54
|
+
*
|
|
55
|
+
* @param activateNames - route names a `canActivate` would be registered for
|
|
56
|
+
* @param deactivateNames - route names a `canDeactivate` would be registered for
|
|
57
|
+
* @param clearsDefinition - true for `replace` (definition guards cleared first)
|
|
58
|
+
*/
|
|
59
|
+
preflightHandlerLimit(activateNames: Iterable<string>, deactivateNames: Iterable<string>, clearsDefinition: boolean): void;
|
|
60
|
+
/**
|
|
61
|
+
* Adds a canActivate guard for a route.
|
|
62
|
+
*
|
|
63
|
+
* @param name - Route name (input-validated by facade)
|
|
64
|
+
* @param handler - Guard function or boolean (input-validated by facade)
|
|
65
|
+
* @param isFromDefinition - True when guard comes from route definition
|
|
66
|
+
* (lands in the definition Map; subject to `clearDefinitionGuards()`).
|
|
67
|
+
* False (default) when added via `getLifecycleApi().addActivateGuard(...)`
|
|
68
|
+
* (lands in the external Map; survives `replace()`).
|
|
69
|
+
*
|
|
70
|
+
* External wins at runtime (#1174): when a route holds both a definition and
|
|
71
|
+
* an external guard, the compiled function is the external one, regardless of
|
|
72
|
+
* registration order. Within one origin the most recent add overwrites. Origin
|
|
73
|
+
* determines which Map the factory is filed under (relevant for
|
|
74
|
+
* `clearDefinitionGuards()` and `cloneRouter` re-registration).
|
|
75
|
+
*/
|
|
76
|
+
addCanActivate(name: string, handler: GuardFnFactory<Dependencies> | boolean, isFromDefinition?: boolean, precompiledFn?: GuardFn): void;
|
|
77
|
+
/**
|
|
78
|
+
* Adds a canDeactivate guard for a route.
|
|
79
|
+
*
|
|
80
|
+
* Symmetric counterpart to {@link addCanActivate}.
|
|
81
|
+
*/
|
|
82
|
+
addCanDeactivate(name: string, handler: GuardFnFactory<Dependencies> | boolean, isFromDefinition?: boolean, precompiledFn?: GuardFn): void;
|
|
83
|
+
/**
|
|
84
|
+
* Removes a canActivate guard for a route. `scope` names the origin lane
|
|
85
|
+
* (see {@link GuardClearScope}) — there is no origin-blind default, so every
|
|
86
|
+
* caller commits to a lane and a new call site cannot silently clear both.
|
|
87
|
+
* Delegates to {@link #clearGuard} (mirrors the add side's `#registerHandler`).
|
|
88
|
+
*
|
|
89
|
+
* @param name - Route name (already validated by facade)
|
|
90
|
+
* @param scope - Which origin(s) to clear: `"definition"` / `"external"` / `"both"`
|
|
91
|
+
*/
|
|
92
|
+
clearCanActivate(name: string, scope: GuardClearScope): void;
|
|
93
|
+
/**
|
|
94
|
+
* Removes a canDeactivate guard for a route. Symmetric counterpart to
|
|
95
|
+
* {@link clearCanActivate}.
|
|
96
|
+
*
|
|
97
|
+
* The `"external"` lane is what makes a route-config `canDeactivate` durable:
|
|
98
|
+
* post-leave auto-cleanup (`completeTransition`) and `removeDeactivateGuard()`
|
|
99
|
+
* unregister only the external, component-managed guard (router5 mount/unmount
|
|
100
|
+
* heritage), while a definition guard survives for re-entry — symmetric with
|
|
101
|
+
* definition `canActivate`, which lives as long as the route is in the tree
|
|
102
|
+
* (#1171). Clearing both by default made a config guard one-shot: the first
|
|
103
|
+
* permitted leave erased it, so re-entry was unguarded, `getRoutesApi().get()`
|
|
104
|
+
* lost the field, and a clone taken after the leave never received it
|
|
105
|
+
* (clone invariant #6).
|
|
106
|
+
*
|
|
107
|
+
* @param name - Route name (already validated by facade)
|
|
108
|
+
* @param scope - Which origin(s) to clear: `"definition"` / `"external"` / `"both"`
|
|
109
|
+
*/
|
|
110
|
+
clearCanDeactivate(name: string, scope: GuardClearScope): void;
|
|
111
|
+
/**
|
|
112
|
+
* Clears all lifecycle handlers (canActivate and canDeactivate).
|
|
113
|
+
* Used by clearRoutes to reset all lifecycle state.
|
|
114
|
+
*/
|
|
115
|
+
clearAll(): void;
|
|
116
|
+
/**
|
|
117
|
+
* Clears only lifecycle handlers that were registered from route definitions.
|
|
118
|
+
* Used by HMR `replace()` to remove definition-sourced guards without
|
|
119
|
+
* touching externally-added guards.
|
|
120
|
+
*
|
|
121
|
+
* For a slot where BOTH a definition and an external guard exist, the external
|
|
122
|
+
* factory survives — and the compiled function is RECOMPILED from it (#1192).
|
|
123
|
+
* Under external-wins (#1174) the compiled slot is already the external guard,
|
|
124
|
+
* so this recompile is idempotent — it re-derives the surviving external factory
|
|
125
|
+
* through the same choke point that keeps clearing correct (and stays robust if
|
|
126
|
+
* the compiled slot were ever out of sync). For a definition-only slot, the
|
|
127
|
+
* compiled function is dropped.
|
|
128
|
+
*/
|
|
129
|
+
clearDefinitionGuards(): void;
|
|
130
|
+
/**
|
|
131
|
+
* Returns lifecycle factories as a flat `[deactivate, activate]` tuple of
|
|
132
|
+
* `Record<name, factory>` — the effective view where external wins over
|
|
133
|
+
* definition for the same slot. Used by `getRoutesApi` to enrich route
|
|
134
|
+
* objects with their current canActivate / canDeactivate factories and by
|
|
135
|
+
* the route-removal cleanup path.
|
|
136
|
+
*
|
|
137
|
+
* For cloneRouter (which needs to preserve origin on re-registration), use
|
|
138
|
+
* {@link getFactoriesByOrigin} instead.
|
|
139
|
+
*/
|
|
140
|
+
getFactories(): [Record<string, GuardFnFactory<Dependencies>>, Record<string, GuardFnFactory<Dependencies>>];
|
|
141
|
+
/**
|
|
142
|
+
* Returns factories tagged by origin — definition and external as separate
|
|
143
|
+
* `[deactivate, activate]` tuples. Used by `cloneRouter` to re-register
|
|
144
|
+
* guards on the clone with their original origin flag preserved.
|
|
145
|
+
*/
|
|
146
|
+
getFactoriesByOrigin(): {
|
|
147
|
+
definition: [Record<string, GuardFnFactory<Dependencies>>, Record<string, GuardFnFactory<Dependencies>>];
|
|
148
|
+
external: [Record<string, GuardFnFactory<Dependencies>>, Record<string, GuardFnFactory<Dependencies>>];
|
|
149
|
+
};
|
|
150
|
+
/**
|
|
151
|
+
* Returns compiled lifecycle functions for transition execution.
|
|
152
|
+
*
|
|
153
|
+
* @returns Tuple of [canDeactivateFunctions, canActivateFunctions] as Maps
|
|
154
|
+
*/
|
|
155
|
+
getFunctions(): [Map<string, GuardFn>, Map<string, GuardFn>];
|
|
156
|
+
canNavigateTo(toDeactivate: string[], toActivate: string[], toState: State, fromState: State | undefined): boolean;
|
|
157
|
+
/**
|
|
158
|
+
* Compiles a guard factory to its `GuardFn` WITHOUT registering it — surfaces
|
|
159
|
+
* a throwing / non-function factory eagerly. The prepare-then-commit
|
|
160
|
+
* add/replace path (`adoptRouteArtifacts`) calls this for every pending guard
|
|
161
|
+
* BEFORE the store swap (#956), so a malformed factory aborts the mutation
|
|
162
|
+
* with the store untouched. The returned function is then installed via the
|
|
163
|
+
* `precompiledFn` argument of {@link addCanActivate} / {@link addCanDeactivate}
|
|
164
|
+
* — no re-compile, so a factory with compile-time side effects runs exactly
|
|
165
|
+
* once. Same boolean-shorthand handling + compile + non-function check as the
|
|
166
|
+
* inline `#registerHandler` path, so a route-config `canActivate: true`
|
|
167
|
+
* (boolean shorthand, runtime-reachable via the public route type) compiles to
|
|
168
|
+
* the cached `TRUE_GUARD`/`FALSE_GUARD` instead of throwing on a non-callable.
|
|
169
|
+
*/
|
|
170
|
+
compileGuardFactory(handler: GuardFnFactory<Dependencies> | boolean, methodName: string): GuardFn;
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
export { GuardClearScope, RouteLifecycleNamespace };
|
|
174
|
+
//# sourceMappingURL=RouteLifecycleNamespace.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouteLifecycleNamespace.d.ts","names":[],"sources":["../../../../src/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.ts"],"mappings":";;;;;;;;;;;;;;KAuCY;;;;;;;;;;;;;;;;;;;;;cAsBC,wBACX,qBAAqB,sBAAsB;;EAuC3C,gBAAgB,MAAM,2BAA2B;EAIjD,gBAAgB;;;;;;;;;;;;;;;;;;;;EA8ChB,sBACE,eAAe,kBACf,iBAAiB,kBACjB;;;;;;;;;;;;;;;;;EAuEF,eACE,cACA,SAAS,eAAe,yBACxB,4BACA,gBAAgB;;;;;;EAiBlB,iBACE,cACA,SAAS,eAAe,yBACxB,4BACA,gBAAgB;;;;;;;;;;EAqBlB,iBAAiB,cAAc,OAAO;;;;;;;;;;;;;;;;;;EAqBtC,mBAAmB,cAAc,OAAO;;;;;EAQxC;;;;;;;;;;;;;;EAsBA;;;;;;;;;;;EA+BA,iBACE,eAAe,eAAe,gBAC9B,eAAe,eAAe;;;;;;EA2BhC;IACE,aACE,eAAe,eAAe,gBAC9B,eAAe,eAAe;IAEhC,WACE,eAAe,eAAe,gBAC9B,eAAe,eAAe;;;;;;;EAgClC,iBAAiB,YAAY,UAAU,YAAY;EAInD,cACE,wBACA,sBACA,SAAS,OACT,WAAW;;;;;;;;;;;;;;EA8Cb,oBACE,SAAS,eAAe,yBACxB,qBACC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=()=>!0,t=()=>!1,n=()=>e,r=()=>t;function i(e){return e?n:r}var a=class{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=new Map;#a=new Map;#o=[this.#i,this.#a];#s;setDependencies(e){this.#s=e}getHandlerCount(e){let t=e===`activate`?this.#e:this.#n,n=e===`activate`?this.#t:this.#r;if(t.size===0)return n.size;if(n.size===0)return t.size;let r=new Set(t.keys());for(let e of n.keys())r.add(e);return r.size}preflightHandlerLimit(e,t,n){let r=this.#s.getValidator();if(!r)return;let i=(e,t,i)=>{let{definition:a,external:o}=this.#d(e),s=0;for(let e of t)(n?o.has(e):a.has(e)||o.has(e))||s++;if(s===0)return;let c=n?o.size:this.getHandlerCount(e);r.lifecycle.validateHandlerLimit(c+s-1,i)};i(`activate`,e,`canActivate`),i(`deactivate`,t,`canDeactivate`)}addCanActivate(e,t,n=!1,r){this.#c(`activate`,e,t,n,`canActivate`,r)}addCanDeactivate(e,t,n=!1,r){this.#c(`deactivate`,e,t,n,`canDeactivate`,r)}clearCanActivate(e,t){this.#l(`activate`,e,t)}clearCanDeactivate(e,t){this.#l(`deactivate`,e,t)}clearAll(){this.#e.clear(),this.#t.clear(),this.#n.clear(),this.#r.clear(),this.#a.clear(),this.#i.clear()}clearDefinitionGuards(){for(let e of this.#e.keys())this.#t.has(e)?this.#u(`activate`,e):this.#a.delete(e);for(let e of this.#n.keys())this.#r.has(e)?this.#u(`deactivate`,e):this.#i.delete(e);this.#e.clear(),this.#n.clear()}getFactories(){let e={},t={};for(let[t,n]of this.#n)e[t]=n;for(let[t,n]of this.#r)e[t]=n;for(let[e,n]of this.#e)t[e]=n;for(let[e,n]of this.#t)t[e]=n;return[e,t]}getFactoriesByOrigin(){let e={},t={},n={},r={};for(let[t,n]of this.#n)e[t]=n;for(let[e,n]of this.#e)t[e]=n;for(let[e,t]of this.#r)n[e]=t;for(let[e,t]of this.#t)r[e]=t;return{definition:[e,t],external:[n,r]}}getFunctions(){return this.#o}canNavigateTo(e,t,n,r){for(let t of e)if(!this.#f(this.#i,t,n,r,`canNavigateTo`))return!1;for(let e of t)if(!this.#f(this.#a,e,n,r,`canNavigateTo`))return!1;return!0}compileGuardFactory(e,t){let n=typeof e==`boolean`?i(e):e,r=this.#s.compileFactory(n);if(typeof r!=`function`)throw TypeError(`[router.${t}] Factory must return a function, got ${typeof r}`);return r}#c(e,t,n,r,a,o){let s=this.#d(e),c=e===`activate`?this.#a:this.#i,l=r?s.definition:s.external,u=r?s.external:s.definition;if(l.has(t)||u.has(t))this.#s.getValidator()?.lifecycle.warnOverwrite(t,e,a);else{let t=this.#s.getValidator();if(t){let n=this.getHandlerCount(e);t.lifecycle.validateHandlerLimit(n,a),t.lifecycle.validateCountThresholds(n+1,a)}}let d=typeof n==`boolean`?i(n):n,f=l.get(t);l.set(t,d);let p=r&&u.has(t);try{let e=o??this.compileGuardFactory(d,a);p||c.set(t,e)}catch(n){throw f===void 0?l.delete(t):l.set(t,f),this.#u(e,t),n}}#l(e,t,n){let{definition:r,external:i}=this.#d(e),a=n!==`external`&&r.delete(t),o=n!==`definition`&&i.delete(t);(a||o)&&this.#u(e,t)}#u(e,t){let n=this.#d(e),r=e===`activate`?this.#a:this.#i,i=n.external.get(t)??n.definition.get(t);if(!i){r.delete(t);return}try{let e=this.#s.compileFactory(i);if(typeof e!=`function`){r.delete(t);return}r.set(t,e)}catch{r.delete(t)}}#d(e){return e===`activate`?{definition:this.#e,external:this.#t}:{definition:this.#n,external:this.#r}}#f(e,t,n,r,i){let a=e.get(t);if(!a)return!0;try{let e=a(n,r);return typeof e==`boolean`?e:(this.#s.getValidator()?.lifecycle.warnAsyncGuardSync(t,i),!1)}catch(e){return this.#s.logger.warn(`router.${i}`,`Guard for "${t}" threw — treated as navigation-blocking (returned false)`,e),!1}}};exports.RouteLifecycleNamespace=a;
|
|
2
|
+
//# sourceMappingURL=RouteLifecycleNamespace.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RouteLifecycleNamespace.js","names":["#definitionActivateFactories","#externalActivateFactories","#definitionDeactivateFactories","#externalDeactivateFactories","#canDeactivateFunctions","#canActivateFunctions","#functionsTuple","#deps","#getFactoryMaps","#registerHandler","#clearGuard","#recompileSlot","#checkGuardSync"],"sources":["../../../../src/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.ts"],"sourcesContent":["// packages/core/src/namespaces/RouteLifecycleNamespace/RouteLifecycleNamespace.ts\n\nimport type { RouteLifecycleDependencies } from \"./types\";\nimport type {\n DefaultDependencies,\n GuardFn,\n State,\n GuardFnFactory,\n} from \"../../types\";\n\n// Boolean shorthand has only two possible values, so the guard and its factory\n// are module-level singletons — registering `true`/`false` reuses one cached\n// factory instead of allocating a fresh closure per call (#962).\nconst TRUE_GUARD: GuardFn = () => true;\nconst FALSE_GUARD: GuardFn = () => false;\nconst TRUE_FACTORY: GuardFnFactory = () => TRUE_GUARD;\nconst FALSE_FACTORY: GuardFnFactory = () => FALSE_GUARD;\n\n/**\n * Converts a boolean value to a guard function factory.\n * Used for the shorthand syntax where true/false is passed instead of a function.\n * Returns one of two cached factories — no per-call allocation (#962).\n */\nfunction booleanToFactory<Dependencies extends DefaultDependencies>(\n value: boolean,\n): GuardFnFactory<Dependencies> {\n return value ? TRUE_FACTORY : FALSE_FACTORY;\n}\n\n/**\n * Origin lane for a guard clear. Every `clearCanActivate` / `clearCanDeactivate`\n * caller names its lane — there is no origin-blind default — so a new call site\n * cannot silently wipe both the route-config and the external guard (#1171):\n *\n * - `\"definition\"` — clear only the route-config guard (`update(name, {…: null})`, #952).\n * - `\"external\"` — clear only the external, component-managed guard\n * (`removeXGuard()` and post-leave auto-cleanup — the inverse of `addXGuard()`).\n * - `\"both\"` — clear both (route removal / router teardown; the route is gone).\n */\nexport type GuardClearScope = \"definition\" | \"external\" | \"both\";\n\n/**\n * Source of truth for `canActivate` / `canDeactivate` guards.\n *\n * Storage is split by origin into four factory Maps (definition vs external,\n * each ×activate/deactivate); a single compiled-function Map per kind backs\n * navigation (\"external wins\" — when a route holds both a definition and an\n * external guard, the compiled guard is the external one, regardless of\n * registration order; #1174). `getFunctions()` returns a cached\n * `[deactivate, activate]` tuple for the hot path (stable reference, no\n * per-navigate allocation).\n *\n * All input validation is handled upstream by `getLifecycleApi` and\n * `getRoutesApi` — this class has no static methods.\n *\n * **Ordering convention.** Every paired surface lists **deactivate before\n * activate**: `getFunctions()` / `getFactories()` return `[deactivate,\n * activate]`, `getFactoriesByOrigin()` returns that tuple per origin, and\n * `canNavigateTo(toDeactivate, toActivate, …)` takes deactivate first. Keep\n * any new paired surface consistent with this order.\n */\nexport class RouteLifecycleNamespace<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n> {\n // Storage split by origin: definition vs external. Resolution is\n // EXTERNAL-WINS regardless of registration order (#1174): the compiled slot\n // reflects the external factory whenever one exists, else the definition. One\n // policy across every path — `#registerHandler` (keeps external over a later\n // definition), `#recompileSlot`, and `clearDefinitionGuards` (#1192) — so a\n // clone's fixed definition→external replay yields the source's effective guard\n // with no extra tracking. Both semantics are expressed over these primary Maps.\n readonly #definitionActivateFactories = new Map<\n string,\n GuardFnFactory<Dependencies>\n >();\n readonly #externalActivateFactories = new Map<\n string,\n GuardFnFactory<Dependencies>\n >();\n readonly #definitionDeactivateFactories = new Map<\n string,\n GuardFnFactory<Dependencies>\n >();\n readonly #externalDeactivateFactories = new Map<\n string,\n GuardFnFactory<Dependencies>\n >();\n // Compiled-function view. Single Map per kind because navigation does not\n // distinguish origin — it just runs the effective guard. Set on add\n // (external-wins — a definition does not overwrite a live external, #1174)\n // and recompiled on clear from whichever origin Map still holds the slot.\n readonly #canDeactivateFunctions = new Map<string, GuardFn>();\n readonly #canActivateFunctions = new Map<string, GuardFn>();\n // Cached tuple — Maps never change reference, so this is stable\n readonly #functionsTuple: [Map<string, GuardFn>, Map<string, GuardFn>] = [\n this.#canDeactivateFunctions,\n this.#canActivateFunctions,\n ];\n\n #deps!: RouteLifecycleDependencies<Dependencies>;\n\n setDependencies(deps: RouteLifecycleDependencies<Dependencies>): void {\n this.#deps = deps;\n }\n\n getHandlerCount(type: \"activate\" | \"deactivate\"): number {\n const definitionMap =\n type === \"activate\"\n ? this.#definitionActivateFactories\n : this.#definitionDeactivateFactories;\n const externalMap =\n type === \"activate\"\n ? this.#externalActivateFactories\n : this.#externalDeactivateFactories;\n\n if (definitionMap.size === 0) {\n return externalMap.size;\n }\n\n if (externalMap.size === 0) {\n return definitionMap.size;\n }\n\n const names = new Set(definitionMap.keys());\n\n for (const name of externalMap.keys()) {\n names.add(name);\n }\n\n return names.size;\n }\n\n /**\n * Pre-flights the #961 handler-limit `RangeError` into the route-CRUD PREPARE\n * phase (#1046). `#registerHandler`'s per-slot limit check throws AFTER the\n * tree/config swap, so `add`/`replace`/`update` tore post-commit when the\n * validator was installed and the per-type count was at `maxLifecycleHandlers`.\n * Running the same check here — before any store mutation — restores atomicity\n * (#951/#956/#698): a batch that would exceed the limit aborts before a single\n * write.\n *\n * Only NEW slots count (an overwrite leaves the union count unchanged, mirroring\n * `#registerHandler`). For `replace` (`clearsDefinition = true`) the definition\n * guards are about to be cleared, so the projection runs against the surviving\n * EXTERNAL guards only — exactly the post-clear state the install loop sees.\n * Plugin-gated: a no-op without the validator (the limit is opt-in).\n *\n * @param activateNames - route names a `canActivate` would be registered for\n * @param deactivateNames - route names a `canDeactivate` would be registered for\n * @param clearsDefinition - true for `replace` (definition guards cleared first)\n */\n preflightHandlerLimit(\n activateNames: Iterable<string>,\n deactivateNames: Iterable<string>,\n clearsDefinition: boolean,\n ): void {\n const validator = this.#deps.getValidator();\n\n if (!validator) {\n return;\n }\n\n const check = (\n type: \"activate\" | \"deactivate\",\n names: Iterable<string>,\n methodName: string,\n ): void => {\n const { definition, external } = this.#getFactoryMaps(type);\n\n // A name already holding a guard of this type is an overwrite (no new\n // slot, mirroring `#registerHandler`). After a definition-clear (replace)\n // only EXTERNAL guards survive, so the existing-name check — and the base\n // count below — run against `external` alone, matching the post-clear\n // install state the loop sees.\n let newSlots = 0;\n\n for (const name of names) {\n const isExisting = clearsDefinition\n ? external.has(name)\n : definition.has(name) || external.has(name);\n\n if (!isExisting) {\n newSlots++;\n }\n }\n\n if (newSlots === 0) {\n return;\n }\n\n // The install loop throws when a new-slot registration observes\n // `count >= max`. Starting from `base` and adding `newSlots` new names,\n // the highest pre-register count it reaches is `base + newSlots - 1` —\n // replicate that worst case so the pre-flight throws iff the loop would.\n const base = clearsDefinition\n ? external.size\n : this.getHandlerCount(type);\n\n validator.lifecycle.validateHandlerLimit(base + newSlots - 1, methodName);\n };\n\n check(\"activate\", activateNames, \"canActivate\");\n check(\"deactivate\", deactivateNames, \"canDeactivate\");\n }\n\n // =========================================================================\n // Instance methods\n // =========================================================================\n\n /**\n * Adds a canActivate guard for a route.\n *\n * @param name - Route name (input-validated by facade)\n * @param handler - Guard function or boolean (input-validated by facade)\n * @param isFromDefinition - True when guard comes from route definition\n * (lands in the definition Map; subject to `clearDefinitionGuards()`).\n * False (default) when added via `getLifecycleApi().addActivateGuard(...)`\n * (lands in the external Map; survives `replace()`).\n *\n * External wins at runtime (#1174): when a route holds both a definition and\n * an external guard, the compiled function is the external one, regardless of\n * registration order. Within one origin the most recent add overwrites. Origin\n * determines which Map the factory is filed under (relevant for\n * `clearDefinitionGuards()` and `cloneRouter` re-registration).\n */\n addCanActivate(\n name: string,\n handler: GuardFnFactory<Dependencies> | boolean,\n isFromDefinition = false,\n precompiledFn?: GuardFn,\n ): void {\n this.#registerHandler(\n \"activate\",\n name,\n handler,\n isFromDefinition,\n \"canActivate\",\n precompiledFn,\n );\n }\n\n /**\n * Adds a canDeactivate guard for a route.\n *\n * Symmetric counterpart to {@link addCanActivate}.\n */\n addCanDeactivate(\n name: string,\n handler: GuardFnFactory<Dependencies> | boolean,\n isFromDefinition = false,\n precompiledFn?: GuardFn,\n ): void {\n this.#registerHandler(\n \"deactivate\",\n name,\n handler,\n isFromDefinition,\n \"canDeactivate\",\n precompiledFn,\n );\n }\n\n /**\n * Removes a canActivate guard for a route. `scope` names the origin lane\n * (see {@link GuardClearScope}) — there is no origin-blind default, so every\n * caller commits to a lane and a new call site cannot silently clear both.\n * Delegates to {@link #clearGuard} (mirrors the add side's `#registerHandler`).\n *\n * @param name - Route name (already validated by facade)\n * @param scope - Which origin(s) to clear: `\"definition\"` / `\"external\"` / `\"both\"`\n */\n clearCanActivate(name: string, scope: GuardClearScope): void {\n this.#clearGuard(\"activate\", name, scope);\n }\n\n /**\n * Removes a canDeactivate guard for a route. Symmetric counterpart to\n * {@link clearCanActivate}.\n *\n * The `\"external\"` lane is what makes a route-config `canDeactivate` durable:\n * post-leave auto-cleanup (`completeTransition`) and `removeDeactivateGuard()`\n * unregister only the external, component-managed guard (router5 mount/unmount\n * heritage), while a definition guard survives for re-entry — symmetric with\n * definition `canActivate`, which lives as long as the route is in the tree\n * (#1171). Clearing both by default made a config guard one-shot: the first\n * permitted leave erased it, so re-entry was unguarded, `getRoutesApi().get()`\n * lost the field, and a clone taken after the leave never received it\n * (clone invariant #6).\n *\n * @param name - Route name (already validated by facade)\n * @param scope - Which origin(s) to clear: `\"definition\"` / `\"external\"` / `\"both\"`\n */\n clearCanDeactivate(name: string, scope: GuardClearScope): void {\n this.#clearGuard(\"deactivate\", name, scope);\n }\n\n /**\n * Clears all lifecycle handlers (canActivate and canDeactivate).\n * Used by clearRoutes to reset all lifecycle state.\n */\n clearAll(): void {\n this.#definitionActivateFactories.clear();\n this.#externalActivateFactories.clear();\n this.#definitionDeactivateFactories.clear();\n this.#externalDeactivateFactories.clear();\n this.#canActivateFunctions.clear();\n this.#canDeactivateFunctions.clear();\n }\n\n /**\n * Clears only lifecycle handlers that were registered from route definitions.\n * Used by HMR `replace()` to remove definition-sourced guards without\n * touching externally-added guards.\n *\n * For a slot where BOTH a definition and an external guard exist, the external\n * factory survives — and the compiled function is RECOMPILED from it (#1192).\n * Under external-wins (#1174) the compiled slot is already the external guard,\n * so this recompile is idempotent — it re-derives the surviving external factory\n * through the same choke point that keeps clearing correct (and stays robust if\n * the compiled slot were ever out of sync). For a definition-only slot, the\n * compiled function is dropped.\n */\n clearDefinitionGuards(): void {\n for (const name of this.#definitionActivateFactories.keys()) {\n if (this.#externalActivateFactories.has(name)) {\n this.#recompileSlot(\"activate\", name);\n } else {\n this.#canActivateFunctions.delete(name);\n }\n }\n\n for (const name of this.#definitionDeactivateFactories.keys()) {\n if (this.#externalDeactivateFactories.has(name)) {\n this.#recompileSlot(\"deactivate\", name);\n } else {\n this.#canDeactivateFunctions.delete(name);\n }\n }\n\n this.#definitionActivateFactories.clear();\n this.#definitionDeactivateFactories.clear();\n }\n\n /**\n * Returns lifecycle factories as a flat `[deactivate, activate]` tuple of\n * `Record<name, factory>` — the effective view where external wins over\n * definition for the same slot. Used by `getRoutesApi` to enrich route\n * objects with their current canActivate / canDeactivate factories and by\n * the route-removal cleanup path.\n *\n * For cloneRouter (which needs to preserve origin on re-registration), use\n * {@link getFactoriesByOrigin} instead.\n */\n getFactories(): [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ] {\n const deactivateRecord: Record<string, GuardFnFactory<Dependencies>> = {};\n const activateRecord: Record<string, GuardFnFactory<Dependencies>> = {};\n\n for (const [name, factory] of this.#definitionDeactivateFactories) {\n deactivateRecord[name] = factory;\n }\n for (const [name, factory] of this.#externalDeactivateFactories) {\n deactivateRecord[name] = factory;\n }\n\n for (const [name, factory] of this.#definitionActivateFactories) {\n activateRecord[name] = factory;\n }\n for (const [name, factory] of this.#externalActivateFactories) {\n activateRecord[name] = factory;\n }\n\n return [deactivateRecord, activateRecord];\n }\n\n /**\n * Returns factories tagged by origin — definition and external as separate\n * `[deactivate, activate]` tuples. Used by `cloneRouter` to re-register\n * guards on the clone with their original origin flag preserved.\n */\n getFactoriesByOrigin(): {\n definition: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ];\n external: [\n Record<string, GuardFnFactory<Dependencies>>,\n Record<string, GuardFnFactory<Dependencies>>,\n ];\n } {\n const defDeact: Record<string, GuardFnFactory<Dependencies>> = {};\n const defAct: Record<string, GuardFnFactory<Dependencies>> = {};\n const extensionDeact: Record<string, GuardFnFactory<Dependencies>> = {};\n const extensionAct: Record<string, GuardFnFactory<Dependencies>> = {};\n\n for (const [name, factory] of this.#definitionDeactivateFactories) {\n defDeact[name] = factory;\n }\n for (const [name, factory] of this.#definitionActivateFactories) {\n defAct[name] = factory;\n }\n for (const [name, factory] of this.#externalDeactivateFactories) {\n extensionDeact[name] = factory;\n }\n for (const [name, factory] of this.#externalActivateFactories) {\n extensionAct[name] = factory;\n }\n\n return {\n definition: [defDeact, defAct],\n external: [extensionDeact, extensionAct],\n };\n }\n\n /**\n * Returns compiled lifecycle functions for transition execution.\n *\n * @returns Tuple of [canDeactivateFunctions, canActivateFunctions] as Maps\n */\n getFunctions(): [Map<string, GuardFn>, Map<string, GuardFn>] {\n return this.#functionsTuple;\n }\n\n canNavigateTo(\n toDeactivate: string[],\n toActivate: string[],\n toState: State,\n fromState: State | undefined,\n ): boolean {\n for (const segment of toDeactivate) {\n if (\n !this.#checkGuardSync(\n this.#canDeactivateFunctions,\n segment,\n toState,\n fromState,\n \"canNavigateTo\",\n )\n ) {\n return false;\n }\n }\n\n for (const segment of toActivate) {\n if (\n !this.#checkGuardSync(\n this.#canActivateFunctions,\n segment,\n toState,\n fromState,\n \"canNavigateTo\",\n )\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Compiles a guard factory to its `GuardFn` WITHOUT registering it — surfaces\n * a throwing / non-function factory eagerly. The prepare-then-commit\n * add/replace path (`adoptRouteArtifacts`) calls this for every pending guard\n * BEFORE the store swap (#956), so a malformed factory aborts the mutation\n * with the store untouched. The returned function is then installed via the\n * `precompiledFn` argument of {@link addCanActivate} / {@link addCanDeactivate}\n * — no re-compile, so a factory with compile-time side effects runs exactly\n * once. Same boolean-shorthand handling + compile + non-function check as the\n * inline `#registerHandler` path, so a route-config `canActivate: true`\n * (boolean shorthand, runtime-reachable via the public route type) compiles to\n * the cached `TRUE_GUARD`/`FALSE_GUARD` instead of throwing on a non-callable.\n */\n compileGuardFactory(\n handler: GuardFnFactory<Dependencies> | boolean,\n methodName: string,\n ): GuardFn {\n const factory =\n typeof handler === \"boolean\"\n ? booleanToFactory<Dependencies>(handler)\n : handler;\n const fn = this.#deps.compileFactory(factory);\n\n if (typeof fn !== \"function\") {\n throw new TypeError(\n `[router.${methodName}] Factory must return a function, got ${typeof fn}`,\n );\n }\n\n return fn;\n }\n\n // =========================================================================\n // Private methods (business logic)\n // =========================================================================\n\n /**\n * Routes a registration into the origin-specific factory Map and updates the\n * compiled function under EXTERNAL-WINS (#1174): the just-added factory becomes\n * the compiled guard unless it is a definition registered while an external\n * guard is already live (then external stays effective; the definition is still\n * stored for a later `clearDefinitionGuards()`). Within one origin the most\n * recent add overwrites.\n * Emits overwrite / threshold warnings symmetric with the pre-refactor\n * single-Map behaviour: any prior entry for the slot — same origin or\n * cross-origin — counts as an overwrite for the warning surface; only a\n * brand-new slot (no entry in either Map) increments the threshold check.\n */\n #registerHandler(\n type: \"activate\" | \"deactivate\",\n name: string,\n handler: GuardFnFactory<Dependencies> | boolean,\n isFromDefinition: boolean,\n methodName: string,\n precompiledFn?: GuardFn,\n ): void {\n const factoryMaps = this.#getFactoryMaps(type);\n const functions =\n type === \"activate\"\n ? this.#canActivateFunctions\n : this.#canDeactivateFunctions;\n const targetMap = isFromDefinition\n ? factoryMaps.definition\n : factoryMaps.external;\n const otherMap = isFromDefinition\n ? factoryMaps.external\n : factoryMaps.definition;\n\n const isOverwrite = targetMap.has(name) || otherMap.has(name);\n\n if (isOverwrite) {\n this.#deps\n .getValidator()\n ?.lifecycle.warnOverwrite(name, type, methodName);\n } else {\n // Single enforcement choke point for EVERY registration path: programmatic\n // (getLifecycleApi) and route-config (getRoutesApi.add/update, where\n // isFromDefinition=true). The hard limit throws here so route-config guards\n // are bounded exactly like programmatic ones (#961); the approaching-limit\n // warning follows. Only new slots count toward the limit — an overwrite\n // leaves the count unchanged. `getHandlerCount` is read once and only when\n // the validator is installed (opt-in), so the no-plugin path stays free.\n const validator = this.#deps.getValidator();\n\n if (validator) {\n const count = this.getHandlerCount(type);\n\n validator.lifecycle.validateHandlerLimit(count, methodName);\n validator.lifecycle.validateCountThresholds(count + 1, methodName);\n }\n }\n\n const factory =\n typeof handler === \"boolean\"\n ? booleanToFactory<Dependencies>(handler)\n : handler;\n\n // Capture the slot's prior factory (if any) BEFORE the overwrite, so a\n // compile-throw can be rolled back to the previously-valid guard rather\n // than dropping it (#963).\n const previousFactory = targetMap.get(name);\n\n targetMap.set(name, factory);\n\n // External-wins (#1174): the compiled slot reflects the external guard\n // whenever one exists, regardless of registration order. A definition\n // registered while an external guard is live is still stored (so a later\n // replace()-clear can recompile from it via `#recompileSlot`) but does NOT\n // overwrite the compiled function — external stays effective. This makes\n // `#registerHandler` consistent with `#recompileSlot` / `clearDefinitionGuards`\n // (both external-wins, #1192), so the whole namespace has ONE policy, and\n // cloneRouter's fixed definition→external replay yields the same effective\n // guard as the source with no extra origin tracking. (The factory is still\n // compiled below to validate it and to keep the rollback path symmetric.)\n const externalWins = isFromDefinition && otherMap.has(name);\n\n try {\n // A pre-validated function (from the #956 add/replace pre-compile) is\n // installed directly — no re-compile; otherwise compile + non-function\n // check here (`compileGuardFactory` throws on a bad factory).\n const fn = precompiledFn ?? this.compileGuardFactory(factory, methodName);\n\n if (!externalWins) {\n functions.set(name, fn);\n }\n } catch (error) {\n // Roll the slot back to its pre-call state: restore the previous factory\n // on an overwrite (#963), else clear the slot. `#recompileSlot` then\n // resets the compiled function from whichever origin Map still holds an\n // entry — the restored same-origin factory, a surviving cross-origin one,\n // or (empty slot) deletes the compiled function.\n if (previousFactory === undefined) {\n targetMap.delete(name);\n } else {\n targetMap.set(name, previousFactory);\n }\n\n this.#recompileSlot(type, name);\n\n throw error;\n }\n }\n\n /**\n * Shared implementation for {@link clearCanActivate} / {@link clearCanDeactivate}\n * — the clear-side counterpart to {@link #registerHandler}. `scope` selects the\n * origin lane (no origin-blind default, #1171); when one origin is cleared and\n * the other survives, `#recompileSlot` recompiles the compiled function from\n * the survivor (external wins, #1174).\n */\n #clearGuard(\n type: \"activate\" | \"deactivate\",\n name: string,\n scope: GuardClearScope,\n ): void {\n const { definition, external } = this.#getFactoryMaps(type);\n const clearedDefinition =\n scope === \"external\" ? false : definition.delete(name);\n const clearedExternal =\n scope === \"definition\" ? false : external.delete(name);\n\n if (clearedDefinition || clearedExternal) {\n this.#recompileSlot(type, name);\n }\n }\n\n /**\n * Recompiles the compiled-function slot from whichever origin Map still has\n * an entry for `name` after a clear. External wins over definition; if\n * neither has an entry, the compiled function is deleted.\n */\n #recompileSlot(type: \"activate\" | \"deactivate\", name: string): void {\n const factoryMaps = this.#getFactoryMaps(type);\n const functions =\n type === \"activate\"\n ? this.#canActivateFunctions\n : this.#canDeactivateFunctions;\n\n const effective =\n factoryMaps.external.get(name) ?? factoryMaps.definition.get(name);\n\n if (!effective) {\n functions.delete(name);\n\n return;\n }\n\n try {\n const fn = this.#deps.compileFactory(effective);\n\n /* v8 ignore next 4 -- @preserve: stored factories were validated at add time, compileFactory should yield a function on second call too */\n if (typeof fn !== \"function\") {\n functions.delete(name);\n\n return;\n }\n\n functions.set(name, fn);\n } catch {\n /* v8 ignore next 2 -- @preserve: defensive — a user-provided factory could theoretically throw on re-compile (state changed since add time); deleting the function blocks navigation on that slot */\n functions.delete(name);\n }\n }\n\n #getFactoryMaps(type: \"activate\" | \"deactivate\"): {\n definition: Map<string, GuardFnFactory<Dependencies>>;\n external: Map<string, GuardFnFactory<Dependencies>>;\n } {\n return type === \"activate\"\n ? {\n definition: this.#definitionActivateFactories,\n external: this.#externalActivateFactories,\n }\n : {\n definition: this.#definitionDeactivateFactories,\n external: this.#externalDeactivateFactories,\n };\n }\n\n /**\n * Shared implementation for synchronous guard checks.\n * Warns if a guard returns a Promise (async guards are not supported in sync mode).\n * Catches exceptions and treats them as navigation-blocking (`false`).\n *\n * @param functions - Map of compiled guard functions to look up\n * @param name - Route name to check the guard for\n * @param toState - Target navigation state\n * @param fromState - Current state (`undefined` on initial navigation)\n * @param methodName - Public API method name for warning messages\n */\n #checkGuardSync(\n functions: Map<string, GuardFn>,\n name: string,\n toState: State,\n fromState: State | undefined,\n methodName: string,\n ): boolean {\n const guardFn = functions.get(name);\n\n if (!guardFn) {\n return true;\n }\n\n try {\n const result = guardFn(toState, fromState);\n\n if (typeof result === \"boolean\") {\n return result;\n }\n\n this.#deps.getValidator()?.lifecycle.warnAsyncGuardSync(name, methodName);\n\n return false;\n } catch (error) {\n // #959: a throwing sync guard must not vanish silently. `navigate()`\n // surfaces the same throw via `handleGuardError` → TRANSITION_ERROR; the\n // sync predicate (`canNavigateTo`) has no error channel, so core logs it\n // directly. This is an OPERATIONAL signal (the guard crashed — distinct\n // from the opt-in validator DX warnings above for which the validator is\n // the right home): the navigation is still treated as blocked (`false`).\n this.#deps.logger.warn(\n `router.${methodName}`,\n `Guard for \"${name}\" threw — treated as navigation-blocking (returned false)`,\n error,\n );\n\n return false;\n }\n }\n}\n"],"mappings":"AAaA,MAAM,MAA4B,GAC5B,MAA6B,GAC7B,MAA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U,KAAKC,EACjB,EACA,CACE,WAAY,KAAKC,GACjB,SAAU,KAAKC,EACjB,CACN,CAaA,GACE,EACA,EACA,EACA,EACA,EACS,CACT,IAAM,EAAU,EAAU,IAAI,CAAI,EAElC,GAAI,CAAC,EACH,MAAO,GAGT,GAAI,CACF,IAAM,EAAS,EAAQ,EAAS,CAAS,EAQzC,OANI,OAAO,GAAW,UACb,GAGT,KAAKI,GAAM,aAAa,CAAC,EAAE,UAAU,mBAAmB,EAAM,CAAU,EAEjE,GACT,OAAS,EAAO,CAad,OANA,KAAKA,GAAM,OAAO,KAChB,UAAU,IACV,cAAc,EAAK,2DACnB,CACF,EAEO,EACT,CACF,CACF"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { DefaultDependencies, GuardFn, GuardFnFactory, RouterLogger } from "../../types/router.js";
|
|
2
|
+
import { RouterValidator } from "../../types/RouterValidator.js";
|
|
3
|
+
//#region src/namespaces/RouteLifecycleNamespace/types.d.ts
|
|
4
|
+
interface RouteLifecycleDependencies<Dependencies extends DefaultDependencies = DefaultDependencies> {
|
|
5
|
+
/** Per-router logger instance (from `getInternals(router).logger`) */
|
|
6
|
+
logger: RouterLogger;
|
|
7
|
+
compileFactory: (factory: GuardFnFactory<Dependencies>) => GuardFn;
|
|
8
|
+
/**
|
|
9
|
+
* Returns the opt-in DX validator, or `null` when no validation-plugin is
|
|
10
|
+
* installed. A plain deps field (#1331) — internals are registered before
|
|
11
|
+
* wiring, so `getInternals(router)` never throws and no try/catch is needed.
|
|
12
|
+
*/
|
|
13
|
+
getValidator: () => RouterValidator | null;
|
|
14
|
+
}
|
|
15
|
+
//#endregion
|
|
16
|
+
export { RouteLifecycleDependencies };
|
|
17
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/namespaces/RouteLifecycleNamespace/types.ts"],"mappings":";;;UAUiB,2BACf,qBAAqB,sBAAsB;;EAG3C,QAAQ;EAER,iBAAiB,SAAS,eAAe,kBAAkB;;;;;;EAM3D,oBAAoB"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("../../constants.js"),t=require("../../RouterError.js"),n=Object.freeze({replace:!0});var r=class{#e;setDependencies(e){this.#e=e}async start(r){let i=this.#e;if(i.isIdle())throw new t.RouterError(e.errorCodes.TRANSITION_CANCELLED);let a=i.getOptions();if(typeof r!=`string`)throw TypeError(`[router.start] path must be a string, got ${typeof r}`);let o=i.matchPath(r);if(!o&&!a.allowNotFound){let n=new t.RouterError(e.errorCodes.ROUTE_NOT_FOUND,{path:r});throw i.emitTransitionError(void 0,void 0,n),n}return i.completeStart(),o?i.navigateToState(o,n):i.navigateToNotFound(r)}stop(){this.#e.clearState()}};exports.RouterLifecycleNamespace=r;
|
|
2
|
+
//# sourceMappingURL=RouterLifecycleNamespace.js.map
|