@real-router/core 0.2.0 → 0.2.2

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/RouterError.ts","../../src/core/dependencies.ts","../../src/core/middleware.ts","../../src/transition/makeError.ts","../../src/transition/mergeStates.ts","../../src/transition/processLifecycleResult.ts","../../src/transition/wrapSyncError.ts","../../src/transition/executeLifecycleHooks.ts","../../src/transition/executeMiddleware.ts","../../src/transitionPath.ts","../../src/transition/index.ts","../../src/core/navigation.ts","../../src/core/observable.ts","../../src/core/options.ts","../../src/core/plugins.ts","../../src/core/routeLifecycle.ts","../../src/internals.ts","../../src/core/stateBuilder.ts","../../src/core/routes/routePath.ts","../../src/core/routerLifecycle.ts","../../src/core/routes/routeConfig.ts","../../src/core/routes/routeQuery.ts","../../src/core/routes/routeTree.ts","../../src/core/routes/index.ts","../../src/core/state.ts","../../src/typeGuards.ts","../../src/createRouter.ts"],"names":["logger","isState","safeCallback","getTypeDescription","isNavigationOptions","isObjKey","plugins","DEFAULT_ROUTE_NAME","isString","routeNodeBuildPath","noop","validateRouteName","getSegmentsByName","createRouteTree","validateState","isParams"],"mappings":";AAgBO,IAAM,gBAAA,0BAA0B,uBAAuB,CAAA;AAQvD,IAAM,wBAAA,0BAAkC,8BAA8B,CAAA;AAwBtE,IAAM,2BAAA,mBAA8B,MAAA;AAAA,EACzC;AACF,CAAA;AAOO,IAAM,gBAAA,0BAA0B,sBAAsB,CAAA;AAQtD,IAAM,aAAA,0BAAuB,oBAAoB,CAAA;AAiBjD,IAAM,UAAA,GAAkC,OAAO,MAAA,CAAO;AAAA,EAC3D,kBAAA,EAAoB,aAAA;AAAA;AAAA,EACpB,sBAAA,EAAwB,wBAAA;AAAA;AAAA,EACxB,sBAAA,EAAwB,iBAAA;AAAA;AAAA,EACxB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,WAA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nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n} from \"core-types\";\n\n/**\n * Internal Symbol for storing the route tree.\n * Using Symbol to simulate a \"private\" property that won't appear in Object.keys().\n *\n * @internal\n */\nexport const ROOT_TREE_SYMBOL = Symbol(\"real-router.routeTree\");\n\n/**\n * Internal Symbol for storing route definitions.\n * Used for dynamic route addition support.\n *\n * @internal\n */\nexport const ROUTE_DEFINITIONS_SYMBOL = Symbol(\"real-router.routeDefinitions\");\n\n/**\n * Internal Symbol for storing resolved forwardTo chains cache.\n * Maps route names to their final destination after following the entire chain.\n *\n * @internal\n * @todo RFC-8: This is a stopgap solution until CacheManager is implemented.\n * Once CacheManager is available, migrate to:\n * CacheManager.getInstance().setResolvedForwardMap(router, resolvedMap)\n *\n * **Current approach (temporary)**:\n * ```typescript\n * router[RESOLVED_FORWARD_MAP_SYMBOL] = { \"A\": \"C\", \"B\": \"C\" };\n * ```\n *\n * **Future approach (RFC-8)**:\n * ```typescript\n * CacheManager.getInstance().setResolvedForwardMap(router, resolvedMap);\n * ```\n *\n * See: .claude/issues/1-dx-improve-rfc-list/rfc-7-route-guard-check.md\n * See: .claude/issues/2-fsm-migration-rfc-list/rfc-8-cache-manager.md\n */\nexport const RESOLVED_FORWARD_MAP_SYMBOL = Symbol(\n \"real-router.resolvedForwardMap\",\n);\n\n/**\n * Internal Symbol for storing root path.\n *\n * @internal\n */\nexport const ROOT_PATH_SYMBOL = Symbol(\"real-router.rootPath\");\n\n/**\n * Internal Symbol for storing router configuration.\n * Hides config from public API to prevent bypassing validation in updateRoute().\n *\n * @internal\n */\nexport const CONFIG_SYMBOL = Symbol(\"real-router.config\");\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Record<ConstantsKeys, string>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const constants: Constants = {\n UNKNOWN_ROUTE: \"@@real-router/UNKNOWN_ROUTE\", // Special route for 404/not found states\n};\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = {\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n};\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = {\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n};\n","// packages/real-router/modules/helpers.ts\n\nimport type { State, Options } from \"core-types\";\nimport type { BuildOptions, TrailingSlashMode } from \"route-tree\";\n\nexport { getTypeDescription } from \"type-guards\";\n\n// =============================================================================\n// State Helpers (migrated from router-error)\n// =============================================================================\n\n/**\n * Simple type guard for State object structure.\n * Checks for required fields: name, params, path.\n *\n * @param value - Value to check\n * @returns true if value has State structure\n * @internal\n */\nfunction isState(value: unknown): value is State {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n return (\n typeof obj.name === \"string\" &&\n typeof obj.path === \"string\" &&\n typeof obj.params === \"object\" &&\n obj.params !== null\n );\n}\n\n/**\n * Deep freezes State object to prevent mutations.\n * Creates a deep clone first, then recursively freezes the clone and all nested objects.\n * Uses simple recursive freezing after cloning (no need for WeakSet since clone has no circular refs).\n *\n * @param state - The State object to freeze\n * @returns A frozen deep clone of the state\n * @throws {TypeError} If state is not a valid State object\n *\n * @example\n * const state = { name: 'home', params: {}, path: '/' };\n * const frozen = deepFreezeState(state);\n * // frozen.params is now immutable\n * // original state is unchanged\n */\nexport function deepFreezeState<T extends State>(state: T): T {\n // Early return for null/undefined\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Validate State structure\n if (!isState(state)) {\n throw new TypeError(\n `[deepFreezeState] Expected valid State object, got: ${typeof state}`,\n );\n }\n\n // Create a deep clone to avoid mutating the original\n // structuredClone preserves circular references, so we need to track visited objects\n const clonedState = structuredClone(state);\n\n // WeakSet to track visited objects (prevent infinite recursion with circular refs)\n const visited = new WeakSet<object>();\n\n // Recursive freeze function with circular reference protection\n function freezeClonedRecursive(obj: unknown): void {\n // Skip primitives, null, undefined\n // Note: typeof undefined === \"undefined\" !== \"object\", so checking undefined is redundant\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already visited objects (circular reference protection)\n if (visited.has(obj)) {\n return;\n }\n\n // Mark as visited\n visited.add(obj);\n\n // Freeze the object/array itself\n Object.freeze(obj);\n\n // Get all values to freeze recursively\n const values = Array.isArray(obj) ? obj : Object.values(obj);\n\n // Recursively freeze nested values\n for (const value of values) {\n freezeClonedRecursive(value);\n }\n }\n\n // Freeze the entire cloned state tree\n freezeClonedRecursive(clonedState);\n\n return clonedState;\n}\n\n// WeakSet to track already frozen root objects for O(1) re-freeze check\nconst frozenRoots = new WeakSet<object>();\n\n// Module-scope recursive freeze function - better JIT optimization, no allocation per call\nfunction freezeRecursive(obj: unknown): void {\n // Skip primitives, null\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already frozen objects (handles potential shared refs)\n if (Object.isFrozen(obj)) {\n return;\n }\n\n // Freeze the object/array\n Object.freeze(obj);\n\n // Iterate without Object.values() allocation\n if (Array.isArray(obj)) {\n for (const item of obj) {\n freezeRecursive(item);\n }\n } else {\n for (const key in obj) {\n freezeRecursive((obj as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Freezes State object in-place without cloning.\n * Optimized for hot paths where state is known to be a fresh object.\n *\n * IMPORTANT: Only use this when you know the state is a fresh object\n * that hasn't been exposed to external code yet (e.g., from makeState()).\n *\n * @param state - The State object to freeze (must be a fresh object)\n * @returns The same state object, now frozen\n * @internal\n */\nexport function freezeStateInPlace<T extends State>(state: T): T {\n // Early return for null/undefined - state from makeState() is never null\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Fast path: already processed root object - O(1) check\n if (frozenRoots.has(state)) {\n return state;\n }\n\n // Freeze the entire state tree\n freezeRecursive(state);\n\n // Mark root as processed for future calls\n frozenRoots.add(state);\n\n return state;\n}\n\n// =============================================================================\n// Route Options Helpers\n// =============================================================================\n\n/**\n * Maps real-router trailingSlash option to route-tree's trailingSlashMode.\n *\n * @param trailingSlash - real-router trailing slash option\n * @returns route-tree trailing slash mode\n * @internal\n */\nfunction mapTrailingSlashMode(\n trailingSlash: Options[\"trailingSlash\"],\n): TrailingSlashMode {\n switch (trailingSlash) {\n case \"never\": {\n return \"never\";\n }\n case \"always\": {\n return \"always\";\n }\n default: {\n return \"default\";\n }\n }\n}\n\n/**\n * Creates route-tree BuildOptions from real-router Options.\n * Used for buildPath caching in routerLifecycle.ts.\n *\n * @param options - real-router options\n * @returns route-tree build options\n */\nexport function createBuildOptions(options: Options): BuildOptions {\n const buildOptions: BuildOptions = {\n trailingSlashMode: mapTrailingSlashMode(options.trailingSlash),\n queryParamsMode: options.queryParamsMode,\n urlParamsEncoding: options.urlParamsEncoding,\n };\n\n // Only include queryParams if defined (exactOptionalPropertyTypes)\n if (options.queryParams !== undefined) {\n buildOptions.queryParams = options.queryParams;\n }\n\n return buildOptions;\n}\n","// packages/real-router/modules/RouterError.ts\n\nimport { errorCodes } from \"./constants\";\nimport { deepFreezeState } from \"./helpers\";\n\nimport type { State } from \"core-types\";\n\n// Pre-compute Set of error code values for O(1) lookup in setCode()\n// This avoids creating array and doing linear search on every setCode() call\nconst errorCodeValues = new Set(Object.values(errorCodes));\n\n// Reserved built-in properties - throw error if user tries to set these\nconst reservedProperties = new Set([\"code\", \"segment\", \"path\", \"redirect\"]);\n\n// Reserved method names - silently ignore attempts to overwrite these\nconst reservedMethods = new Set([\n \"setCode\",\n \"setErrorInstance\",\n \"setAdditionalFields\",\n \"hasField\",\n \"getField\",\n \"toJSON\",\n]);\n\nexport class RouterError extends Error {\n [key: string]: unknown;\n\n // Using public properties to ensure structural compatibility\n // with RouterError interface in core-types\n readonly segment: string | undefined;\n readonly path: string | undefined;\n readonly redirect: State | undefined;\n\n // Note: code appears to be writable but setCode() should be used\n // to properly update both code and message together\n code: string;\n\n /**\n * Creates a new RouterError instance.\n *\n * The options object accepts built-in fields (message, segment, path, redirect)\n * and any additional custom fields, which will all be attached to the error instance.\n *\n * @param code - The error code (e.g., \"ROUTE_NOT_FOUND\", \"CANNOT_ACTIVATE\")\n * @param options - Optional configuration object\n * @param options.message - Custom error message (defaults to code if not provided)\n * @param options.segment - The route segment where the error occurred\n * @param options.path - The full path where the error occurred\n * @param options.redirect - Optional redirect state for navigation errors\n *\n * @example\n * ```typescript\n * // Basic error\n * const err1 = new RouterError(\"ROUTE_NOT_FOUND\");\n *\n * // Error with custom message\n * const err2 = new RouterError(\"ERR\", { message: \"Something went wrong\" });\n *\n * // Error with context and custom fields\n * const err3 = new RouterError(\"CANNOT_ACTIVATE\", {\n * message: \"Insufficient permissions\",\n * segment: \"admin\",\n * path: \"/admin/users\",\n * userId: \"123\" // custom field\n * });\n *\n * // Error with redirect\n * const err4 = new RouterError(\"TRANSITION_ERR\", {\n * redirect: { name: \"home\", path: \"/\", params: {} }\n * });\n * ```\n */\n constructor(\n code: string,\n {\n message,\n segment,\n path,\n redirect,\n ...rest\n }: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n path?: string | undefined;\n redirect?: State | undefined;\n } = {},\n ) {\n super(message ?? code);\n\n this.code = code;\n this.segment = segment;\n this.path = path;\n // Deep freeze redirect to prevent mutations (creates a frozen clone)\n this.redirect = redirect ? deepFreezeState(redirect) : undefined;\n\n // Assign custom fields, checking reserved properties and filtering out reserved method names\n // Issue #39: Throw for reserved properties to match setAdditionalFields behavior\n for (const [key, value] of Object.entries(rest)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Updates the error code and conditionally updates the message.\n *\n * If the current message is one of the standard error code values\n * (e.g., \"ROUTE_NOT_FOUND\", \"SAME_STATES\"), it will be replaced with the new code.\n * This allows keeping error messages in sync with codes when using standard error codes.\n *\n * If the message is custom (not a standard error code), it will be preserved.\n *\n * @param newCode - The new error code to set\n *\n * @example\n * // Message follows code (standard error code as message)\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", { message: \"ROUTE_NOT_FOUND\" });\n * err.setCode(\"CUSTOM_ERROR\"); // message becomes \"CUSTOM_ERROR\"\n *\n * @example\n * // Custom message is preserved\n * const err = new RouterError(\"ERR\", { message: \"Custom error message\" });\n * err.setCode(\"NEW_CODE\"); // message stays \"Custom error message\"\n */\n setCode(newCode: string): void {\n this.code = newCode;\n\n // Only update message if it's a standard error code value (not a custom message)\n if (errorCodeValues.has(this.message)) {\n this.message = newCode;\n }\n }\n\n /**\n * Copies properties from another Error instance to this RouterError.\n *\n * This method updates the message, cause, and stack trace from the provided error.\n * Useful for wrapping native errors while preserving error context.\n *\n * @param err - The Error instance to copy properties from\n * @throws {TypeError} If err is null or undefined\n *\n * @example\n * ```typescript\n * const routerErr = new RouterError(\"TRANSITION_ERR\");\n * try {\n * // some operation that might fail\n * } catch (nativeErr) {\n * routerErr.setErrorInstance(nativeErr);\n * throw routerErr;\n * }\n * ```\n */\n setErrorInstance(err: Error): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!err) {\n throw new TypeError(\n \"[RouterError.setErrorInstance] err parameter is required and must be an Error instance\",\n );\n }\n\n this.message = err.message;\n this.cause = err.cause;\n this.stack = err.stack ?? \"\";\n }\n\n /**\n * Adds custom fields to the error object.\n *\n * This method allows attaching arbitrary data to the error for debugging or logging purposes.\n * All fields become accessible as properties on the error instance and are included in JSON serialization.\n *\n * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)\n * are automatically filtered out to prevent accidental overwriting of class methods.\n *\n * @param fields - Object containing custom fields to add to the error\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"CANNOT_ACTIVATE\");\n * err.setAdditionalFields({\n * userId: \"123\",\n * attemptedRoute: \"/admin\",\n * reason: \"insufficient permissions\"\n * });\n *\n * console.log(err.userId); // \"123\"\n * console.log(JSON.stringify(err)); // includes all custom fields\n * ```\n */\n setAdditionalFields(fields: Record<string, unknown>): void {\n // Assign fields, throwing for reserved properties, silently ignoring methods\n for (const [key, value] of Object.entries(fields)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError.setAdditionalFields] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Checks if a custom field exists on the error object.\n *\n * This method checks for both custom fields added via setAdditionalFields()\n * and built-in fields (code, message, segment, etc.).\n *\n * @param key - The field name to check\n * @returns `true` if the field exists, `false` otherwise\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\", { segment: \"users\" });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * err.hasField(\"userId\"); // true\n * err.hasField(\"segment\"); // true\n * err.hasField(\"unknown\"); // false\n * ```\n */\n hasField(key: string): boolean {\n return key in this;\n }\n\n /**\n * Retrieves a custom field value from the error object.\n *\n * This method can access both custom fields and built-in fields.\n * Returns `undefined` if the field doesn't exist.\n *\n * @param key - The field name to retrieve\n * @returns The field value, or `undefined` if it doesn't exist\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\");\n * err.setAdditionalFields({ userId: \"123\", role: \"admin\" });\n *\n * err.getField(\"userId\"); // \"123\"\n * err.getField(\"role\"); // \"admin\"\n * err.getField(\"code\"); // \"ERR\" (built-in field)\n * err.getField(\"unknown\"); // undefined\n * ```\n */\n getField(key: string): unknown {\n return this[key];\n }\n\n /**\n * Serializes the error to a JSON-compatible object.\n *\n * This method is automatically called by JSON.stringify() and includes:\n * - Built-in fields: code, message, segment (if set), path (if set), redirect (if set)\n * - All custom fields added via setAdditionalFields() or constructor\n * - Excludes: stack trace (for security/cleanliness)\n *\n * @returns A plain object representation of the error, suitable for JSON serialization\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * message: \"Route not found\",\n * path: \"/admin/users/123\"\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * JSON.stringify(err);\n * // {\n * // \"code\": \"ROUTE_NOT_FOUND\",\n * // \"message\": \"Route not found\",\n * // \"path\": \"/admin/users/123\",\n * // \"userId\": \"123\"\n * // }\n * ```\n */\n toJSON(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n code: this.code,\n message: this.message,\n };\n\n if (this.segment !== undefined) {\n result.segment = this.segment;\n }\n if (this.path !== undefined) {\n result.path = this.path;\n }\n if (this.redirect !== undefined) {\n result.redirect = this.redirect;\n }\n\n // add all public fields\n // Using Set.has() for O(1) lookup instead of Array.includes() O(n)\n // Overall complexity: O(n) instead of O(n*m)\n const excludeKeys = new Set([\n \"code\",\n \"message\",\n \"segment\",\n \"path\",\n \"redirect\",\n \"stack\",\n ]);\n\n for (const key in this) {\n if (Object.hasOwn(this, key) && !excludeKeys.has(key)) {\n result[key] = this[key];\n }\n }\n\n return result;\n }\n}\n","// packages/real-router/modules/core/dependencies.ts\n\nimport { logger } from \"logger\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type { DefaultDependencies, Router } from \"core-types\";\n\nfunction validateStringKey(\n methodName: string,\n key: unknown,\n): asserts key is string {\n if (typeof key !== \"string\") {\n throw new TypeError(\n `[router.${methodName}]: dependency name must be a string, got ${typeof key}`,\n );\n }\n}\n\nconst DEPENDENCY_LIMITS = {\n WARN: 20,\n ERROR: 50,\n HARD_LIMIT: 100,\n} as const;\n\nfunction checkDependencyCount(deps: object, methodName: string): void {\n const currentCount = Object.keys(deps).length;\n\n if (currentCount === DEPENDENCY_LIMITS.WARN) {\n logger.warn(\n `router.${methodName}`,\n `${DEPENDENCY_LIMITS.WARN} dependencies registered. ` +\n `Consider if all are necessary.`,\n );\n } else if (currentCount === DEPENDENCY_LIMITS.ERROR) {\n logger.error(\n `router.${methodName}`,\n `${DEPENDENCY_LIMITS.ERROR} dependencies registered! ` +\n `This indicates architectural problems. ` +\n `Hard limit at ${DEPENDENCY_LIMITS.HARD_LIMIT}.`,\n );\n } else if (currentCount >= DEPENDENCY_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.${methodName}] Dependency limit exceeded (${DEPENDENCY_LIMITS.HARD_LIMIT}). ` +\n `Current: ${currentCount}. This is likely a bug in your code. ` +\n `If you genuinely need more dependencies, your architecture needs refactoring.`,\n );\n }\n}\n\nexport function withDependencies<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(dependencies: Partial<Dependencies>) {\n const dependencyNotFoundError = (method: string, name: keyof Dependencies) =>\n new ReferenceError(\n `[router.${method}]: dependency \"${String(name)}\" not found`,\n );\n\n const setDependencies = (deps: Partial<Dependencies>) => {\n // Reject non-plain objects (classes, Date, Map, Array)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!(deps && typeof deps === \"object\" && deps.constructor === Object)) {\n throw new TypeError(\n `[router.setDependencies] Invalid argument: expected plain object, received ${getTypeDescription(\n deps,\n )}`,\n );\n }\n\n // Getters can throw, return different values, or have side effects\n for (const dependencyName in deps) {\n if (Object.getOwnPropertyDescriptor(deps, dependencyName)?.get) {\n throw new TypeError(\n `[router.setDependencies] Getters not allowed: \"${dependencyName}\"`,\n );\n }\n }\n\n // Atomic limit check - either all set or none\n checkDependencyCount(\n {\n ...routerDependencies,\n ...deps,\n },\n \"setDependencies\",\n );\n\n const overwrittenKeys = [];\n\n for (const key in deps) {\n if (deps[key] !== undefined) {\n if (Object.hasOwn(routerDependencies, key)) {\n overwrittenKeys.push(key);\n }\n\n routerDependencies[key] = deps[key];\n }\n }\n\n if (overwrittenKeys.length > 0) {\n logger.warn(\n \"router.setDependencies\",\n \"Overwritten:\",\n overwrittenKeys.join(\", \"),\n );\n }\n };\n\n // Create null-prototype object to avoid prototype pollution\n\n const routerDependencies: Partial<Dependencies> = Object.create(\n null,\n ) as Partial<Dependencies>;\n\n setDependencies(dependencies);\n\n return (router: Router<Dependencies>): Router<Dependencies> => {\n router.setDependency = <K extends keyof Dependencies & string>(\n dependencyName: K,\n dependencyValue: Dependencies[K],\n ): Router<Dependencies> => {\n // undefined = \"don't set\" (feature for conditional setting)\n if (dependencyValue === undefined) {\n return router;\n }\n\n validateStringKey(\"setDependency\", dependencyName);\n\n const isNewKey = !Object.hasOwn(routerDependencies, dependencyName);\n\n if (isNewKey) {\n // Only check limit when adding new keys (overwrites don't increase count)\n checkDependencyCount(routerDependencies, \"setDependency\");\n } else {\n const oldValue = routerDependencies[dependencyName];\n const isChanging = oldValue !== dependencyValue;\n // Special case for NaN idempotency (NaN !== NaN is always true)\n const bothAreNaN =\n Number.isNaN(oldValue) && Number.isNaN(dependencyValue);\n\n if (isChanging && !bothAreNaN) {\n logger.warn(\n \"router.setDependency\",\n \"Router dependency already exists and is being overwritten:\",\n dependencyName,\n );\n }\n }\n\n routerDependencies[dependencyName] = dependencyValue;\n\n return router;\n };\n\n router.setDependencies = (\n deps: Partial<Dependencies>,\n ): Router<Dependencies> => {\n setDependencies(deps);\n\n return router;\n };\n\n router.getDependency = <K extends keyof Dependencies>(\n dependencyName: K,\n ): Dependencies[K] => {\n validateStringKey(\"getDependency\", dependencyName);\n\n const dependency = routerDependencies[dependencyName];\n\n if (dependency === undefined) {\n throw dependencyNotFoundError(\"getDependency\", dependencyName);\n }\n\n return dependency;\n };\n\n router.getDependencies = (): Partial<Dependencies> => ({\n ...routerDependencies,\n });\n\n router.removeDependency = (\n dependencyName: keyof Dependencies,\n ): Router<Dependencies> => {\n if (!Object.hasOwn(routerDependencies, dependencyName)) {\n logger.warn(\n `router.removeDependency`,\n `Attempted to remove non-existent dependency: \"${getTypeDescription(dependencyName)}\"`,\n );\n }\n\n delete routerDependencies[dependencyName];\n\n return router;\n };\n\n router.hasDependency = (dependencyName: keyof Dependencies): boolean => {\n return Object.hasOwn(routerDependencies, dependencyName);\n };\n\n router.resetDependencies = (): Router<Dependencies> => {\n for (const key in routerDependencies) {\n delete routerDependencies[key];\n }\n\n return router;\n };\n\n return router;\n };\n}\n","// packages/real-router/modules/core/middleware.ts\n\nimport { logger } from \"logger\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type {\n Unsubscribe,\n DefaultDependencies,\n Middleware,\n MiddlewareFactory,\n Router,\n} from \"core-types\";\n\n/**\n * Gets a displayable name for a factory function.\n * Returns \"anonymous\" for arrow functions or unnamed functions.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction getFactoryName(factory: Function): string {\n if (factory.name) {\n return factory.name;\n }\n\n return \"anonymous\";\n}\n\n/**\n * Middleware registry limits to prevent memory leaks and architectural issues.\n * Based on practical experience with production routers.\n */\nconst MIDDLEWARE_LIMITS = {\n WARN: 15, // Log warning - consider refactoring\n ERROR: 30, // Log error - architectural problem\n HARD_LIMIT: 50, // Throw error - critical issue\n} as const;\n\n/**\n * Validates that a value is a valid middleware factory function.\n * Provides clear error messages for debugging.\n *\n * @param middlewareFactory - Value to validate\n * @param index - Position in the array for better error messages\n * @throws {TypeError} If the value is not a function\n */\nfunction validateMiddlewareFactory<Dependencies extends DefaultDependencies>(\n middlewareFactory: unknown,\n index: number,\n): asserts middlewareFactory is MiddlewareFactory<Dependencies> {\n if (typeof middlewareFactory !== \"function\") {\n throw new TypeError(\n `[router.useMiddleware] Expected middleware factory function at index ${index}, ` +\n `got ${getTypeDescription(middlewareFactory)}`,\n );\n }\n}\n\n/**\n * Validates that a middleware factory returned a valid middleware function.\n * Runtime protection against incorrect middleware implementations.\n *\n * @param middleware - Return value from middleware factory\n * @param factory - The factory that produced this middleware (for error context)\n * @throws {TypeError} If the middleware is not a function\n */\nfunction validateMiddleware<Dependencies extends DefaultDependencies>(\n middleware: unknown,\n factory: MiddlewareFactory<Dependencies>,\n): asserts middleware is Middleware {\n if (typeof middleware !== \"function\") {\n throw new TypeError(\n `[router.useMiddleware] Middleware factory must return a function, ` +\n `got ${getTypeDescription(middleware)}. ` +\n `Factory: ${getFactoryName(factory)}`,\n );\n }\n}\n\n/**\n * Checks the total middleware count and emits warnings/errors based on thresholds.\n * Prevents memory leaks and architectural degradation.\n *\n * @param newCount - Number of middleware to be added\n * @param currentSize - Current number of registered middleware\n * @throws {Error} If adding would exceed hard limit\n */\nfunction validateMiddlewareCount(newCount: number, currentSize: number): void {\n const totalSize = newCount + currentSize;\n\n // Hard limit check - fail fast to prevent memory issues\n if (totalSize > MIDDLEWARE_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.useMiddleware] Middleware limit exceeded (${MIDDLEWARE_LIMITS.HARD_LIMIT}). ` +\n `Current: ${currentSize}, Attempting to add: ${newCount}. ` +\n `This indicates an architectural problem. Consider consolidating middleware.`,\n );\n }\n\n // Graduated warnings for early problem detection\n if (totalSize >= MIDDLEWARE_LIMITS.ERROR) {\n logger.error(\n \"router.useMiddleware\",\n `${totalSize} middleware registered! ` +\n `This is excessive and will impact performance. ` +\n `Hard limit at ${MIDDLEWARE_LIMITS.HARD_LIMIT}.`,\n );\n } else if (totalSize >= MIDDLEWARE_LIMITS.WARN) {\n logger.warn(\n \"router.useMiddleware\",\n `${totalSize} middleware registered. ` + `Consider if all are necessary.`,\n );\n }\n}\n\n/**\n * Adds middleware capabilities to a router instance.\n * Middleware functions are executed during navigation transitions.\n *\n * Design decisions:\n * - Uses Set for O(1) duplicate detection and removal\n * - Maintains Map for factory->function mapping\n * - Preserves insertion order (important for middleware chain)\n * - Atomic operations with rollback on failure\n * - Prevents duplicate registrations\n *\n * @param router - Router instance to enhance\n * @returns Enhanced router with middleware methods\n */\nexport function withMiddleware<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n // Use Set for efficient O(1) operations and automatic deduplication\n const middlewareFactories = new Set<MiddlewareFactory<Dependencies>>();\n\n // Map factories to their produced middleware for efficient lookup\n const factoryToMiddleware = new Map<\n MiddlewareFactory<Dependencies>,\n Middleware\n >();\n\n /**\n * Registers one or more middleware factories with the router.\n * Middleware are executed in order during navigation transitions.\n *\n * @param passedMiddlewareFactories - Factory functions that create middleware\n * @returns Unsubscribe function to remove all added middleware\n * @throws {TypeError} If any factory is not a function\n * @throws {Error} If factory is already registered or limit exceeded\n *\n * @example\n * const unsubscribe = router.useMiddleware(\n * authMiddleware,\n * loggingMiddleware\n * );\n * // Later: unsubscribe() to remove both\n */\n router.useMiddleware = (\n ...passedMiddlewareFactories: MiddlewareFactory<Dependencies>[]\n ): Unsubscribe => {\n // Early validation before any state changes\n validateMiddlewareCount(\n passedMiddlewareFactories.length,\n middlewareFactories.size,\n );\n\n // Validate ALL factories first (atomicity principle)\n passedMiddlewareFactories.forEach((factory, index) => {\n validateMiddlewareFactory<Dependencies>(factory, index);\n\n // Prevent duplicate registrations to avoid confusion\n if (middlewareFactories.has(factory)) {\n throw new Error(\n `[router.useMiddleware] Middleware factory already registered. ` +\n `To re-register, first unsubscribe the existing middleware. ` +\n `Factory: ${getFactoryName(factory)}`,\n );\n }\n });\n\n // Track successfully initialized middleware for potential rollback\n const initialized: {\n factory: MiddlewareFactory<Dependencies>;\n middleware: Middleware;\n }[] = [];\n\n // Initialize phase with rollback capability\n try {\n for (const factory of passedMiddlewareFactories) {\n // Create middleware instance with router context\n const middleware = factory(router, router.getDependency);\n\n // Validate the produced middleware\n validateMiddleware<Dependencies>(middleware, factory);\n\n initialized.push({ factory, middleware });\n }\n } catch (error) {\n // Rollback: Clean up any successfully initialized middleware\n // This ensures atomicity - either all succeed or none are registered\n logger.error(\n \"router.useMiddleware\",\n \"Failed to initialize middleware, rolling back\",\n error,\n );\n\n // No cleanup needed as we haven't modified state yet\n throw error;\n }\n\n // Commit phase: All validations passed, update state atomically\n for (const { factory, middleware } of initialized) {\n middlewareFactories.add(factory);\n factoryToMiddleware.set(factory, middleware);\n }\n\n // Return unsubscribe function specific to THIS call's middleware\n return (): void => {\n // Remove only the middleware added in THIS specific call\n for (const { factory } of initialized) {\n const wasDeleted = middlewareFactories.delete(factory);\n\n if (!wasDeleted) {\n // This shouldn't happen but log for debugging\n logger.warn(\n \"router.useMiddleware\",\n `Attempted to remove non-existent middleware factory. ` +\n `This might indicate a memory leak or incorrect cleanup logic.`,\n );\n }\n\n // Clean up the mapping\n factoryToMiddleware.delete(factory);\n }\n };\n };\n\n /**\n * Removes all registered middleware from the router.\n * Useful for testing or complete router reset.\n *\n * @returns The router instance for chaining\n */\n router.clearMiddleware = (): Router<Dependencies> => {\n // Clear both collections efficiently\n middlewareFactories.clear();\n factoryToMiddleware.clear();\n\n return router;\n };\n\n /**\n * Returns a copy of registered middleware factories.\n * Preserves insertion order (important for middleware chain).\n *\n * @internal Used by router.clone(). Will be removed from public API.\n * @deprecated Use behavior testing instead of checking internal state\n * @returns Array of middleware factories in registration order\n */\n router.getMiddlewareFactories = (): MiddlewareFactory<Dependencies>[] => {\n // Return a copy to prevent external mutations\n // Set iterator preserves insertion order (ES2015 guarantee)\n return [...middlewareFactories];\n };\n\n /**\n * Returns the actual middleware functions in execution order.\n * Used internally by the transition system.\n *\n * @internal Used by transition execution. Not part of public API.\n * @returns Array of middleware functions ready for execution\n */\n router.getMiddlewareFunctions = (): Middleware[] => {\n // Return middleware functions in insertion order\n // Map preserves insertion order (ES2015 guarantee)\n return [...factoryToMiddleware.values()];\n };\n\n return router;\n}\n","// packages/real-router/modules/transition/makeError.ts\n\nimport type { RouterError } from \"@real-router/core\";\n\n// Helper: Creating an error with code\nexport const makeError = (\n code: string,\n err?: RouterError,\n): RouterError | undefined => {\n if (!err) {\n return undefined;\n }\n\n err.setCode(code);\n\n return err;\n};\n","// packages/real-router/modules/transition/mergeStates.ts\n\nimport type { Params, State, StateMeta } from \"core-types\";\n\n/**\n * Merges two states with toState taking priority over fromState.\n *\n * Priority order for state fields: toState > fromState\n * Priority order for meta fields: toState.meta > fromState.meta > defaults\n *\n * Special case: meta.params are merged (not replaced):\n * { ...toState.meta.params, ...fromState.meta.params }\n *\n * @param toState - Target state (higher priority)\n * @param fromState - Source state (lower priority)\n * @returns New merged state object\n */\nexport const mergeStates = (toState: State, fromState: State): State => {\n const toMeta = toState.meta;\n const fromMeta = fromState.meta;\n\n // Optimization #1: Conditional merge for params\n // Use spread only when both are defined\n const toParams = toMeta?.params;\n const fromParams = fromMeta?.params;\n\n // Both have params - need to merge; otherwise use whichever is defined\n const metaParams: Params =\n toParams && fromParams\n ? { ...toParams, ...fromParams }\n : (toParams ?? fromParams ?? {});\n\n // Optimization #2: Build meta with defaults, then apply fromMeta, then toMeta\n // Note: StateMeta can have custom fields added by guards/middleware, so we preserve them\n const resultMeta: StateMeta = {\n // Defaults first\n id: 1,\n options: {},\n redirected: false,\n // fromMeta fields (lower priority, may include custom fields)\n ...fromMeta,\n // toMeta fields (higher priority, may include custom fields)\n ...toMeta,\n // Explicitly set params to our merged version (override spread)\n params: metaParams,\n };\n\n // Optimization #4: Copy all toState fields (including custom ones)\n // then explicitly set meta to our merged version\n // Note: State can have custom fields added by middleware, so we must preserve them\n return {\n ...toState,\n meta: resultMeta,\n };\n};\n","// packages/real-router/modules/transition/processLifecycleResult.ts\n\n/* eslint-disable promise/always-return, promise/no-callback-in-promise */\nimport { isPromise, isState } from \"type-guards\";\n\nimport { errorCodes, RouterError } from \"@real-router/core\";\n\nimport type { DoneFn, State, ActivationFn } from \"core-types\";\n\n// Helper: Lifecycle results Processing Function\nexport const processLifecycleResult = (\n result: ReturnType<ActivationFn>,\n done: DoneFn,\n segment?: string,\n): void => {\n const errorData = segment ? { segment } : {};\n\n if (result === undefined) {\n // We expect a Done call\n return;\n }\n\n if (typeof result === \"boolean\") {\n if (result) {\n done();\n } else {\n done(new RouterError(errorCodes.TRANSITION_ERR, errorData));\n }\n\n return;\n }\n\n if (isState(result)) {\n // Type guard should narrow, but TypeScript needs help\n done(undefined, result);\n\n return;\n }\n\n if (isPromise<State | boolean | undefined>(result)) {\n // Callback-based API: promise handled internally, not returned\n // Mixing promises with callbacks is intentional for backward compatibility\n // Type assertion needed due to complex union type narrowing\n // Optimization: .then(onFulfill, onReject) instead of .then().catch()\n // This saves 1 Promise allocation per async middleware call\n void result.then(\n (resVal) => {\n // Issue #38: Handle Promise<boolean> same as sync boolean\n if (typeof resVal === \"boolean\") {\n if (resVal) {\n done();\n } else {\n done(new RouterError(errorCodes.TRANSITION_ERR, errorData));\n }\n } else {\n done(undefined, resVal);\n }\n },\n (error_: unknown) => {\n let error: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n } = errorData;\n\n if (error_ instanceof Error) {\n error = {\n ...errorData,\n message: error_.message,\n stack: error_.stack,\n };\n\n // Error.cause requires ES2022+ - safely access it if present\n if (\"cause\" in error_ && error_.cause !== undefined) {\n error.cause = error_.cause;\n }\n } else if (error_ && typeof error_ === \"object\") {\n error = { ...errorData, ...error_ };\n }\n\n done(new RouterError(errorCodes.TRANSITION_ERR, error));\n },\n );\n\n return;\n }\n\n // This should never be reached - all valid ActivationFn return types are handled above\n // If we get here, it means the activation function returned an unexpected type\n done(\n new RouterError(errorCodes.TRANSITION_ERR, {\n ...errorData,\n message: `Invalid lifecycle result type: ${typeof result}`,\n }),\n );\n};\n","// packages/real-router/modules/transition/wrapSyncError.ts\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// Reserved properties that conflict with RouterError constructor\n// Issue #39: Filter these when wrapping sync errors to avoid TypeError\nconst reservedRouterErrorProps = new Set([\n \"code\",\n \"segment\",\n \"path\",\n \"redirect\",\n]);\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 - Optional route segment name (for lifecycle hooks)\n * @returns Structured error metadata for RouterError\n *\n * @example\n * ```typescript\n * try {\n * hookFn();\n * } catch (error) {\n * const metadata = wrapSyncError(error, \"users.profile\");\n * done(new RouterError(errorCodes.TRANSITION_ERR, metadata));\n * }\n * ```\n */\nexport function wrapSyncError(\n thrown: unknown,\n segment?: string,\n): SyncErrorMetadata {\n // Base metadata - always include segment if provided\n const base: SyncErrorMetadata = segment ? { 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 // Issue #39: Skip reserved properties to avoid RouterError constructor TypeError\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","// packages/real-router/modules/transition/executeLifecycleHooks.ts\n\nimport { logger } from \"logger\";\nimport { isState } from \"type-guards\";\n\nimport { errorCodes, RouterError } from \"@real-router/core\";\n\nimport { makeError } from \"./makeError\";\nimport { mergeStates } from \"./mergeStates\";\nimport { processLifecycleResult } from \"./processLifecycleResult\";\nimport { wrapSyncError } from \"./wrapSyncError\";\n\nimport type {\n DoneFn,\n State,\n ActivationFn,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\n/**\n * Strict callback type where state is always provided.\n *\n * @internal\n */\ntype StrictDoneFn = (error: RouterErrorType | undefined, state: State) => void;\n\n/**\n * Safely invokes a callback, catching and logging any errors.\n *\n * @internal\n */\nfunction safeCallback(\n callback: StrictDoneFn,\n error: RouterErrorType | undefined,\n state: State,\n): void {\n try {\n callback(error, state);\n } catch (error_) {\n logger.error(\"core:lifecycle\", \"Error in lifecycle callback:\", error_);\n }\n}\n\n// Helper: execution of the Lifecycle Hooks group\nexport const executeLifecycleHooks = (\n hooks: Map<string, ActivationFn>,\n toState: State,\n fromState: State | undefined,\n segments: string[],\n errorCode: string,\n isCancelled: () => boolean,\n callback: StrictDoneFn,\n): void => {\n let currentState = toState;\n const segmentsToProcess = segments.filter((name) => hooks.has(name));\n\n if (segmentsToProcess.length === 0) {\n safeCallback(callback, undefined, currentState);\n\n return;\n }\n\n let index = 0;\n\n // If the transition is cancelled, we will not process the hooks\n // Guards cannot redirect - they can only allow (true/undefined) or block (false/error)\n const done: DoneFn = (err, state) => {\n if (err) {\n // Guards cannot redirect - convert any redirect to error\n if (err.redirect) {\n const errorWithoutRedirect = new RouterError(errorCode, {\n message: \"Guards cannot redirect. Use middleware for redirects.\",\n attemptedRedirect: err.redirect,\n });\n\n processNext(errorWithoutRedirect);\n } else {\n processNext(err);\n }\n } else {\n processNext(undefined, state);\n }\n };\n\n const processNext = (err?: RouterErrorType, newState?: State): void => {\n if (isCancelled()) {\n safeCallback(\n callback,\n new RouterError(errorCodes.TRANSITION_CANCELLED),\n currentState,\n );\n\n return;\n }\n\n if (err) {\n safeCallback(callback, makeError(errorCode, err), currentState);\n\n return;\n }\n\n // Processing a new state\n // Optimization: Early return for undefined newState (most common case ~90%+)\n // This avoids isState() call and subsequent checks\n if (!newState) {\n // Fast path: skip all checks\n } else if (newState !== currentState && isState(newState)) {\n // Guards cannot redirect to a different route\n if (newState.name !== currentState.name) {\n const redirectNotAllowedErr = new RouterError(errorCode, {\n message: \"Guards cannot redirect to different route. Use middleware.\",\n attemptedRedirect: {\n name: newState.name,\n params: newState.params,\n path: newState.path,\n },\n });\n\n safeCallback(callback, redirectNotAllowedErr, currentState);\n\n return;\n }\n\n // Same route - safe to merge (param modifications, meta changes)\n const hasChanged =\n newState.params !== currentState.params ||\n newState.path !== currentState.path;\n\n if (hasChanged) {\n logger.error(\n \"core:transition\",\n \"Warning: State mutated during transition\",\n { from: currentState, to: newState },\n );\n }\n\n currentState = mergeStates(newState, currentState);\n }\n\n if (index >= segmentsToProcess.length) {\n safeCallback(callback, undefined, currentState);\n\n return;\n }\n\n const segment = segmentsToProcess[index++];\n // Safe cast: segmentsToProcess only contains names that exist in hooks (filtered above)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed by filter\n const hookFn = hooks.get(segment)!;\n\n try {\n const result = hookFn.call(null, currentState, fromState, done);\n\n processLifecycleResult(result, done, segment);\n } catch (syncError: unknown) {\n // Note: TRANSITION_ERR is placeholder - makeError() will set correct code\n done(\n new RouterError(\n errorCodes.TRANSITION_ERR,\n wrapSyncError(syncError, segment),\n ),\n );\n }\n };\n\n processNext();\n};\n","// packages/real-router/modules/transition/executeMiddleware.ts\n\nimport { logger } from \"logger\";\nimport { isState } from \"type-guards\";\n\nimport { errorCodes, RouterError } from \"@real-router/core\";\n\nimport { makeError } from \"./makeError\";\nimport { mergeStates } from \"./mergeStates\";\nimport { processLifecycleResult } from \"./processLifecycleResult\";\nimport { wrapSyncError } from \"./wrapSyncError\";\n\nimport type {\n DoneFn,\n State,\n ActivationFn,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\n/**\n * Strict callback type where state is always provided.\n *\n * @internal\n */\ntype StrictDoneFn = (error: RouterErrorType | undefined, state: State) => void;\n\n/**\n * Safely invokes a callback, catching and logging any errors.\n *\n * @internal\n */\nfunction safeCallback(\n callback: StrictDoneFn,\n error: RouterErrorType | undefined,\n state: State,\n): void {\n try {\n callback(error, state);\n } catch (error_) {\n logger.error(\n \"real-router:middleware\",\n \"Error in middleware callback:\",\n error_,\n );\n }\n}\n\n// Helper: processing middleware\nexport const executeMiddleware = (\n middlewareFunctions: ActivationFn[],\n toState: State,\n fromState: State | undefined,\n isCancelled: () => boolean,\n callback: StrictDoneFn,\n): void => {\n let currentState = toState;\n let index = 0;\n\n // If the transition is cancelled, we will not process the middleware\n // Note: Middleware redirects are not supported - errors pass through\n const done: DoneFn = (err, state) => {\n if (err) {\n processNext(err);\n } else {\n processNext(undefined, state);\n }\n };\n\n const processNext = (err?: RouterErrorType, newState?: State): void => {\n if (isCancelled()) {\n safeCallback(\n callback,\n new RouterError(errorCodes.TRANSITION_CANCELLED),\n currentState,\n );\n\n return;\n }\n\n if (err) {\n safeCallback(\n callback,\n makeError(errorCodes.TRANSITION_ERR, err),\n currentState,\n );\n\n return;\n }\n\n // Processing a new state\n // Optimization: Early return for undefined newState (most common case ~90%+)\n // This avoids isState() call and subsequent checks\n if (!newState) {\n // Fast path: skip all checks\n } else if (newState !== currentState && isState(newState)) {\n const hasChanged =\n newState.name !== currentState.name ||\n newState.params !== currentState.params ||\n newState.path !== currentState.path;\n\n if (hasChanged) {\n logger.error(\n \"real-router:middleware\",\n \"Warning: State mutated during middleware execution\",\n { from: currentState, to: newState },\n );\n }\n\n currentState = mergeStates(newState, currentState);\n }\n\n if (index >= middlewareFunctions.length) {\n safeCallback(callback, undefined, currentState);\n\n return;\n }\n\n const middlewareFn = middlewareFunctions[index++];\n\n try {\n const result = middlewareFn.call(null, currentState, fromState, done);\n\n processLifecycleResult(result, done);\n } catch (syncError: unknown) {\n done(\n new RouterError(errorCodes.TRANSITION_ERR, wrapSyncError(syncError)),\n );\n }\n };\n\n processNext();\n};\n","// packages/real-router/modules/transitionPath.ts\n\nimport { logger } from \"logger\";\nimport { validateState } from \"type-guards\";\n\nimport type { Params, State } from \"core-types\";\n\n/**\n * Parameters extracted from a route segment.\n * Maps parameter names to their string values.\n */\ntype SegmentParams = Record<string, string>;\n\n/**\n * Represents a transition path between two router states.\n * Contains information about which route segments need to be activated/deactivated.\n */\ninterface TransitionPath {\n /** The common ancestor route segment where paths diverge */\n intersection: string;\n /** Route segments that need to be deactivated (in reverse order) */\n toDeactivate: string[];\n /** Route segments that need to be activated (in order) */\n toActivate: string[];\n}\n\n// Constants for better maintainability\nconst ROUTE_SEGMENT_SEPARATOR = \".\";\nconst EMPTY_INTERSECTION = \"\";\nconst DEFAULT_ROUTE_NAME = \"\";\n\n/**\n * Builds a reversed copy of a string array.\n * Optimization: single pass instead of creating intermediate array with .toReversed().\n *\n * @param arr - Source array\n * @returns New array with elements in reverse order\n * @internal\n */\nfunction reverseArray(arr: string[]): string[] {\n const len = arr.length;\n const result: string[] = [];\n\n for (let i = len - 1; i >= 0; i--) {\n result.push(arr[i]);\n }\n\n return result;\n}\n\n/**\n * Handles conversion of route names with many segments (5+).\n * Internal helper for nameToIDs function.\n *\n * Uses optimized hybrid approach: split to get segments, then slice original\n * string to build cumulative paths. This approach is 65-81% faster than\n * string concatenation for typical cases (5-10 segments).\n *\n * @param name - Route name with 5 or more segments\n * @returns Array of cumulative segment IDs\n * @throws {Error} If route depth exceeds maximum allowed\n * @internal\n */\nfunction nameToIDsGeneral(name: string): string[] {\n // We know there are at least 5 segments at this point (after fast paths)\n const segments = name.split(ROUTE_SEGMENT_SEPARATOR);\n const segmentCount = segments.length;\n\n // First segment is always just itself\n const ids: string[] = [segments[0]];\n\n // Calculate cumulative lengths and slice from original string\n // This avoids repeated string concatenation (O(k²) → O(k))\n let cumulativeLen = segments[0].length;\n\n for (let i = 1; i < segmentCount - 1; i++) {\n cumulativeLen += 1 + segments[i].length; // +1 for dot separator\n ids.push(name.slice(0, cumulativeLen));\n }\n\n // Last segment is always the full route name\n ids.push(name);\n\n return ids;\n}\n\n/**\n * Extracts segment-specific parameters from a state object.\n * Only includes parameters that are valid for serialization (primitives).\n *\n * @param name - Segment name to extract parameters for\n * @param state - State containing the parameters\n * @returns Object with extracted segment parameters\n */\nfunction extractSegmentParams(name: string, state: State): SegmentParams {\n const keys = state.meta?.params[name];\n\n // No parameters defined for this segment\n if (!keys || typeof keys !== \"object\") {\n return {};\n }\n\n const result: SegmentParams = {};\n\n for (const key in keys as Params) {\n // Skip inherited properties\n if (!Object.hasOwn(keys, key)) {\n continue;\n }\n\n // Skip undefined values for consistent behavior (treat { key: undefined } same as missing key)\n // Edge case: can appear from manual State creation or object merging\n // @ts-expect-error Params type doesn't allow undefined, but it can appear at runtime\n if (keys[key] === undefined) {\n continue;\n }\n\n const value = state.params[key];\n\n // Skip null/undefined values\n if (value == null) {\n continue;\n }\n\n // Check type and add to result\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n result[key] = String(value);\n } else {\n // Warn about unsupported complex types (arrays, nested objects)\n // Note: After null check and primitive check, only objects remain here.\n // symbol/function/bigint are rejected by isParams validation before reaching this code.\n logger.warn(\n \"transitionPath.extractSegmentParams\",\n `Unsupported param type for key \"${key}\": ${typeof value}. ` +\n `Only primitives (string, number, boolean) are supported.`,\n typeof value,\n );\n }\n }\n\n return result;\n}\n\n/**\n * Finds the point where two state paths diverge based on segments and parameters.\n * Compares both segment names and their parameters to find the first difference.\n *\n * @param toState - Target state\n * @param fromState - Source state\n * @param toStateIds - Segment IDs for target state\n * @param fromStateIds - Segment IDs for source state\n * @param maxI - Maximum index to check (minimum of both arrays)\n * @returns Index of first difference, or maxI if all checked segments match\n */\nfunction pointOfDifference(\n toState: State,\n fromState: State,\n toStateIds: string[],\n fromStateIds: string[],\n maxI: number,\n): number {\n for (let i = 0; i < maxI; i++) {\n const toSegment = toStateIds[i];\n const fromSegment = fromStateIds[i];\n\n // Different segment names - immediate difference\n if (toSegment !== fromSegment) {\n return i;\n }\n\n // Same segment name - check parameters\n const toParams = extractSegmentParams(toSegment, toState);\n const fromParams = extractSegmentParams(fromSegment, fromState);\n\n // Fast check: different number of parameters\n const toKeys = Object.keys(toParams);\n const fromKeys = Object.keys(fromParams);\n\n if (toKeys.length !== fromKeys.length) {\n return i;\n }\n\n // Detailed check: compare parameter values\n for (const key of toKeys) {\n if (toParams[key] !== fromParams[key]) {\n return i;\n }\n }\n }\n\n return maxI;\n}\n\n/**\n * Converts a route name to an array of hierarchical segment identifiers.\n * Each segment ID includes all parent segments in the path.\n *\n * @param name - Route name in dot notation (e.g., 'users.profile.edit')\n * @returns Array of cumulative segment IDs\n * @throws {Error} If route depth exceeds maximum allowed depth\n *\n * @example\n * // Simple route\n * nameToIDs('users');\n * // Returns: ['users']\n *\n * @example\n * // Nested route\n * nameToIDs('users.profile.edit');\n * // Returns: ['users', 'users.profile', 'users.profile.edit']\n *\n * @example\n * // Empty string (root route)\n * nameToIDs('');\n * // Returns: ['']\n *\n * @remarks\n * Input parameter is NOT validated in this function for performance reasons.\n * Validation significantly slows down nameToIDs execution.\n * The input should be validated by the function/method that calls nameToIDs.\n */\nexport function nameToIDs(name: string): string[] {\n // ===== FAST PATH 1: Empty string (root route) =====\n // Most common in initial navigation\n if (!name) {\n return [DEFAULT_ROUTE_NAME];\n }\n\n // ===== FAST PATH 2: Single segment (no dots) =====\n // Very common: 'home', 'users', 'settings', etc.\n const firstDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR);\n\n if (firstDot === -1) {\n return [name];\n }\n\n // ===== FAST PATH 3: Two segments =====\n // Common: 'users.list', 'admin.dashboard', etc.\n const secondDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR, firstDot + 1);\n\n if (secondDot === -1) {\n return [\n name.slice(0, firstDot), // 'users'\n name, // 'users.list'\n ];\n }\n\n // ===== FAST PATH 4: Three segments =====\n // Common: 'users.profile.edit', 'app.settings.general', etc.\n const thirdDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR, secondDot + 1);\n\n if (thirdDot === -1) {\n return [\n name.slice(0, firstDot), // 'users'\n name.slice(0, secondDot), // 'users.profile'\n name, // 'users.profile.edit'\n ];\n }\n\n // ===== FAST PATH 5: Four segments =====\n const fourthDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR, thirdDot + 1);\n\n if (fourthDot === -1) {\n return [\n name.slice(0, firstDot),\n name.slice(0, secondDot),\n name.slice(0, thirdDot),\n name,\n ];\n }\n\n // ===== STANDARD PATH: 5+ segments =====\n // Less common, use general algorithm with optimizations\n return nameToIDsGeneral(name);\n}\n\n/**\n * Calculates the transition path between two router states.\n * Determines which route segments need to be deactivated and activated\n * to transition from one state to another.\n *\n * @param toState - Target state to transition to\n * @param fromState - Current state to transition from (optional)\n * @returns Transition path with intersection and segments to activate/deactivate\n *\n * @throws {TypeError} When toState is null or undefined\n * @throws {TypeError} When toState is not an object\n * @throws {TypeError} When toState.name is missing or not a string\n * @throws {TypeError} When toState.params is missing or not an object\n * @throws {TypeError} When toState.path is missing or not a string\n * @throws {TypeError} When toState.name contains invalid route format:\n * - Contains only whitespace (e.g., \" \")\n * - Has consecutive dots (e.g., \"users..profile\")\n * - Has leading/trailing dots (e.g., \".users\" or \"users.\")\n * - Segments don't match pattern [a-zA-Z_][a-zA-Z0-9_-]* (e.g., \"users.123\")\n * - Contains spaces or special characters (e.g., \"users profile\")\n * - Exceeds maximum length (8192 characters)\n * @throws {TypeError} When fromState is provided and has any of the validation errors listed above for toState\n *\n * @example\n * // ✅ Valid calls\n * getTransitionPath({ name: 'users.profile', params: {}, path: '/users/profile' });\n * getTransitionPath(toState, fromState);\n * getTransitionPath({ name: '', params: {}, path: '/' }); // root route\n *\n * @example\n * // ❌ Invalid calls that throw TypeError\n * getTransitionPath(null); // toState is null\n * getTransitionPath(undefined); // toState is undefined\n * getTransitionPath({}); // missing required fields\n * getTransitionPath({ name: 123, params: {}, path: '/' }); // name not a string\n * getTransitionPath({ name: 'home', path: '/' }); // missing params\n * getTransitionPath({ name: 'users..profile', params: {}, path: '/' }); // consecutive dots\n * getTransitionPath({ name: '.users', params: {}, path: '/' }); // leading dot\n * getTransitionPath({ name: 'users.', params: {}, path: '/' }); // trailing dot\n * getTransitionPath({ name: 'users profile', params: {}, path: '/' }); // contains space\n * getTransitionPath({ name: 'users.123', params: {}, path: '/' }); // segment starts with number\n * getTransitionPath(validToState, { name: 'invalid..route', params: {}, path: '/' }); // fromState invalid\n *\n * @example\n * // Full activation (no fromState)\n * getTransitionPath(makeState('users.profile'));\n * // Returns: {\n * // intersection: '',\n * // toActivate: ['users', 'users.profile'],\n * // toDeactivate: []\n * // }\n *\n * @example\n * // Partial transition with common ancestor\n * getTransitionPath(\n * makeState('users.profile'),\n * makeState('users.list')\n * );\n * // Returns: {\n * // intersection: 'users',\n * // toActivate: ['users.profile'],\n * // toDeactivate: ['users.list']\n * // }\n *\n * @example\n * // Complete route change\n * getTransitionPath(\n * makeState('admin.dashboard'),\n * makeState('users.profile')\n * );\n * // Returns: {\n * // intersection: '',\n * // toActivate: ['admin', 'admin.dashboard'],\n * // toDeactivate: ['users.profile', 'users']\n * // }\n */\nexport function getTransitionPath(\n toState: State,\n fromState?: State,\n): TransitionPath {\n // Validate required toState\n validateState(toState, \"getTransitionPath\");\n\n // ===== FAST PATH 1: Initial navigation (no fromState) =====\n // This is the best performing case in benchmarks (5M ops/sec)\n if (!fromState) {\n return {\n intersection: EMPTY_INTERSECTION,\n toActivate: nameToIDs(toState.name),\n toDeactivate: [],\n };\n }\n\n // Validate optional fromState\n validateState(fromState, \"getTransitionPath\");\n\n const toStateOptions = toState.meta?.options ?? {};\n\n // ===== FAST PATH 2: Force reload =====\n // Skip all optimization when reload is requested\n if (toStateOptions.reload) {\n return {\n intersection: EMPTY_INTERSECTION,\n toActivate: nameToIDs(toState.name),\n toDeactivate: reverseArray(nameToIDs(fromState.name)),\n };\n }\n\n // ===== FAST PATH 3: Missing meta or meta.params requires full reload =====\n // Check if meta or meta.params is actually missing (not just empty)\n const toHasMeta = toState.meta?.params !== undefined;\n const fromHasMeta = fromState.meta?.params !== undefined;\n\n if (!toHasMeta && !fromHasMeta) {\n // Both states missing meta.params - require full reload\n return {\n intersection: EMPTY_INTERSECTION,\n toActivate: nameToIDs(toState.name),\n toDeactivate: reverseArray(nameToIDs(fromState.name)),\n };\n }\n\n // ===== FAST PATH 4: Same routes with empty meta.params =====\n // If both have empty meta.params {}, no parameter checking needed\n if (toState.name === fromState.name && toHasMeta && fromHasMeta) {\n const toParamsEmpty =\n toState.meta && Object.keys(toState.meta.params).length === 0;\n const fromParamsEmpty =\n fromState.meta && Object.keys(fromState.meta.params).length === 0;\n\n if (toParamsEmpty && fromParamsEmpty) {\n // Both have empty params - no transition needed\n return {\n intersection: toState.name,\n toActivate: [],\n toDeactivate: [],\n };\n }\n }\n\n // ===== STANDARD PATH: Routes with parameters =====\n // Use original algorithm for complex cases with parameters\n const toStateIds = nameToIDs(toState.name);\n const fromStateIds = nameToIDs(fromState.name);\n const maxI = Math.min(fromStateIds.length, toStateIds.length);\n\n // Find where paths diverge based on segments and parameters\n // not obvious validate toState and fromState\n const i = pointOfDifference(\n toState,\n fromState,\n toStateIds,\n fromStateIds,\n maxI,\n );\n\n // Optimization: Build deactivation list in reverse order directly\n // instead of slice(i).toReversed() which creates 2 arrays\n const toDeactivate: string[] = [];\n\n for (let j = fromStateIds.length - 1; j >= i; j--) {\n toDeactivate.push(fromStateIds[j]);\n }\n\n // Build activation list (forward order for proper initialization)\n const toActivate = toStateIds.slice(i);\n\n // Determine intersection point (common ancestor)\n const intersection =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n fromState && i > 0 ? fromStateIds[i - 1] : EMPTY_INTERSECTION;\n\n return {\n intersection,\n toDeactivate,\n toActivate,\n };\n}\n","// packages/real-router/modules/transition/index.ts\n\nimport { RouterError, constants, errorCodes } from \"@real-router/core\";\n\nimport { executeLifecycleHooks } from \"./executeLifecycleHooks\";\nimport { executeMiddleware } from \"./executeMiddleware\";\nimport { getTransitionPath, nameToIDs } from \"../transitionPath\";\n\nimport type {\n NavigationOptions,\n CancelFn,\n State,\n DefaultDependencies,\n Router,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\n/**\n * Strict callback type where state is always provided.\n * Used internally in transition chain where state is guaranteed.\n */\ntype StrictDoneFn = (error: RouterErrorType | undefined, state: State) => void;\n\nexport function transition<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n transitionCallback: (err: RouterErrorType | undefined, state: State) => void,\n): CancelFn {\n // The state of transaction\n let cancelled = false;\n let completed = false;\n\n // We're caching the necessary data\n const [canDeactivateFunctions, canActivateFunctions] =\n router.getLifecycleFunctions();\n const middlewareFunctions = router.getMiddlewareFunctions();\n const isUnknownRoute = toState.name === constants.UNKNOWN_ROUTE;\n\n // State management functions\n // Issue #36: Check both explicit cancellation AND router shutdown\n // Issue #50: Use isActive() instead of isStarted() for two-phase start support\n // isActive() is true during initial start transition, isStarted() is false\n const isCancelled = () => cancelled || !router.isActive();\n\n const cancel = () => {\n if (!cancelled && !completed) {\n cancelled = true;\n complete(new RouterError(errorCodes.TRANSITION_CANCELLED));\n }\n };\n\n const complete = (err: RouterErrorType | undefined, state?: State) => {\n if (completed) {\n return;\n }\n\n completed = true;\n transitionCallback(err, state ?? toState);\n };\n\n // The main transaction logic\n const runTransition = (): void => {\n const { toDeactivate, toActivate } = getTransitionPath(toState, fromState);\n\n // determine the necessary steps\n const shouldDeactivate =\n fromState && !opts.forceDeactivate && toDeactivate.length > 0;\n const shouldActivate = !isUnknownRoute && toActivate.length > 0;\n const shouldRunMiddleware = middlewareFunctions.length > 0;\n\n // The chain of execution\n const runDeactivation = (callback: StrictDoneFn) => {\n if (shouldDeactivate) {\n executeLifecycleHooks(\n canDeactivateFunctions,\n toState,\n fromState,\n toDeactivate,\n errorCodes.CANNOT_DEACTIVATE,\n isCancelled,\n callback,\n );\n } else {\n callback(undefined, toState);\n }\n };\n\n const runActivation = (state: State, callback: StrictDoneFn) => {\n if (shouldActivate) {\n executeLifecycleHooks(\n canActivateFunctions,\n state,\n fromState,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n isCancelled,\n (err, newState) => {\n callback(err, newState);\n },\n );\n } else {\n // State is already frozen from makeState()\n callback(undefined, state);\n }\n };\n\n const runMiddleware = (state: State, callback: StrictDoneFn) => {\n if (shouldRunMiddleware) {\n executeMiddleware(\n middlewareFunctions,\n state,\n fromState,\n isCancelled,\n (err, newState) => {\n callback(err, newState);\n },\n );\n } else {\n // State is already frozen from makeState()\n callback(undefined, state);\n }\n };\n\n // perform a chain\n runDeactivation((err, state) => {\n if (err) {\n complete(err, state);\n\n return;\n }\n\n runActivation(state, (runActivationErr, runActivationState) => {\n if (runActivationErr) {\n complete(runActivationErr, runActivationState);\n\n return;\n }\n\n runMiddleware(\n runActivationState,\n (runMiddlewareErr, runMiddlewareState) => {\n if (runMiddlewareErr) {\n complete(runMiddlewareErr, runMiddlewareState);\n\n return;\n }\n\n // Automatic cleaning of inactive segments\n if (fromState) {\n const activeSegments = nameToIDs(toState.name);\n const previousActiveSegments = nameToIDs(fromState.name);\n const activeSet = new Set(activeSegments);\n\n for (const name of previousActiveSegments) {\n if (!activeSet.has(name) && canDeactivateFunctions.has(name)) {\n router.clearCanDeactivate(name);\n }\n }\n }\n\n complete(undefined, runMiddlewareState);\n },\n );\n });\n });\n };\n\n // Launch transition\n runTransition();\n\n return cancel;\n}\n","// packages/real-router/modules/core/navigation.ts\n\nimport { logger } from \"logger\";\nimport { getTypeDescription, isNavigationOptions } from \"type-guards\";\n\nimport { events, errorCodes, constants, RouterError } from \"@real-router/core\";\n\nimport { transition } from \"../transition\";\n\nimport type {\n CancelFn,\n DoneFn,\n NavigationOptions,\n Params,\n State,\n DefaultDependencies,\n Router,\n} from \"core-types\";\n\nconst noop = () => {};\n\n/**\n * Safely invokes a callback, catching and logging any errors.\n * Prevents user callback errors from crashing the router.\n *\n * @internal\n */\nfunction safeCallback(\n callback: DoneFn,\n ...args: [error?: RouterError, state?: State]\n): void {\n try {\n callback(...args);\n } catch (error) {\n logger.error(\"router.navigate\", \"Error in navigation callback:\", error);\n }\n}\n\n/**\n * Result of parsing polymorphic navigate() arguments.\n *\n * @internal\n */\ninterface ParsedNavigateArgs {\n params: Params;\n opts: NavigationOptions;\n callback: DoneFn;\n}\n\n/**\n * Parses the polymorphic arguments of navigate().\n *\n * Handles all valid call signatures:\n * - navigate(name, callback)\n * - navigate(name, params)\n * - navigate(name, params, callback)\n * - navigate(name, params, opts)\n * - navigate(name, params, opts, callback)\n *\n * @internal\n */\nfunction parseNavigateArgs(\n paramsOrDone?: Params | DoneFn,\n optsOrDone?: NavigationOptions | DoneFn,\n done?: DoneFn,\n): ParsedNavigateArgs {\n if (typeof paramsOrDone === \"function\") {\n // Form: navigate(name, callback)\n return { params: {}, opts: {}, callback: paramsOrDone };\n }\n\n // Forms: navigate(name), navigate(name, params), navigate(name, params, callback),\n // navigate(name, params, opts), navigate(name, params, opts, callback)\n // Also handles: navigate(name, null/undefined, callback) - runtime defense\n const params = paramsOrDone ?? {};\n\n if (typeof optsOrDone === \"function\") {\n return { params, opts: {}, callback: optsOrDone };\n }\n\n return {\n params,\n opts: optsOrDone ?? {},\n callback: done ?? noop,\n };\n}\n\nexport function withNavigation<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n let cancelCurrentTransition: CancelFn | null = null;\n let navigating = false;\n\n // Cancel of the previous transition\n const cancel = (): Router<Dependencies> => {\n if (cancelCurrentTransition) {\n cancelCurrentTransition();\n cancelCurrentTransition = null;\n }\n\n navigating = false;\n\n return router;\n };\n\n /**\n * Internal navigation function that accepts pre-built state\n *\n * @internal\n */\n const navigateToState = (\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n callback: DoneFn,\n emitSuccess: boolean,\n ): CancelFn => {\n // Warn about concurrent navigation (potential SSR race condition)\n if (navigating) {\n logger.warn(\n \"router.navigate\",\n \"Concurrent navigation detected on shared router instance. \" +\n \"For SSR, use router.clone() to create isolated instance per request.\",\n );\n }\n\n // Cancel previous transition\n cancel();\n\n // Set navigating flag BEFORE emitting TRANSITION_START\n // This ensures isNavigating() returns true during event handlers\n navigating = true;\n\n // Emit TRANSITION_START (after navigating flag is set)\n router.invokeEventListeners(events.TRANSITION_START, toState, fromState);\n\n // Create callback for transition\n const transitionCallback = (err: RouterError | undefined, state: State) => {\n navigating = false;\n cancelCurrentTransition = null;\n\n if (!err) {\n // Route was already validated in navigate() via buildState().\n // Since guards can no longer redirect (Issue #55), the state.name cannot change.\n // However, routes can be dynamically removed during async navigation,\n // so we do a lightweight check with hasRoute() instead of full buildState().\n // UNKNOWN_ROUTE is always valid (used for 404 handling).\n if (\n state.name === constants.UNKNOWN_ROUTE ||\n router.hasRoute(state.name)\n ) {\n router.setState(state);\n\n // Emit TRANSITION_SUCCESS only if requested\n if (emitSuccess) {\n router.invokeEventListeners(\n events.TRANSITION_SUCCESS,\n state,\n fromState,\n opts,\n );\n }\n\n // State is already frozen from transition module\n safeCallback(callback, undefined, state);\n } else {\n // Route was removed during async navigation\n const notFoundErr = new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: state.name,\n });\n\n safeCallback(callback, notFoundErr);\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n router.getState(),\n notFoundErr,\n );\n }\n\n return;\n }\n\n // Error handling\n if (err.code === errorCodes.TRANSITION_CANCELLED) {\n router.invokeEventListeners(\n events.TRANSITION_CANCEL,\n toState,\n fromState,\n );\n } else {\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n toState,\n fromState,\n err,\n );\n }\n\n safeCallback(callback, err);\n };\n\n // Launch transition\n cancelCurrentTransition = transition(\n router,\n toState,\n fromState,\n opts,\n transitionCallback,\n );\n\n return cancelCurrentTransition;\n };\n\n router.navigate = function navigate(\n name: string,\n paramsOrDone?: Params | DoneFn,\n optsOrDone?: NavigationOptions | DoneFn,\n done?: DoneFn,\n ): CancelFn {\n // Parse polymorphic arguments first (needed for callback in error case)\n const { params, opts, callback } = parseNavigateArgs(\n paramsOrDone,\n optsOrDone,\n done,\n );\n\n // Quick check of the state of the router\n if (!router.isStarted()) {\n const err = new RouterError(errorCodes.ROUTER_NOT_STARTED);\n\n safeCallback(callback, err);\n\n return noop;\n }\n\n // Validate opts after polymorphic argument resolution\n // Note: Empty object {} is valid, but invalid types/fields are rejected\n if (!isNavigationOptions(opts)) {\n throw new TypeError(\n `[router.navigate] Invalid options: ${getTypeDescription(opts)}. Expected NavigationOptions object.`,\n );\n }\n\n // build route state with segments (avoids duplicate getSegmentsByName call)\n const result = router.buildStateWithSegments(name, params);\n\n if (!result) {\n const err = new RouterError(errorCodes.ROUTE_NOT_FOUND);\n\n safeCallback(callback, err);\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n router.getState(),\n err,\n );\n\n return noop;\n }\n\n const { state: route, segments } = result;\n\n // create a target state\n // Use buildPathWithSegments to avoid duplicate getSegmentsByName in buildPath\n const toState = router.makeState(\n route.name,\n route.params,\n router.buildPathWithSegments(route.name, route.params, segments),\n {\n params: route.meta,\n options: opts,\n redirected: opts.redirected ?? false,\n },\n );\n\n // Early return for skipTransition - no state equality check needed\n // eslint-disable-next-line @typescript-eslint/no-deprecated,sonarjs/deprecation\n if (opts.skipTransition) {\n // toState is already frozen from makeState()\n safeCallback(callback, undefined, toState);\n\n return noop;\n }\n\n const fromState = router.getState();\n\n // Fast verification for the same states\n if (\n !opts.reload &&\n !opts.force &&\n router.areStatesEqual(fromState, toState, false)\n ) {\n const err = new RouterError(errorCodes.SAME_STATES);\n\n safeCallback(callback, err);\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n toState,\n fromState,\n err,\n );\n\n return noop;\n }\n\n // transition execution with TRANSITION_SUCCESS emission\n // Use router.navigateToState instead of local variable to allow mocking in tests\n // Note: Guards cannot redirect - redirects are handled in middleware only\n return router.navigateToState(toState, fromState, opts, callback, true); // emitSuccess = true for public navigate()\n };\n\n router.navigateToDefault = function navigateToDefault(\n optsOrDone?: NavigationOptions | DoneFn,\n done?: DoneFn,\n ): CancelFn {\n const options = router.getOptions();\n\n if (!options.defaultRoute) {\n return noop;\n }\n\n let opts: NavigationOptions = {};\n let callback: DoneFn = noop;\n\n if (typeof optsOrDone === \"function\") {\n callback = optsOrDone;\n } else if (optsOrDone) {\n opts = optsOrDone;\n callback = done ?? noop;\n }\n\n // Validate opts for better error messages (specific to navigateToDefault)\n if (!isNavigationOptions(opts)) {\n throw new TypeError(\n `[router.navigateToDefault] Invalid options: ${getTypeDescription(opts)}. Expected NavigationOptions object.`,\n );\n }\n\n return router.navigate(\n options.defaultRoute,\n options.defaultParams,\n opts,\n callback,\n );\n };\n\n // Expose internal navigation for use by plugins and lifecycle\n router.navigateToState = navigateToState;\n\n /**\n * Checks if a navigation transition is currently in progress.\n *\n * @returns true if navigation is active, false otherwise\n *\n * @example\n * if (router.isNavigating()) {\n * console.log('Navigation in progress...');\n * }\n *\n * @remarks\n * After FSM migration (RFC-2), this will be replaced with:\n * `router.getRouterState() === RouterState.TRANSITIONING`\n */\n router.isNavigating = (): boolean => router.isStarted() && navigating;\n\n return router;\n}\n","// packages/real-router/modules/core/observable.ts\n\nimport { logger } from \"logger\";\nimport { isNavigationOptions, isState } from \"type-guards\";\n\nimport { events, RouterError } from \"@real-router/core\";\n\nimport type { plugins } from \"../constants\";\nimport type {\n DefaultDependencies,\n EventName,\n EventsKeys,\n NavigationOptions,\n Plugin,\n Router,\n RouterError as RouterErrorType,\n State,\n SubscribeFn,\n Unsubscribe,\n} from \"core-types\";\n\n/**\n * Symbol.observable polyfill declaration for TC39 proposal\n *\n * @see https://github.com/tc39/proposal-observable\n */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: unique symbol;\n }\n}\n\ntype EventMethodMap = {\n [K in EventsKeys as (typeof events)[K]]: (typeof plugins)[K];\n};\n\n/**\n * Max recursion depth to prevent stack overflow from circular event triggers\n */\nconst MAX_EVENT_DEPTH = 5;\n\n/**\n * Hard limit to prevent memory leaks from exponential listener creation\n */\nconst MAX_LISTENERS_HARD_LIMIT = 10_000;\n\n/**\n * Invoke all listeners for a given event.\n *\n * @template E - Event literal type.\n * @param eventName - The event being dispatched (used only for logging).\n * @param set - Array of callbacks (or undefined).\n * @param args - Arguments to pass to each callback.\n */\nfunction invokeFor<E extends EventName>(\n eventName: E,\n set: Set<Plugin[EventMethodMap[E]]>,\n ...args: Parameters<NonNullable<Plugin[EventMethodMap[E]]>>\n): void {\n if (set.size === 0) {\n return;\n }\n\n // Clone the listeners array so that removals/additions\n // during iteration won't affect this loop.\n const listeners = [...set];\n\n for (const cb of listeners) {\n // Note: cb is guaranteed to be a function because addEventListener\n // validates typeof cb === \"function\" before adding to the set\n try {\n // We can't use cb(...args) due to TypeScript limitations with\n // conditional types, so we use this pattern to invoke the callback\n // with the correct number of arguments from the args array\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- Function.prototype.apply requires Function type\n Function.prototype.apply.call(cb as Function, undefined, args);\n } catch (error) {\n logger.error(\"Router\", `Error in listener for ${eventName}:`, error);\n }\n }\n}\n\nexport function withObservability<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n /**\n * Event listeners storage. Using Set for O(1) operations and automatic deduplication.\n * Sets are created lazily to reduce memory footprint when events are not used.\n *\n * Type-safe lazy map that preserves the relationship between event names and their callback types.\n */\n type CallbackSet<E extends EventName> = Set<Plugin[EventMethodMap[E]]>;\n type CallbacksMap = {\n [E in EventName]?: CallbackSet<E>;\n };\n const callbacks: CallbacksMap = {};\n\n /**\n * Gets or creates a Set for the given event name (lazy initialization)\n */\n function getCallbackSet<E extends EventName>(eventName: E): CallbackSet<E> {\n const existing = callbacks[eventName];\n\n if (existing) {\n return existing;\n }\n\n const set = new Set<Plugin[EventMethodMap[E]]>();\n\n // Type assertion needed: TS can't narrow generic E to specific event name\n (callbacks as Record<E, CallbackSet<E>>)[eventName] = set;\n\n return set;\n }\n\n /**\n * Tracks current recursion depth for each event type.\n * Created lazily to reduce memory footprint when events are not dispatched.\n */\n let eventDepthMap: Record<EventName, number> | null = null;\n\n /**\n * Gets or creates the event depth map (lazy initialization)\n */\n const getEventDepthMap = (): Record<EventName, number> => {\n eventDepthMap ??= {\n [events.ROUTER_START]: 0,\n [events.TRANSITION_START]: 0,\n [events.TRANSITION_SUCCESS]: 0,\n [events.TRANSITION_ERROR]: 0,\n [events.TRANSITION_CANCEL]: 0,\n [events.ROUTER_STOP]: 0,\n };\n\n return eventDepthMap;\n };\n\n /**\n * Valid event names for validation (avoids creating objects just for hasOwn check)\n */\n const validEventNames = new Set<EventName>([\n events.ROUTER_START,\n events.TRANSITION_START,\n events.TRANSITION_SUCCESS,\n events.TRANSITION_ERROR,\n events.TRANSITION_CANCEL,\n events.ROUTER_STOP,\n ]);\n\n /**\n * Validates arguments for invokeEventListeners to prevent runtime errors.\n * Checks event name validity, recursion depth, and parameter types.\n * Throws descriptive errors for debugging instead of silent failures.\n */\n const isInvokeEventListenersArgumentsValid = (\n eventName: (typeof events)[EventsKeys],\n ) => {\n if (!validEventNames.has(eventName)) {\n throw new Error(`Invalid event name: ${eventName}`);\n }\n\n const depthMap = getEventDepthMap();\n const depth = depthMap[eventName];\n\n if (depth >= MAX_EVENT_DEPTH) {\n throw new Error(\n `[Router] Maximum recursion depth (${MAX_EVENT_DEPTH}) exceeded for event: ${eventName}`,\n );\n }\n };\n\n /**\n * Validates arguments for add/removeEventListener operations.\n * Ensures event name is valid and callback is a function.\n * Critical for preventing invalid subscriptions that could cause memory leaks.\n */\n const isAddRemoveEventListenersArgumentsValid = <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => {\n if (!validEventNames.has(eventName)) {\n throw new Error(`Invalid event name: ${eventName}`);\n }\n\n if (typeof cb !== \"function\") {\n throw new TypeError(\n `Expected callback to be a function for event ${eventName}`,\n );\n }\n };\n\n /**\n * @internal Central event dispatcher for router core\n * * Uses only for navigate method.\n */\n router.invokeEventListeners = (\n eventName: (typeof events)[EventsKeys],\n toState?: State,\n fromState?: State,\n arg?: RouterErrorType | NavigationOptions,\n // eslint-disable-next-line sonarjs/cognitive-complexity\n ) => {\n isInvokeEventListenersArgumentsValid(eventName);\n\n const depthMap = getEventDepthMap();\n\n try {\n depthMap[eventName]++;\n\n switch (eventName) {\n case events.TRANSITION_START:\n case events.TRANSITION_CANCEL: {\n if (!toState) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is required for event \"${eventName}\"`,\n );\n }\n\n // TODO(private-api): Remove isState() validation when method becomes protected.\n // All internal callers pass states from makeState() (already validated) or getState().\n // Potential savings: ~56-877 ns per call (depends on params depth)\n if (!isState(toState)) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // TODO(private-api): Remove when method becomes protected (fromState from getState())\n if (fromState && !isState(fromState)) {\n throw new TypeError(\n `[router.invokeEventListeners] fromState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // States are already frozen: toState from makeState(), fromState from getState()\n // Use getCallbackSet for lazy initialization\n invokeFor(eventName, getCallbackSet(eventName), toState, fromState);\n\n break;\n }\n case events.TRANSITION_ERROR: {\n // TODO(private-api): Remove isState() validations when method becomes protected.\n // States come from makeState() or getState() - already validated.\n if (toState && !isState(toState)) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // TODO(private-api): Remove when method becomes protected\n if (fromState && !isState(fromState)) {\n throw new TypeError(\n `[router.invokeEventListeners] fromState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n if (!arg) {\n throw new TypeError(\n `[router.invokeEventListeners] error is required for event \"${eventName}\"`,\n );\n }\n\n if (!(arg instanceof RouterError)) {\n throw new TypeError(\n `[router.invokeEventListeners] error must be a RouterError instance for event \"${eventName}\". ` +\n `Got: ${typeof arg === \"object\" ? arg.constructor.name : typeof arg}`,\n );\n }\n\n // States are already frozen if provided: toState from makeState(), fromState from getState()\n // Use getCallbackSet for lazy initialization\n invokeFor(\n eventName,\n getCallbackSet(eventName),\n toState,\n fromState,\n arg,\n );\n\n break;\n }\n case events.TRANSITION_SUCCESS: {\n if (!toState) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is required for event \"${eventName}\"`,\n );\n }\n\n // TODO(private-api): Remove isState() validations when method becomes protected.\n // States come from makeState() or getState() - already validated.\n if (!isState(toState)) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // TODO(private-api): Remove when method becomes protected\n if (fromState && !isState(fromState)) {\n throw new TypeError(\n `[router.invokeEventListeners] fromState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n if (!arg) {\n throw new TypeError(\n `[router.invokeEventListeners] options is required for event \"${eventName}\"`,\n );\n }\n\n if (arg instanceof RouterError) {\n throw new TypeError(\n `[router.invokeEventListeners] options cannot be a RouterError for event \"${eventName}\". ` +\n `Use TRANSITION_ERROR event for errors.`,\n );\n }\n\n if (!isNavigationOptions(arg)) {\n throw new TypeError(\n `[router.invokeEventListeners] options is invalid for event \"${eventName}\". ` +\n `Expected NavigationOptions object.`,\n );\n }\n\n // States are already frozen: toState from makeState(), fromState from getState()\n // Use getCallbackSet for lazy initialization\n invokeFor(\n eventName,\n getCallbackSet(eventName),\n toState,\n fromState,\n arg,\n );\n\n break;\n }\n // for events.ROUTER_START, events.ROUTER_STOP\n default: {\n // Exhaustive check: at this point only ROUTER_START and ROUTER_STOP should remain\n // TypeScript will error if new event types are added without handling them above\n const _exhaustiveCheck:\n | typeof events.ROUTER_START\n | typeof events.ROUTER_STOP = eventName;\n\n // Use getCallbackSet for lazy initialization\n invokeFor(_exhaustiveCheck, getCallbackSet(_exhaustiveCheck));\n\n break;\n }\n }\n } finally {\n depthMap[eventName]--;\n }\n };\n\n /**\n * Checks if there are any listeners registered for a given event.\n * Used for performance optimization to skip event emission when no listeners exist.\n *\n * @param eventName - The event to check for listeners\n * @returns true if at least one listener is registered, false otherwise\n *\n * @example\n * ```typescript\n * // Skip expensive event emission if no listeners\n * if (router.hasListeners(events.TRANSITION_ERROR)) {\n * router.invokeEventListeners(events.TRANSITION_ERROR, ...);\n * }\n * ```\n *\n * @internal\n */\n router.hasListeners = (eventName: (typeof events)[EventsKeys]): boolean => {\n if (!validEventNames.has(eventName)) {\n return false;\n }\n\n const set = callbacks[eventName];\n\n return set !== undefined && set.size > 0;\n };\n\n /**\n * @internal Use unsubscribe function returned by addEventListener\n * Uses only for plugins.\n * @deprecated Will be protected in next major version\n */\n router.removeEventListener = <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => {\n isAddRemoveEventListenersArgumentsValid(eventName, cb);\n\n // Don't create Set just for removal - check if it exists first\n const set = callbacks[eventName];\n\n if (!set || set.size === 0) {\n return;\n }\n\n const deleted = set.delete(cb);\n\n if (!deleted) {\n // Need for debugging purposes, as it is not an error to remove a listener that was never added.\n // This can happen if the listener was already removed or never added.\n logger.warn(\n \"Router\",\n `Attempted to remove non-existent listener for \"${eventName}\". ` +\n `This might indicate a memory leak or incorrect cleanup logic.`,\n );\n }\n };\n\n router.addEventListener = <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ): Unsubscribe => {\n isAddRemoveEventListenersArgumentsValid(eventName, cb);\n\n const set = getCallbackSet(eventName);\n\n if (set.has(cb)) {\n throw new Error(\n `[router.addEventListener] Listener already exists for event \"${eventName}\". ` +\n `Each listener function can only be registered once per event. ` +\n `Store the returned unsubscribe function to remove the listener.`,\n );\n }\n\n if (set.size === 1000) {\n logger.warn(\n \"router.addEventListener\",\n `Warning: Event \"${eventName}\" has ${set.size} listeners. ` +\n `This might indicate a memory leak.`,\n );\n }\n\n if (set.size >= MAX_LISTENERS_HARD_LIMIT) {\n throw new Error(\n `[router.addEventListener] Maximum listener limit (${MAX_LISTENERS_HARD_LIMIT}) ` +\n `reached for event \"${eventName}\". ` +\n `This is a critical memory leak. The application is creating listeners ` +\n `exponentially. Check for loops or recursive calls that register listeners.`,\n );\n }\n\n set.add(cb);\n\n return () => {\n router.removeEventListener(eventName, cb);\n };\n };\n\n /**\n * Simple subscription API for navigation success events\n */\n function subscribe(listener: SubscribeFn): Unsubscribe {\n if (typeof listener !== \"function\") {\n throw new TypeError(\n \"[router.subscribe] Expected a function. \" +\n \"For Observable pattern use router[Symbol.observable]().subscribe(observer)\",\n );\n }\n\n return router.addEventListener(\n events.TRANSITION_SUCCESS,\n (toState: State, fromState?: State) => {\n // States are already frozen: toState from makeState(), fromState from getState()\n listener({\n route: toState,\n previousRoute: fromState,\n });\n },\n );\n }\n\n router.subscribe = subscribe;\n\n /**\n * Observable symbol - TC39 proposal with fallback\n * Runtime check needed despite type declaration because Symbol.observable\n * is not yet standard in all environments\n *\n * @see https://github.com/tc39/proposal-observable\n */\n const $$observable: typeof Symbol.observable =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime check for environments without Symbol.observable\n (typeof Symbol === \"function\" && Symbol.observable) ||\n (\"@@observable\" as unknown as typeof Symbol.observable);\n\n /**\n * Track active observers for deduplication\n * Using WeakMap to allow garbage collection of observers\n */\n const observerSubscriptions = new WeakMap<\n Observer,\n { unsubscribe: Unsubscribe; active: boolean }\n >();\n\n /**\n * Observer interface per Observable spec\n */\n interface Observer {\n next?: (value: SubscribeState) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n }\n\n /**\n * Subscription interface per Observable spec\n */\n interface Subscription {\n unsubscribe: () => void;\n readonly closed: boolean;\n }\n\n /**\n * Observable options for enhanced control\n */\n interface ObservableOptions {\n /** AbortSignal for automatic unsubscription */\n signal?: AbortSignal;\n /** Replay current state to new subscribers (default: true) */\n replay?: boolean;\n }\n\n interface SubscribeState {\n route: State;\n previousRoute: State | undefined;\n }\n\n /**\n * Observable interface for TC39 compliance\n */\n interface RouterObservable {\n [key: symbol]: () => RouterObservable;\n subscribe: (\n observer: Observer | ((value: SubscribeState) => void),\n options?: ObservableOptions,\n ) => Subscription;\n }\n\n /**\n * Modern Observable implementation with:\n * - Deduplication: same observer can only subscribe once\n * - Error isolation: errors in one observer don't affect others\n * - Replay: new subscribers receive current state immediately\n * - AbortSignal: automatic cleanup with AbortController\n * - TC39 Observable spec compliance\n */\n function observable(): RouterObservable {\n return {\n /**\n * Subscribe to router state changes\n *\n * @example\n * // Basic subscription\n * const subscription = router[Symbol.observable]().subscribe({\n * next: ({ route, previousRoute }) => console.log(route.name)\n * });\n *\n * @example\n * // With AbortController\n * const controller = new AbortController();\n * router[Symbol.observable]().subscribe(\n * { next: ({ route }) => console.log(route) },\n * { signal: controller.signal }\n * );\n * // Later: controller.abort();\n */\n subscribe(\n observer: Observer | ((value: SubscribeState) => void),\n options: ObservableOptions = {},\n ): Subscription {\n // Normalize observer\n const normalizedObserver: Observer =\n typeof observer === \"function\" ? { next: observer } : observer;\n\n // Check for duplicate subscription\n const existing = observerSubscriptions.get(normalizedObserver);\n\n if (existing?.active) {\n logger.warn(\n \"router.observable\",\n \"Duplicate subscription prevented. Same observer already subscribed.\",\n );\n\n return {\n unsubscribe: existing.unsubscribe,\n get closed() {\n return !existing.active;\n },\n };\n }\n\n const { signal, replay = true } = options;\n\n // Check if already aborted\n if (signal?.aborted) {\n return {\n unsubscribe: () => {},\n closed: true,\n };\n }\n\n let closed = false;\n\n // Create safe invoker with error isolation\n const safeNext = (value: SubscribeState) => {\n if (closed) {\n return;\n }\n\n if (normalizedObserver.next) {\n try {\n normalizedObserver.next(value);\n } catch (error) {\n logger.error(\n \"router.observable\",\n \"Error in observer.next:\",\n error,\n );\n\n // Call error handler if provided\n if (normalizedObserver.error) {\n try {\n normalizedObserver.error(error);\n } catch (errorHandlerError) {\n logger.error(\n \"router.observable\",\n \"Error in observer.error:\",\n errorHandlerError,\n );\n }\n }\n }\n }\n };\n\n // Internal event listener\n const eventListener = (toState: State, fromState?: State) => {\n safeNext({\n route: toState,\n previousRoute: fromState,\n });\n };\n\n // Subscribe to transition success events\n const unsubscribeListener = router.addEventListener(\n events.TRANSITION_SUCCESS,\n eventListener,\n );\n\n // Create subscription object\n const subscription: { unsubscribe: Unsubscribe; active: boolean } = {\n unsubscribe: () => {\n if (closed) {\n return;\n }\n\n closed = true;\n subscription.active = false;\n unsubscribeListener();\n\n // Call complete handler\n if (normalizedObserver.complete) {\n try {\n normalizedObserver.complete();\n } catch (error) {\n logger.error(\n \"router.observable\",\n \"Error in observer.complete:\",\n error,\n );\n }\n }\n },\n active: true,\n };\n\n // Track subscription for deduplication\n observerSubscriptions.set(normalizedObserver, subscription);\n\n // Handle AbortSignal\n if (signal) {\n const abortHandler = () => {\n subscription.unsubscribe();\n };\n\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n // Replay current state if requested and available\n if (replay) {\n const currentState = router.getState();\n\n if (currentState) {\n // Use queueMicrotask for async replay to match Observable semantics\n queueMicrotask(() => {\n safeNext({\n route: currentState,\n previousRoute: undefined,\n });\n });\n }\n }\n\n return {\n unsubscribe: subscription.unsubscribe,\n get closed() {\n return closed;\n },\n };\n },\n\n /**\n * Observable symbol for interop with RxJS and other libraries\n */\n [$$observable](): RouterObservable {\n return this;\n },\n };\n }\n\n // Attach observable to router\n router[$$observable] = observable;\n\n return router;\n}\n","// packages/real-router/modules/core/options.ts\n\nimport { isObjKey, isString } from \"type-guards\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type { DefaultDependencies, Options, Router } from \"core-types\";\n\nconst defaultOptions: Options = {\n defaultRoute: \"\",\n defaultParams: {},\n trailingSlash: \"preserve\",\n queryParamsMode: \"loose\",\n queryParams: {\n arrayFormat: \"none\",\n booleanFormat: \"none\",\n nullFormat: \"default\",\n },\n caseSensitive: false,\n urlParamsEncoding: \"default\",\n allowNotFound: true,\n rewritePathOnMatch: true,\n} satisfies Options;\n\n/**\n * Valid values for string enum options.\n * Used for runtime validation in setOption/withOptions.\n */\nconst VALID_OPTION_VALUES = {\n trailingSlash: [\"strict\", \"never\", \"always\", \"preserve\"] as const,\n queryParamsMode: [\"default\", \"strict\", \"loose\"] as const,\n urlParamsEncoding: [\"default\", \"uri\", \"uriComponent\", \"none\"] as const,\n} as const;\n\n/**\n * Valid keys and values for queryParams option.\n */\nconst VALID_QUERY_PARAMS = {\n arrayFormat: [\"none\", \"brackets\", \"index\", \"comma\"] as const,\n booleanFormat: [\"none\", \"string\", \"empty-true\"] as const,\n nullFormat: [\"default\", \"hidden\"] as const,\n} as const;\n\nconst optionNotFoundError = (method: string, name: keyof Options) =>\n new ReferenceError(`[router.${method}]: option \"${name}\" not found`);\n\n/**\n * Validates that value is a plain object without getters.\n */\nfunction validatePlainObject(\n value: unknown,\n optionName: string,\n methodName: string,\n): asserts value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || value.constructor !== Object) {\n throw new TypeError(\n `[router.${methodName}] Invalid type for \"${optionName}\": ` +\n `expected plain object, got ${getTypeDescription(value)}`,\n );\n }\n\n // Getters can throw, return different values, or have side effects\n for (const key in value) {\n if (Object.getOwnPropertyDescriptor(value, key)?.get) {\n throw new TypeError(\n `[router.${methodName}] Getters not allowed in \"${optionName}\": \"${key}\"`,\n );\n }\n }\n}\n\n/**\n * Validates queryParams keys and values against allowed enums.\n */\nfunction validateQueryParams(\n value: Record<string, unknown>,\n methodName: string,\n): void {\n for (const key in value) {\n if (!isObjKey(key, VALID_QUERY_PARAMS)) {\n const validKeys = Object.keys(VALID_QUERY_PARAMS)\n .map((k) => `\"${k}\"`)\n .join(\", \");\n\n throw new TypeError(\n `[router.${methodName}] Unknown queryParams key: \"${key}\". ` +\n `Valid keys: ${validKeys}`,\n );\n }\n\n const paramValue = value[key];\n const validValues = VALID_QUERY_PARAMS[key];\n const isValid = (validValues as readonly string[]).includes(\n paramValue as string,\n );\n\n if (!isValid) {\n const allowedValues = validValues.map((v) => `\"${v}\"`).join(\", \");\n\n throw new TypeError(\n `[router.${methodName}] Invalid value for queryParams.${key}: ` +\n `expected one of ${allowedValues}, got \"${String(paramValue)}\"`,\n );\n }\n }\n}\n\n/**\n * Validates string enum options against allowed values.\n */\nfunction validateEnumOption(\n optionName: keyof typeof VALID_OPTION_VALUES,\n value: unknown,\n methodName: string,\n): void {\n const validValues = VALID_OPTION_VALUES[optionName];\n const isValid = (validValues as readonly string[]).includes(value as string);\n\n if (!isValid) {\n const allowedValues = validValues.map((v) => `\"${v}\"`).join(\", \");\n\n throw new TypeError(\n `[router.${methodName}] Invalid value for \"${optionName}\": ` +\n `expected one of ${allowedValues}, got \"${String(value)}\"`,\n );\n }\n}\n\nfunction validateOptionValue<K extends keyof Options>(\n optionName: K,\n value: unknown,\n expectedValue: Options[K],\n methodName: string,\n): void {\n // For object options - ensure plain objects only (not null, arrays, Date, etc)\n if (expectedValue && typeof expectedValue === \"object\") {\n validatePlainObject(value, optionName, methodName);\n\n if (optionName === \"queryParams\") {\n validateQueryParams(value, methodName);\n }\n\n return;\n }\n\n // For primitives - typeof check first\n if (typeof value !== typeof expectedValue) {\n throw new TypeError(\n `[router.${methodName}] Invalid type for \"${optionName}\": ` +\n `expected ${typeof expectedValue}, got ${typeof value}`,\n );\n }\n\n // For string enum options - validate against allowed values\n if (optionName in VALID_OPTION_VALUES) {\n validateEnumOption(\n optionName as keyof typeof VALID_OPTION_VALUES,\n value,\n methodName,\n );\n }\n}\n\n// =============================================================================\n// Deep Freeze Helper\n// =============================================================================\n// Options contains nested objects (queryParams, defaultParams) that need\n// to be frozen recursively to prevent mutation via nested access:\n// router.getOptions().queryParams.arrayFormat = \"brackets\" // Should throw!\n// =============================================================================\n\n/**\n * Recursively freezes an object and all nested objects.\n * Only freezes plain objects, not primitives or special objects.\n */\nfunction deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze the object itself\n Object.freeze(obj);\n\n // Recursively freeze nested plain objects\n for (const key of Object.keys(obj)) {\n const value = (obj as Record<string, unknown>)[key];\n\n // Only freeze plain objects (not null, arrays, Date, etc.)\n if (value && typeof value === \"object\" && value.constructor === Object) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\nexport function withOptions<Dependencies extends DefaultDependencies>(\n options: Partial<Options>,\n): (router: Router<Dependencies>) => Router<Dependencies> {\n return (router: Router<Dependencies>): Router<Dependencies> => {\n // Validate options on initialization\n for (const [key, value] of Object.entries(options)) {\n if (!isObjKey(key, defaultOptions)) {\n throw new TypeError(`[router.options] Unknown option: \"${key}\"`);\n }\n\n // Skip undefined values for conditional configuration\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (value === undefined) {\n continue;\n }\n\n validateOptionValue(key, value, defaultOptions[key], \"withOptions\");\n }\n\n // ==========================================================================\n // Performance Optimization: Frozen Options\n // ==========================================================================\n // Instead of creating a copy on every getOptions() call, we freeze the\n // options object once and return the same reference.\n //\n // Trade-off:\n // - getOptions(): O(n) copy → O(1) reference return\n // - setOption(): O(1) mutation → O(n) object recreation\n //\n // This is beneficial because getOptions() is called frequently (every\n // start(), navigate()), while setOption() is called rarely (initialization).\n // ==========================================================================\n\n let frozenOptions: Readonly<Options> = deepFreeze({\n ...defaultOptions,\n ...options,\n });\n\n // Return frozen reference directly - no copy needed!\n // Mutations will throw TypeError in strict mode\n router.getOptions = () => frozenOptions;\n\n router.setOption = <K extends keyof Options>(\n optionName: K,\n value: Options[K],\n ): Router<Dependencies> => {\n // Validate optionName is a string (TypeScript can be bypassed at runtime)\n if (!isString(optionName)) {\n throw new TypeError(\n `[router.setOption]: option name must be a string, got ${typeof optionName}`,\n );\n }\n\n // Options cannot be changed after router starts, except defaultRoute/defaultParams\n if (\n router.isStarted() &&\n optionName !== \"defaultRoute\" &&\n optionName !== \"defaultParams\"\n ) {\n throw new Error(\n `[router.setOption] Options cannot be changed after router.start(). ` +\n `Only defaultRoute/defaultParams can be changed after start.`,\n );\n }\n\n // Use Object.hasOwn to reject prototype keys like __proto__\n if (!Object.hasOwn(frozenOptions, optionName)) {\n throw optionNotFoundError(\"setOption\", optionName);\n }\n\n validateOptionValue(\n optionName,\n value,\n defaultOptions[optionName],\n \"setOption\",\n );\n\n // Recreate frozen options with new value\n // For nested objects (defaultParams), create a shallow copy to avoid\n // sharing mutable references\n const newValue =\n value && typeof value === \"object\" && value.constructor === Object\n ? { ...value }\n : value;\n\n frozenOptions = deepFreeze({\n ...frozenOptions,\n [optionName]: newValue,\n });\n\n return router;\n };\n\n return router;\n };\n}\n","// packages/real-router/modules/core/plugins.ts\n\nimport { logger } from \"logger\";\nimport { isObjKey } from \"type-guards\";\n\nimport { events as EVENTS_CONST, plugins as PLUGINS_CONST } from \"../constants\";\nimport { getTypeDescription } from \"../helpers\";\n\nimport type {\n EventName,\n Unsubscribe,\n Router,\n Plugin,\n PluginFactory,\n DefaultDependencies,\n} from \"core-types\";\n\ntype EventMappingType = Record<\n (typeof PLUGINS_CONST)[keyof typeof PLUGINS_CONST],\n EventName\n>;\n\nconst LOGGER_CONTEXT_FOR_PLUGINS = \"router.usePlugin\";\n\nconst eventsMap = {\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_ERROR]: EVENTS_CONST.TRANSITION_ERROR,\n [PLUGINS_CONST.TRANSITION_CANCEL]: EVENTS_CONST.TRANSITION_CANCEL,\n} as const satisfies EventMappingType;\n\nconst EVENT_METHOD_NAMES = Object.keys(eventsMap).filter(\n (eventName): eventName is keyof typeof eventsMap =>\n isObjKey<typeof eventsMap>(eventName, eventsMap),\n);\n\nconst PLUGIN_LIMITS = {\n WARN: 10,\n ERROR: 25,\n HARD_LIMIT: 50,\n};\n\nconst validatePluginsSize = (\n newPluginsSize: number,\n registeredPluginsSize: number,\n) => {\n // Check total size BEFORE initialization to fail fast\n const newSize = newPluginsSize + registeredPluginsSize;\n\n // Hard limit: more than 50 plugins indicates architectural problem\n if (newSize > PLUGIN_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.usePlugin] Plugin limit exceeded (${PLUGIN_LIMITS.HARD_LIMIT})`,\n );\n }\n\n // Graduated warnings for early problem detection\n if (newSize >= PLUGIN_LIMITS.ERROR) {\n logger.error(LOGGER_CONTEXT_FOR_PLUGINS, `${newSize} plugins registered!`);\n } else if (newSize >= PLUGIN_LIMITS.WARN) {\n logger.warn(LOGGER_CONTEXT_FOR_PLUGINS, `${newSize} plugins registered`);\n }\n};\n\nconst validateAppliedPlugin = (plugin: Plugin) => {\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 ${getTypeDescription(\n plugin,\n )}`,\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 for (const key in plugin) {\n if (!(key === \"teardown\" || isObjKey<typeof eventsMap>(key, eventsMap))) {\n throw new TypeError(\n `[router.usePlugin] Unknown property '${key}'. ` +\n `Plugin must only contain event handlers and optional teardown.`,\n );\n }\n }\n};\n\n/**\n * Validates plugin batch and returns deduplicated set.\n * Throws if any plugin is invalid or already registered.\n */\nfunction validatePluginBatch<Dependencies extends DefaultDependencies>(\n plugins: PluginFactory<Dependencies>[],\n registeredPlugins: Set<PluginFactory<Dependencies>>,\n): Set<PluginFactory<Dependencies>> {\n const seenInBatch = new Set<PluginFactory<Dependencies>>();\n\n for (const plugin of plugins) {\n if (typeof plugin !== \"function\") {\n throw new TypeError(\n `[router.usePlugin] Expected plugin factory function, got ${typeof plugin}`,\n );\n }\n\n if (registeredPlugins.has(plugin)) {\n throw new Error(\n `[router.usePlugin] Plugin factory already registered. ` +\n `To re-register, first unsubscribe the existing plugin.`,\n );\n }\n\n if (seenInBatch.has(plugin)) {\n logger.warn(\n LOGGER_CONTEXT_FOR_PLUGINS,\n \"Duplicate factory in batch, will be registered once\",\n );\n } else {\n seenInBatch.add(plugin);\n }\n }\n\n return seenInBatch;\n}\n\nexport function withPlugins<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): Router<Dependencies> {\n const routerPlugins = new Set<PluginFactory<Dependencies>>();\n\n /**\n * Returns registered plugin factories\n *\n * @internal Used by router.clone(). Will be removed from public API.\n * @deprecated Use behavior testing instead of checking internal state\n */\n router.getPlugins = (): PluginFactory<Dependencies>[] => [...routerPlugins];\n\n /**\n * Registers one or more plugins in the router\n * Plugins can subscribe to router lifecycle events\n *\n * @returns Unsubscribe function that removes all added plugins\n */\n router.usePlugin = (\n ...plugins: PluginFactory<Dependencies>[]\n ): Unsubscribe => {\n // Prevent exceeding plugin limit (50 max)\n validatePluginsSize(plugins.length, routerPlugins.size);\n\n // Validate ALL plugins before any state changes (atomicity)\n const seenInBatch = validatePluginBatch(plugins, routerPlugins);\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 = 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 logger.error(\n LOGGER_CONTEXT_FOR_PLUGINS,\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 routerPlugins.add(factory);\n }\n\n // Return unsubscribe function - each call manages only its own plugins\n let unsubscribed = false;\n\n return () => {\n if (unsubscribed) {\n return;\n }\n\n unsubscribed = true;\n\n // Remove only plugins added in THIS call\n for (const { factory } of initializedPlugins) {\n routerPlugins.delete(factory);\n }\n\n // Cleanup all plugins from this call\n for (const { cleanup } of initializedPlugins) {\n try {\n cleanup();\n } catch (error) {\n logger.error(\n LOGGER_CONTEXT_FOR_PLUGINS,\n \"Error during cleanup:\",\n error,\n );\n }\n }\n };\n };\n\n /**\n * Initializes a single plugin and subscribes it to router events\n *\n * @param pluginFactory - Factory function to create plugin\n * @returns Composite cleanup function that unsubscribes from all events\n */\n function startPlugin(\n pluginFactory: PluginFactory<Dependencies>,\n ): Unsubscribe {\n // Create plugin instance with router context\n const appliedPlugin = pluginFactory(router, router.getDependency);\n\n validateAppliedPlugin(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 router.addEventListener(\n eventsMap[methodName],\n appliedPlugin[methodName],\n ),\n );\n\n if (methodName === PLUGINS_CONST.ROUTER_START && router.isStarted()) {\n logger.warn(\n LOGGER_CONTEXT_FOR_PLUGINS,\n \"Router already started, onStart will not be called\",\n );\n }\n } else {\n logger.warn(\n LOGGER_CONTEXT_FOR_PLUGINS,\n `Property '${methodName}' is not a function, skipping`,\n );\n }\n }\n }\n\n // Return composite cleanup function\n return () => {\n // Unsubscribe from all events\n removeEventListeners.forEach((removeListener) => {\n removeListener();\n });\n\n // Call plugin's custom teardown if exists\n if (typeof appliedPlugin.teardown === \"function\") {\n appliedPlugin.teardown();\n }\n };\n }\n\n return router;\n}\n","// packages/real-router/modules/core/routeLifecycle.ts\n\nimport { logger } from \"logger\";\nimport { isBoolean, validateRouteName } from \"type-guards\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type {\n ActivationFn,\n ActivationFnFactory,\n DefaultDependencies,\n Router,\n} from \"core-types\";\n\n/**\n * Lifecycle handler registry limits to prevent memory leaks.\n * Higher limits than middleware since routes can be numerous.\n */\nconst LIFECYCLE_LIMITS = {\n WARN: 50, // Log warning - review route structure\n ERROR: 100, // Log error - too many routes with handlers\n HARD_LIMIT: 200, // Throw error - critical architectural issue\n} as const;\n\n/**\n * Validates that a handler is either a boolean or a factory function.\n *\n * @param handler - Value to validate\n * @param methodName - Calling method for error context\n * @throws {TypeError} If handler is not valid\n */\nfunction validateHandler<Dependencies extends DefaultDependencies>(\n handler: unknown,\n methodName: string,\n): asserts handler is ActivationFnFactory<Dependencies> | boolean {\n if (!isBoolean(handler) && typeof handler !== \"function\") {\n throw new TypeError(\n `[router.${methodName}] Handler must be a boolean or factory function, ` +\n `got ${getTypeDescription(handler)}`,\n );\n }\n}\n\n/**\n * Checks the total handler count and emits warnings based on thresholds.\n * Prevents memory leaks from excessive route handlers.\n *\n * @param currentSize - Current number of registered handlers\n * @param methodName - Calling method for error context\n * @throws {Error} If limit is exceeded\n */\nfunction checkHandlerCount(currentSize: number, methodName: string): void {\n if (currentSize >= LIFECYCLE_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.${methodName}] Lifecycle handler limit exceeded (${LIFECYCLE_LIMITS.HARD_LIMIT}). ` +\n `This indicates too many routes with individual handlers. ` +\n `Consider using middleware for cross-cutting concerns.`,\n );\n }\n\n if (currentSize >= LIFECYCLE_LIMITS.ERROR) {\n logger.error(\n `router.${methodName}`,\n `${currentSize} lifecycle handlers registered! ` +\n `This is excessive. Hard limit at ${LIFECYCLE_LIMITS.HARD_LIMIT}.`,\n );\n } else if (currentSize >= LIFECYCLE_LIMITS.WARN) {\n logger.warn(\n `router.${methodName}`,\n `${currentSize} lifecycle handlers registered. ` +\n `Consider consolidating logic.`,\n );\n }\n}\n\n/**\n * Converts a boolean value to an activation function factory.\n * Used for the shorthand syntax where true/false is passed instead of a function.\n *\n * Design note: Creates a factory that returns a function returning the boolean.\n * This maintains consistency with the factory pattern used throughout.\n *\n * @param value - Boolean value to convert\n * @returns Factory function that produces an activation function\n */\nfunction booleanToFactory<Dependencies extends DefaultDependencies>(\n value: boolean,\n): ActivationFnFactory<Dependencies> {\n // Cache the activation function to avoid recreating it\n const activationFn: ActivationFn = () => value;\n\n return () => activationFn;\n}\n\n/**\n * Adds route lifecycle capabilities to a router instance.\n * Allows registration of canActivate and canDeactivate guards for routes.\n *\n * Design decisions:\n * - Uses Map for O(1) operations and better memory management\n * - Separate Maps for factories and compiled functions\n * - Supports both boolean shortcuts and factory functions\n * - Warns on overwrites to prevent silent failures\n * - Enforces limits to prevent architectural degradation\n *\n * @param router - Router instance to enhance\n * @returns Enhanced router with lifecycle methods\n */\nexport function withRouteLifecycle<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): Router<Dependencies> {\n // Use Map for efficient O(1) operations\n // Separate storage for factories (source) and functions (compiled)\n const canDeactivateFactories = new Map<\n string,\n ActivationFnFactory<Dependencies>\n >();\n const canActivateFactories = new Map<\n string,\n ActivationFnFactory<Dependencies>\n >();\n const canDeactivateFunctions = new Map<string, ActivationFn>();\n const canActivateFunctions = new Map<string, ActivationFn>();\n\n // Track routes currently being registered to prevent self-modification\n // This prevents desynchronization between factories and functions Maps\n const registering = new Set<string>();\n\n /**\n * Internal helper to register a lifecycle handler.\n * Centralizes the logic for both canActivate and canDeactivate.\n *\n * @param type - Type of handler ('activate' or 'deactivate')\n * @param name - Route name\n * @param handler - Handler function or boolean\n * @param factories - Map to store factories\n * @param functions - Map to store compiled functions\n * @param methodName - Method name for error messages\n */\n function registerHandler(\n type: \"activate\" | \"deactivate\",\n name: string,\n handler: ActivationFnFactory<Dependencies> | boolean,\n factories: Map<string, ActivationFnFactory<Dependencies>>,\n functions: Map<string, ActivationFn>,\n methodName: string,\n ): void {\n // Prevent self-modification during factory compilation\n // This ensures factories and functions Maps stay synchronized\n if (registering.has(name)) {\n throw new Error(\n `[router.${methodName}] Cannot modify route \"${name}\" during its own registration`,\n );\n }\n\n const isOverwrite = factories.has(name);\n\n if (isOverwrite) {\n // Warn about overwrites for debugging\n logger.warn(\n `router.${methodName}`,\n `Overwriting existing ${type} handler for route \"${name}\"`,\n );\n } else {\n // Check limit only for new handlers\n checkHandlerCount(factories.size + 1, methodName);\n }\n\n // Convert boolean to factory if needed\n const factory = isBoolean(handler)\n ? booleanToFactory<Dependencies>(handler)\n : handler;\n\n // Store factory\n factories.set(name, factory);\n\n // Mark route as being registered before calling user factory\n registering.add(name);\n\n // Compile and cache the function immediately\n // This validates the factory early and improves runtime performance\n try {\n const fn = factory(router, router.getDependency);\n\n if (typeof fn !== \"function\") {\n throw new TypeError(\n `[router.${methodName}] Factory must return a function, got ${getTypeDescription(fn)}`,\n );\n }\n\n functions.set(name, fn);\n } catch (error) {\n // Rollback on failure to maintain consistency\n factories.delete(name);\n\n throw error;\n } finally {\n // Always remove from registering set\n registering.delete(name);\n }\n }\n\n /**\n * Returns lifecycle factories for cloning.\n *\n * @internal Used by router.clone(). Not part of public API.\n * @returns Tuple of [canDeactivateFactories, canActivateFactories]\n */\n router.getLifecycleFactories = (): [\n Record<string, ActivationFnFactory<Dependencies>>,\n Record<string, ActivationFnFactory<Dependencies>>,\n ] => {\n // Convert Maps to Records for backward compatibility\n // Note: This creates a snapshot, not a live reference\n const deactivateRecord: Record<\n string,\n ActivationFnFactory<Dependencies>\n > = {};\n const activateRecord: Record<\n string,\n ActivationFnFactory<Dependencies>\n > = {};\n\n for (const [name, factory] of canDeactivateFactories) {\n deactivateRecord[name] = factory;\n }\n\n for (const [name, factory] of canActivateFactories) {\n activateRecord[name] = factory;\n }\n\n return [deactivateRecord, activateRecord];\n };\n\n /**\n * Returns compiled lifecycle functions for transition execution.\n * Returns Maps directly for O(1) operations without Object.fromEntries overhead.\n *\n * @internal Used by transition system. Not part of public API.\n * @returns Tuple of [canDeactivateFunctions, canActivateFunctions] as Maps\n */\n router.getLifecycleFunctions = () => [\n canDeactivateFunctions,\n canActivateFunctions,\n ];\n\n /**\n * Registers a canActivate guard for a route.\n * The guard is called before activating the route.\n *\n * @param name - Route name to guard\n * @param canActivateHandler - Guard function or boolean\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string or handler is invalid\n * @throws {Error} If handler limit is exceeded\n *\n * @example\n * // Boolean shorthand\n * router.canActivate('admin', false); // Always deny\n *\n * @example\n * // Factory function\n * router.canActivate('profile', (router) => {\n * return (toState, fromState, done) => {\n * const isAuthenticated = router.getDependency('auth').isLoggedIn();\n * done(isAuthenticated ? undefined : new Error('Not authenticated'));\n * };\n * });\n */\n router.canActivate = (\n name: string,\n canActivateHandler: ActivationFnFactory<Dependencies> | boolean,\n ): Router<Dependencies> => {\n validateRouteName(name, \"canActivate\");\n validateHandler<Dependencies>(canActivateHandler, \"canActivate\");\n\n registerHandler(\n \"activate\",\n name,\n canActivateHandler,\n canActivateFactories,\n canActivateFunctions,\n \"canActivate\",\n );\n\n return router;\n };\n\n /**\n * Registers a canDeactivate guard for a route.\n * The guard is called before leaving the route.\n *\n * @param name - Route name to guard\n * @param canDeactivateHandler - Guard function or boolean\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string or handler is invalid\n * @throws {Error} If handler limit is exceeded\n *\n * @example\n * // Prevent leaving with unsaved changes\n * router.canDeactivate('editor', (router) => {\n * return (toState, fromState, done) => {\n * if (hasUnsavedChanges()) {\n * const confirmed = confirm('Discard unsaved changes?');\n * done(confirmed ? undefined : new Error('User cancelled'));\n * } else {\n * done();\n * }\n * };\n * });\n */\n router.canDeactivate = (\n name: string,\n canDeactivateHandler: ActivationFnFactory<Dependencies> | boolean,\n ): Router<Dependencies> => {\n validateRouteName(name, \"canDeactivate\");\n validateHandler<Dependencies>(canDeactivateHandler, \"canDeactivate\");\n\n registerHandler(\n \"deactivate\",\n name,\n canDeactivateHandler,\n canDeactivateFactories,\n canDeactivateFunctions,\n \"canDeactivate\",\n );\n\n return router;\n };\n\n /**\n * Removes a canDeactivate guard for a route.\n * Used to clean up guards that are no longer needed.\n *\n * @param name - Route name to clear guard for\n * @param silent - If true, suppresses warning when no handler exists\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string\n *\n * @example\n * router.clearCanDeactivate('editor');\n */\n router.clearCanDeactivate = (\n name: string,\n silent = false,\n ): Router<Dependencies> => {\n validateRouteName(name, \"clearCanDeactivate\");\n\n // Prevent clearing a route during its own registration\n if (registering.has(name)) {\n throw new Error(\n `[router.clearCanDeactivate] Cannot modify route \"${name}\" during its own registration`,\n );\n }\n\n const factoryDeleted = canDeactivateFactories.delete(name);\n const functionDeleted = canDeactivateFunctions.delete(name);\n\n if (!silent && !factoryDeleted && !functionDeleted) {\n logger.warn(\n \"router.clearCanDeactivate\",\n `No canDeactivate handler found for route \"${name}\"`,\n );\n }\n\n return router;\n };\n\n /**\n * Removes a canActivate guard for a route.\n * Used to clean up guards that are no longer needed.\n *\n * @param name - Route name to clear guard for\n * @param silent - If true, suppresses warning when no handler exists\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string\n *\n * @example\n * router.clearCanActivate('admin');\n */\n router.clearCanActivate = (\n name: string,\n silent = false,\n ): Router<Dependencies> => {\n validateRouteName(name, \"clearCanActivate\");\n\n // Prevent clearing a route during its own registration\n if (registering.has(name)) {\n throw new Error(\n `[router.clearCanActivate] Cannot modify route \"${name}\" during its own registration`,\n );\n }\n\n const factoryDeleted = canActivateFactories.delete(name);\n const functionDeleted = canActivateFunctions.delete(name);\n\n if (!silent && !factoryDeleted && !functionDeleted) {\n logger.warn(\n \"router.clearCanActivate\",\n `No canActivate handler found for route \"${name}\"`,\n );\n }\n\n return router;\n };\n\n return router;\n}\n","// packages/real-router/modules/internals.ts\n\n/**\n * Typed accessors for internal router storage.\n *\n * Router uses Symbols to store internal state that shouldn't appear in Object.keys().\n * These accessors provide type-safe access without scattered type casts.\n *\n * @internal\n */\n\nimport {\n ROOT_TREE_SYMBOL,\n RESOLVED_FORWARD_MAP_SYMBOL,\n CONFIG_SYMBOL,\n} from \"./constants\";\n\nimport type { Router, DefaultDependencies, Config } from \"core-types\";\nimport type { RouteTree } from \"route-tree\";\n\n/**\n * Internal storage shape for router.\n * These properties are stored using Symbols for encapsulation.\n */\ninterface RouterInternals {\n [ROOT_TREE_SYMBOL]: RouteTree;\n [RESOLVED_FORWARD_MAP_SYMBOL]: Record<string, string>;\n [CONFIG_SYMBOL]: Config;\n}\n\n/**\n * Type for router with internal storage exposed.\n */\ntype RouterWithInternals<Dependencies extends DefaultDependencies> =\n Router<Dependencies> & RouterInternals;\n\n// =============================================================================\n// Route Tree Accessors\n// =============================================================================\n\n/**\n * Gets the route tree from router internal storage.\n * Tree is always initialized in createRouter, so this never returns undefined.\n *\n * @param router - Router instance\n * @returns Route tree\n */\nexport function getRouteTree<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): RouteTree {\n return (router as RouterWithInternals<Dependencies>)[ROOT_TREE_SYMBOL];\n}\n\n/**\n * Sets the route tree in router internal storage.\n *\n * @param router - Router instance\n * @param tree - New route tree\n */\nexport function setRouteTree<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n tree: RouteTree,\n): void {\n (router as RouterWithInternals<Dependencies>)[ROOT_TREE_SYMBOL] = tree;\n}\n\n// =============================================================================\n// Resolved Forward Map Accessors\n// =============================================================================\n\n/**\n * Gets the resolved forward map from router internal storage.\n * Map is always initialized in createRouter, so this never returns undefined.\n *\n * @param router - Router instance\n * @returns Resolved forward map (route name → final destination)\n */\nexport function getResolvedForwardMap<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Record<string, string> {\n return (router as RouterWithInternals<Dependencies>)[\n RESOLVED_FORWARD_MAP_SYMBOL\n ];\n}\n\n/**\n * Sets the resolved forward map in router internal storage.\n *\n * @param router - Router instance\n * @param map - New resolved forward map\n */\nexport function setResolvedForwardMap<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n map: Record<string, string>,\n): void {\n (router as RouterWithInternals<Dependencies>)[RESOLVED_FORWARD_MAP_SYMBOL] =\n map;\n}\n\n// =============================================================================\n// Config Accessors\n// =============================================================================\n\n/**\n * Gets the router configuration from internal storage.\n * Config is always initialized in createRouter, so this never returns undefined.\n *\n * @param router - Router instance\n * @returns Router configuration (decoders, encoders, defaultParams, forwardMap)\n */\nexport function getConfig<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Config {\n return (router as RouterWithInternals<Dependencies>)[CONFIG_SYMBOL];\n}\n\n/**\n * Sets the router configuration in internal storage.\n *\n * @param router - Router instance\n * @param config - New configuration\n */\nexport function setConfig<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n config: Config,\n): void {\n (router as RouterWithInternals<Dependencies>)[CONFIG_SYMBOL] = config;\n}\n","// packages/real-router/modules/core/stateBuilder.ts\n\n/**\n * State Builder Utilities.\n *\n * Functions for building RouteTreeState from raw route segments.\n * This module handles the conversion from low-level route-node data\n * to the higher-level state representation used by real-router.\n *\n * @module core/stateBuilder\n */\n\nimport { getMetaFromSegments } from \"route-tree\";\n\nimport type {\n MatchResult,\n RouteParams,\n RouteTree,\n RouteTreeState,\n} from \"route-tree\";\n\n/**\n * Builds a dot-separated route name from segments.\n *\n * @param segments - Array of route segments with names\n * @returns Dot-separated route name (e.g., \"users.profile\")\n *\n * @example\n * ```typescript\n * const segments = [{ name: \"users\" }, { name: \"profile\" }];\n * buildNameFromSegments(segments); // \"users.profile\"\n * ```\n */\nexport function buildNameFromSegments(segments: readonly RouteTree[]): string {\n let name = \"\";\n\n for (const segment of segments) {\n if (segment.name) {\n if (name) {\n name += \".\";\n }\n\n name += segment.name;\n }\n }\n\n return name;\n}\n\n/**\n * Creates a RouteTreeState from a MatchResult.\n *\n * This function is the primary way to build a RouteTreeState when\n * you have a MatchResult from matchPathSegments() or other low-level APIs.\n *\n * @param matchResult - Result from matchPathSegments() containing segments and params\n * @param name - Optional explicit name (if not provided, built from segments)\n * @returns RouteTreeState with name, params, and meta\n *\n * @example\n * ```typescript\n * const matchResult = routeNode.matchPathSegments(\"/users/123\");\n * if (matchResult) {\n * const state = createRouteState(matchResult);\n * // { name: \"users.profile\", params: { id: \"123\" }, meta: {...} }\n * }\n * ```\n */\nexport function createRouteState<P extends RouteParams = RouteParams>(\n matchResult: MatchResult<P>,\n name?: string,\n): RouteTreeState<P> {\n const resolvedName = name ?? buildNameFromSegments(matchResult.segments);\n\n return {\n name: resolvedName,\n params: matchResult.params,\n meta: getMetaFromSegments(matchResult.segments),\n };\n}\n","// packages/real-router/modules/core/routes/routePath.ts\n\nimport {\n createRouteTree,\n matchSegments,\n buildPath as routeNodeBuildPath,\n} from \"route-tree\";\nimport { isString } from \"type-guards\";\n\nimport { constants } from \"@real-router/core\";\n\nimport { ROUTE_DEFINITIONS_SYMBOL, ROOT_PATH_SYMBOL } from \"../../constants\";\nimport { createBuildOptions } from \"../../helpers\";\nimport { getConfig, getRouteTree, setRouteTree } from \"../../internals\";\nimport { createRouteState } from \"../stateBuilder\";\n\nimport type {\n Params,\n State,\n Router,\n DefaultDependencies,\n Options,\n} from \"core-types\";\nimport type {\n BuildOptions,\n MatchOptions,\n RouteDefinition,\n RouteTree,\n} from \"route-tree\";\n\n// =============================================================================\n// BuildOptions Cache (local to routePath)\n// =============================================================================\n\n/**\n * Internal Symbol for caching buildOptions.\n * Local to this module — only used by buildPath functionality.\n *\n * @internal\n * @todo RFC-1: Replace with direct #options field access from internal contour.\n */\nconst BUILD_OPTIONS_CACHE_SYMBOL = Symbol(\"real-router.buildOptionsCache\");\n\n/**\n * Type for router with cached buildOptions.\n */\ntype RouterWithCache = Record<symbol, BuildOptions | undefined>;\n\n/**\n * Initializes buildOptions cache for a router.\n * Called from routerLifecycle.ts at router.start().\n *\n * @param router - Router instance\n * @param options - Router options\n *\n * @internal\n */\nexport function initBuildOptionsCache<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n options: Options,\n): void {\n // Invalidate previous cache (support for stop/start cycles)\n delete (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL];\n // Create new cache with current options\n (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL] =\n createBuildOptions(options);\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_ROUTE_NAME = \"\";\n\n/**\n * Creates RouteNode match options from real-router options.\n */\nfunction createMatchOptions(options: Options): MatchOptions {\n return {\n ...createBuildOptions(options),\n caseSensitive: options.caseSensitive,\n strictTrailingSlash: options.trailingSlash === \"strict\",\n strongMatching: false,\n };\n}\n\n/**\n * Adds path building and matching capabilities to a router instance.\n * Handles URL path construction, path-to-route matching, and root path management.\n *\n * @returns Function to enhance router with path capabilities\n */\nexport function withRoutePath<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n /**\n * Builds a URL path for a route with parameters.\n *\n * @param route - Route name (dot-notation for nested routes, e.g., 'users.profile')\n * @param params - Route parameters to encode into the path\n * @returns Built URL path\n * @throws {TypeError} If route is not a non-empty string\n * @throws {Error} If route does not exist in the router\n * @throws {Error} If required parameters are missing\n * @throws {Error} If parameter value doesn't match its constraint pattern\n *\n * @remarks\n * **Parameter Type Coercion:**\n * - Numeric values (including `NaN`, `Infinity`, `-Infinity`) are converted to strings\n * via `String()`. This may produce unexpected URLs like `/user/NaN` or `/user/Infinity`.\n * Validate numeric parameters before passing them to buildPath if semantic correctness\n * is required.\n * - Boolean values are converted to `\"true\"` or `\"false\"` strings.\n * - Empty strings throw an error as they don't match the default parameter pattern.\n * - Arrays are converted via `String()` (e.g., `[\"a\",\"b\"]` → `\"a,b\"`), which may fail\n * validation unless a custom constraint like `<.*>` is used.\n *\n * @example\n * // Basic usage\n * router.buildPath('users.view', { id: '123' });\n * // Returns: '/users/123'\n *\n * @example\n * // With query parameters\n * router.buildPath('search', { q: 'hello', page: '1' });\n * // Returns: '/search?q=hello&page=1'\n *\n * @example\n * // Numeric values are stringified (use with caution)\n * router.buildPath('user', { id: 42 }); // → '/user/42'\n * router.buildPath('user', { id: NaN }); // → '/user/NaN' ⚠️\n * router.buildPath('user', { id: Infinity }); // → '/user/Infinity' ⚠️\n */\n router.buildPath = (route: string, params?: Params): string => {\n // Early validation for better DX (fail-fast with clear message)\n if (!isString(route) || route === \"\") {\n throw new TypeError(\n `[real-router] buildPath: route must be a non-empty string, got ${typeof route === \"string\" ? '\"\"' : typeof route}`,\n );\n }\n\n if (route === constants.UNKNOWN_ROUTE) {\n return isString(params?.path) ? params.path : \"\";\n }\n\n const config = getConfig(router);\n\n // R2 optimization: avoid spread when no defaultParams\n const paramsWithDefault = Object.hasOwn(config.defaultParams, route)\n ? { ...config.defaultParams[route], ...params }\n : (params ?? {});\n\n // Apply custom encoder if defined (copy protects original params)\n const encodedParams =\n typeof config.encoders[route] === \"function\"\n ? config.encoders[route]({ ...paramsWithDefault })\n : paramsWithDefault;\n\n // R5 optimization: read cached buildOptions (created at router.start())\n // Fallback for cold calls before start() — creates buildOptions on the fly\n const buildOptions =\n (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL] ??\n createBuildOptions(router.getOptions());\n\n return routeNodeBuildPath(\n getRouteTree(router),\n route,\n encodedParams,\n buildOptions,\n );\n };\n\n /**\n * Internal path builder that accepts pre-computed segments.\n * Avoids duplicate getSegmentsByName call when segments are already available.\n *\n * @internal\n */\n router.buildPathWithSegments = (\n route: string,\n params: Params,\n segments: readonly unknown[],\n ): string => {\n // Early validation for better DX (fail-fast with clear message)\n if (!isString(route) || route === \"\") {\n throw new TypeError(\n `[real-router] buildPathWithSegments: route must be a non-empty string, got ${typeof route === \"string\" ? '\"\"' : typeof route}`,\n );\n }\n\n if (route === constants.UNKNOWN_ROUTE) {\n return isString(params.path) ? params.path : \"\";\n }\n\n const config = getConfig(router);\n\n // R2 optimization: avoid spread when no defaultParams\n const paramsWithDefault = Object.hasOwn(config.defaultParams, route)\n ? { ...config.defaultParams[route], ...params }\n : params;\n\n // Apply custom encoder if defined (copy protects original params)\n const encodedParams =\n typeof config.encoders[route] === \"function\"\n ? config.encoders[route]({ ...paramsWithDefault })\n : paramsWithDefault;\n\n // R5 optimization: read cached buildOptions\n /* v8 ignore next 2 -- @preserve defensive: always called after router.start() */\n const buildOptions =\n (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL] ??\n createBuildOptions(router.getOptions());\n\n // Pass segments to avoid duplicate getSegmentsByName call in route-tree\n // Cast to RouteTree[] - segments come from getSegmentsByName which returns RouteTree[]\n return routeNodeBuildPath(\n getRouteTree(router),\n route,\n encodedParams,\n buildOptions,\n segments as readonly RouteTree[],\n );\n };\n\n /**\n * Matches a URL path to a route in the tree.\n * Uses caching for performance optimization.\n * Note: RouteNode automatically matches `/` child nodes when accessing parent.\n *\n * @param path - URL path to match\n * @param source - Optional source identifier for debugging\n * @returns Matched state or undefined if no match\n *\n * @example\n * const state = router.matchPath('/users/123');\n * // Returns: { name: 'users.view', params: { id: '123' }, ... }\n */\n router.matchPath = <P extends Params = Params, MP extends Params = Params>(\n path: string,\n source?: string,\n ): State<P, MP> | undefined => {\n // Early validation for better DX (fail-fast with clear message)\n if (!isString(path)) {\n throw new TypeError(\n `[real-router] matchPath: path must be a string, got ${typeof path}`,\n );\n }\n\n const options = router.getOptions();\n\n // Use full set of options supported by RouteNode\n const matchOptions = createMatchOptions(options);\n\n // Use low-level API: get segments and build state in real-router\n const matchResult = matchSegments(getRouteTree(router), path, matchOptions);\n\n if (matchResult) {\n // Build RouteTreeState from MatchResult\n const routeState = createRouteState(matchResult);\n const { name, params, meta } = routeState;\n\n const { decoders } = getConfig(router);\n const decodedParams =\n typeof decoders[name] === \"function\"\n ? decoders[name](params as Params)\n : params;\n const { name: routeName, params: routeParams } = router.forwardState<P>(\n name,\n decodedParams as P,\n );\n const builtPath = options.rewritePathOnMatch\n ? router.buildPath(routeName, routeParams)\n : path;\n\n // makeState() already returns frozen state - no need for redundant freeze\n return router.makeState<P, MP>(routeName, routeParams, builtPath, {\n params: meta as MP,\n options: {},\n source,\n redirected: false,\n });\n }\n\n return undefined;\n };\n\n /**\n * Sets the root path for the router.\n *\n * @param newRootPath - New root path\n */\n router.setRootPath = (newRootPath): void => {\n type RouterInternal = Record<symbol, RouteDefinition[] | string>;\n const routerInternal = router as RouterInternal;\n\n routerInternal[ROOT_PATH_SYMBOL] = newRootPath;\n\n // Rebuild tree with new root path\n const routeDefinitions = routerInternal[\n ROUTE_DEFINITIONS_SYMBOL\n ] as RouteDefinition[];\n\n setRouteTree(\n router,\n createRouteTree(DEFAULT_ROUTE_NAME, newRootPath, routeDefinitions, {\n skipValidation: true,\n }),\n );\n };\n\n router.getRootPath = (): string => {\n return (router as Record<symbol, string>)[ROOT_PATH_SYMBOL] || \"\";\n };\n\n return router;\n}\n","// packages/real-router/modules/core/routerLifecycle.ts\n\nimport { logger } from \"logger\";\nimport { isState } from \"type-guards\";\n\nimport { errorCodes, events, RouterError } from \"@real-router/core\";\n\nimport { initBuildOptionsCache } from \"./routes/routePath\";\n\nimport type {\n DoneFn,\n NavigationOptions,\n Params,\n State,\n DefaultDependencies,\n Router,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\nconst noop = () => {};\n\n// =============================================================================\n// Cached Errors (Performance Optimization)\n// =============================================================================\n// Pre-create error instances to avoid object allocation on hot paths.\n// Error creation involves: new object, stack trace capture (~500ns-2μs).\n// Cached errors skip this overhead entirely.\n//\n// Trade-off: All error instances share the same stack trace (points here).\n// This is acceptable because:\n// 1. These errors indicate user misconfiguration, not internal bugs\n// 2. Error code and message are sufficient for debugging\n// 3. Performance gain (~80% for error paths) outweighs stack trace loss\n// =============================================================================\n\n/**\n * Cached error for start() called without path/state and no defaultRoute.\n *\n * @internal\n */\nconst CACHED_NO_START_PATH_ERROR = new RouterError(\n errorCodes.NO_START_PATH_OR_STATE,\n);\n\n/**\n * Cached error for start() called when router is already started/starting.\n *\n * @internal\n */\nconst CACHED_ALREADY_STARTED_ERROR = new RouterError(\n errorCodes.ROUTER_ALREADY_STARTED,\n);\n\ntype StartRouterArguments =\n | []\n | [done: DoneFn]\n | [startPathOrState: string | State]\n | [startPathOrState: string | State, done: DoneFn];\n\nconst getStartRouterArguments = (\n args: StartRouterArguments,\n): [startPathOrState: string | State | undefined, done: DoneFn] => {\n // Simple validation\n if (args.length > 2) {\n throw new Error(\"Invalid number of arguments\");\n }\n\n const [first, second] = args;\n\n if (!first) {\n return [undefined, noop];\n }\n if (typeof first === \"function\") {\n return [undefined, first];\n }\n\n return [first, second ?? noop];\n};\n\n// State resolution logic\nconst resolveStartState = <Dependencies extends DefaultDependencies>(\n pathOrState: string | State,\n router: Router<Dependencies>,\n): State | undefined => {\n if (typeof pathOrState === \"string\") {\n return router.matchPath(pathOrState);\n }\n\n // Validate state object structure using isState type guard\n // This validates: name (non-empty string), path (string), params (plain object)\n // Rejects: missing fields, wrong types, functions, symbols, class instances\n if (!isState(pathOrState)) {\n return undefined;\n }\n\n // Validate that the route exists\n // buildPath throws RouteNotFoundError for invalid routes, so we wrap in try-catch\n // to gracefully return undefined instead of propagating the error\n // See: https://github.com/greydragon888/real-router/issues/42\n try {\n router.buildPath(pathOrState.name, pathOrState.params);\n } catch {\n return undefined;\n }\n\n return pathOrState;\n};\n\n// Note: Guards cannot redirect - redirects are not supported from guards\n// See: https://github.com/greydragon888/real-router/issues/44\n// Transition errors are always reported to callback, no silent fallback to defaultRoute\n\nconst STARTED = Symbol(\"started\");\n// Issue #50: Track \"active\" state separately from \"started\"\n// Active = router is starting or started (allows transitions)\n// Started = router has completed initial start (allows navigation)\nconst ACTIVE = Symbol(\"active\");\n\nexport function withRouterLifecycle<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n router[STARTED] = false;\n router[ACTIVE] = false;\n\n const setIsStarted = () => {\n router[STARTED] = true;\n };\n\n const unsetIsStarted = () => {\n router[STARTED] = false;\n };\n\n const setIsActive = () => {\n router[ACTIVE] = true;\n };\n\n const unsetIsActive = () => {\n router[ACTIVE] = false;\n };\n\n router.isStarted = () => !!router[STARTED];\n\n // Issue #50: isActive() indicates router is starting or started\n // Used by transition to check if transitions should be cancelled\n router.isActive = () => !!router[ACTIVE];\n\n router.start = (...args: StartRouterArguments): Router<Dependencies> => {\n const options = router.getOptions();\n const [startPathOrState, done] = getStartRouterArguments(args);\n\n let callbackInvoked = false;\n\n // Early return if already started or starting (concurrent start() protection)\n // Issue #50: Check both isStarted() and isActive() to block concurrent start() calls\n // - isStarted(): Router has completed initial start\n // - isActive(): Router is in the process of starting (async transition in progress)\n // Performance: Uses cached error to avoid object allocation (~500ns-2μs saved)\n if (router.isStarted() || router.isActive()) {\n callbackInvoked = true;\n\n done(CACHED_ALREADY_STARTED_ERROR);\n\n return router;\n }\n\n // ==========================================================================\n // Early return for NO_START_PATH_OR_STATE (Performance Optimization)\n // ==========================================================================\n // Check BEFORE setIsActive() to avoid:\n // - setIsActive/unsetIsActive calls\n // - handleTransitionComplete overhead\n // - Event emission setup\n //\n // This is a common error case: start() called without path and no defaultRoute.\n // Optimizing this path saves ~80% of error handling overhead.\n // ==========================================================================\n if (!startPathOrState && !options.defaultRoute) {\n callbackInvoked = true;\n\n // Lazy emit: only invoke if listeners exist\n // hasListeners check (~5ns) vs invokeEventListeners validation (~100ns+)\n if (router.hasListeners(events.TRANSITION_ERROR)) {\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n undefined,\n CACHED_NO_START_PATH_ERROR,\n );\n }\n\n done(CACHED_NO_START_PATH_ERROR);\n\n return router;\n }\n\n // Issue #50: Mark router as active BEFORE attempting transition\n // This allows the transition to proceed (isCancelled() checks isActive())\n setIsActive();\n\n // Perform the actual transition\n // See: https://github.com/greydragon888/real-router/issues/44\n // On error, always report to handleTransitionComplete (no silent fallback)\n const performTransition = (\n toState: State,\n navOptions: NavigationOptions = {},\n ) => {\n // Use internal navigateToState without emitting TRANSITION_SUCCESS\n // handleTransitionComplete will emit it\n router.navigateToState(\n toState,\n undefined,\n navOptions,\n (err: RouterErrorType | undefined, resultState: State | undefined) => {\n handleTransitionComplete(err, resultState);\n },\n false, // emitSuccess = false - handleTransitionComplete will emit\n );\n };\n\n const protectedDone = (err?: RouterError, state?: State) => {\n if (callbackInvoked) {\n logger.warn(\"real-router\", \"Callback already invoked\");\n\n return;\n }\n\n callbackInvoked = true;\n // State is already frozen from makeState() in start flow\n done(err, state);\n };\n\n // Base options for all operations in start() method\n const startOptions: NavigationOptions = {\n replace: true, // start() always replace history\n };\n\n // Centralized callback for transition completion\n // See: https://github.com/greydragon888/real-router/issues/44\n // Transition errors are always reported (no silent fallback to defaultRoute)\n //\n // See: https://github.com/greydragon888/real-router/issues/50\n // Two-phase start: Only mark router as started AFTER successful transition\n // This prevents inconsistent state where isStarted()=true but getState()=undefined\n //\n // Note: emitErrorEvent controls whether TRANSITION_ERROR event is emitted:\n // - true: for errors NOT going through navigateToState (ROUTE_NOT_FOUND, NO_START_PATH_OR_STATE)\n // - false: for errors from performTransition (navigateToState already emits TRANSITION_ERROR)\n const handleTransitionComplete = (\n err?: RouterError,\n state?: State,\n emitErrorEvent = false,\n ) => {\n if (err) {\n // Issue #50: Unset active flag on failure (router is no longer starting)\n unsetIsActive();\n\n if (emitErrorEvent && router.hasListeners(events.TRANSITION_ERROR)) {\n // Emit TRANSITION_ERROR for errors not going through navigateToState\n // Performance: Skip emission if no listeners\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n undefined,\n err,\n );\n }\n } else {\n // Two-phase start: Only set started and emit ROUTER_START on success\n // See: https://github.com/greydragon888/real-router/issues/50\n setIsStarted();\n router.invokeEventListeners(events.ROUTER_START);\n\n router.invokeEventListeners(\n events.TRANSITION_SUCCESS,\n state,\n undefined,\n { replace: true },\n );\n }\n // For performTransition errors, TRANSITION_ERROR is already emitted by navigateToState\n\n protectedDone(err, state);\n };\n\n // Build state for default route and perform transition\n // Uses performTransition to properly handle two-phase start\n const navigateToDefault = (\n defaultRouteName: string,\n defaultParams: Params,\n navOptions: NavigationOptions,\n ) => {\n const defaultRoute = router.buildState(defaultRouteName, defaultParams);\n\n if (!defaultRoute) {\n handleTransitionComplete(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: defaultRouteName,\n }),\n undefined,\n true,\n );\n\n return;\n }\n\n const toState = router.makeState(\n defaultRoute.name,\n defaultRoute.params,\n router.buildPath(defaultRoute.name, defaultRoute.params),\n {\n params: defaultRoute.meta,\n options: navOptions,\n redirected: false,\n },\n );\n\n performTransition(toState, navOptions);\n };\n\n // Resolve start path/state: use defaultRoute if no explicit path provided\n // Note: Early return for \"no path AND no defaultRoute\" is handled above\n const resolvedStartPathOrState = startPathOrState ?? options.defaultRoute;\n\n // Parse the start path or state\n const startState = resolveStartState(resolvedStartPathOrState, router);\n\n // Determine the target state and path\n const targetPath =\n typeof resolvedStartPathOrState === \"string\"\n ? resolvedStartPathOrState\n : \"\";\n\n // Check if we can attempt to start the router\n // See: https://github.com/greydragon888/real-router/issues/50\n // Two-phase start: We only initialize the cache here, but don't mark as started yet.\n // The router will be marked as started only after successful transition in handleTransitionComplete.\n //\n // Note: !startPathOrState checks ORIGINAL argument to distinguish:\n // - start() without path → can use defaultRoute\n // - start('/invalid') with explicit path → no silent fallback (Issue #44)\n const canAttemptStart =\n startState !== undefined ||\n options.allowNotFound ||\n (options.defaultRoute && !startPathOrState);\n\n if (canAttemptStart) {\n // Setup buildOptions cache for buildPath (needed for transition)\n initBuildOptionsCache(router, options);\n }\n\n // Perform transition based on conditions\n // All start() transitions should use replace: true\n // See: https://github.com/greydragon888/real-router/issues/43\n if (startState) {\n performTransition(startState, startOptions);\n } else if (options.defaultRoute && !startPathOrState) {\n // IMPORTANT: Check !startPathOrState (original argument), NOT !resolvedStartPathOrState\n // This distinguishes between:\n // - User called start() without path → use defaultRoute (this branch)\n // - User called start('/invalid') with explicit path → error, no silent fallback\n // See: https://github.com/greydragon888/real-router/issues/44\n\n const params = options.defaultParams;\n\n navigateToDefault(options.defaultRoute, params, startOptions);\n } else if (options.allowNotFound) {\n performTransition(\n router.makeNotFoundState(targetPath, startOptions),\n startOptions,\n );\n } else {\n handleTransitionComplete(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, { path: targetPath }),\n undefined,\n true, // emitErrorEvent: doesn't go through navigateToState\n );\n }\n\n return router;\n };\n\n router.stop = (): Router<Dependencies> => {\n // Issue #50: Always unset active flag when stopping\n // This cancels any in-flight transitions via isCancelled() check\n unsetIsActive();\n\n if (router.isStarted()) {\n unsetIsStarted();\n\n router.setState(undefined);\n\n router.invokeEventListeners(events.ROUTER_STOP);\n }\n\n return router;\n };\n\n return router;\n}\n","// packages/real-router/modules/core/routes/routeConfig.ts\n\nimport { logger } from \"logger\";\nimport { getSegmentsByName } from \"route-tree\";\nimport { isParams, getTypeDescription } from \"type-guards\";\n\nimport { getConfig, setResolvedForwardMap } from \"../../internals\";\n\nimport type {\n ActivationFnFactory,\n Config,\n DefaultDependencies,\n Params,\n Route,\n Router,\n} from \"core-types\";\nimport type { RouteDefinition, RouteTree } from \"route-tree\";\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validates parameters object structure.\n *\n * @param params - Parameters to validate\n * @param methodName - Calling method for error context\n * @throws {TypeError} If params structure is invalid\n */\nexport function validateParams(\n params: unknown,\n methodName: string,\n): asserts params is Params {\n if (!isParams(params)) {\n throw new TypeError(\n `[router.${methodName}] Invalid params structure: ${getTypeDescription(params)}`,\n );\n }\n}\n\n/**\n * Validates route properties (canActivate, defaultParams) before registration.\n * This ensures type safety at configuration time, not runtime.\n *\n * @param route - Route to validate\n * @param fullName - Full route name (with parent prefix)\n * @throws {TypeError} If canActivate is not a function\n * @throws {TypeError} If defaultParams is not a plain object\n */\nexport function validateRouteProperties<\n Dependencies extends DefaultDependencies,\n>(route: Route<Dependencies>, fullName: string): void {\n // Validate canActivate is a function\n if (\n route.canActivate !== undefined &&\n typeof route.canActivate !== \"function\"\n ) {\n throw new TypeError(\n `[router.addRoute] canActivate must be a function for route \"${fullName}\", ` +\n `got ${getTypeDescription(route.canActivate)}`,\n );\n }\n\n // Validate defaultParams is a plain object\n // Runtime check for invalid types passed via `as any`\n if (route.defaultParams !== undefined) {\n const params: unknown = route.defaultParams;\n\n if (\n params === null ||\n typeof params !== \"object\" ||\n Array.isArray(params)\n ) {\n throw new TypeError(\n `[router.addRoute] defaultParams must be an object for route \"${fullName}\", ` +\n `got ${getTypeDescription(route.defaultParams)}`,\n );\n }\n }\n\n // Recursively validate children\n if (route.children) {\n for (const child of route.children) {\n const childFullName = `${fullName}.${child.name}`;\n\n validateRouteProperties(child, childFullName);\n }\n }\n}\n\n// ============================================================================\n// Parameter Extraction Helpers\n// ============================================================================\n\n/**\n * Extracts required path parameters from route segments.\n * Required params are urlParams and spatParams (not queryParams).\n *\n * Note: getSegmentsByName only returns segments with parsers,\n * so we can safely use non-null assertion here.\n *\n * @param segments - Route segments from getSegmentsByName\n * @returns Set of required parameter names\n */\nexport function getRequiredParams(segments: readonly RouteTree[]): Set<string> {\n const params = new Set<string>();\n\n for (const segment of segments) {\n // getSegmentsByName only includes segments with parsers\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const parser = segment.parser!;\n\n for (const param of parser.urlParams) {\n params.add(param);\n }\n\n for (const param of parser.spatParams) {\n params.add(param);\n }\n }\n\n return params;\n}\n\n/**\n * Extracts parameter names from a path string.\n * Matches :param and *splat patterns.\n *\n * @param path - Route path string\n * @returns Set of parameter names\n */\nfunction extractParamsFromPath(path: string): Set<string> {\n const params = new Set<string>();\n // Match :param and *splat patterns\n const paramRegex = /[*:]([A-Z_a-z]\\w*)/g;\n let match;\n\n while ((match = paramRegex.exec(path)) !== null) {\n params.add(match[1]);\n }\n\n return params;\n}\n\n/**\n * Collects all path segments for a route from batch definitions.\n * Traverses parent routes to include inherited path segments.\n *\n * @remarks Callers must guarantee routeName exists in routes.\n *\n * @param routes - Batch of routes to search\n * @param routeName - Full route name to find (must exist in routes)\n * @param parentName - Current parent name prefix\n * @param paths - Accumulated path segments\n * @returns Array of path strings\n */\nfunction collectPathsToRoute<Dependencies extends DefaultDependencies>(\n routes: readonly Route<Dependencies>[],\n routeName: string,\n parentName = \"\",\n paths: string[] = [],\n): string[] {\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n const currentPaths = [...paths, route.path];\n\n if (fullName === routeName) {\n return currentPaths;\n }\n\n if (route.children && routeName.startsWith(`${fullName}.`)) {\n return collectPathsToRoute(\n route.children,\n routeName,\n fullName,\n currentPaths,\n );\n }\n }\n\n /* v8 ignore next -- @preserve unreachable: callers guarantee routeName exists in routes */\n return undefined as never;\n}\n\n/**\n * Extracts all parameters from multiple path segments.\n *\n * @param paths - Array of path strings\n * @returns Set of all parameter names\n */\nfunction extractParamsFromPaths(paths: readonly string[]): Set<string> {\n const params = new Set<string>();\n\n for (const path of paths) {\n for (const param of extractParamsFromPath(path)) {\n params.add(param);\n }\n }\n\n return params;\n}\n\n/**\n * Collects all route names from a batch of routes (including children).\n *\n * @param routes - Routes to collect names from\n * @param parentName - Parent name prefix\n * @returns Set of all route names in the batch\n */\nfunction collectRouteNames<Dependencies extends DefaultDependencies>(\n routes: readonly Route<Dependencies>[],\n parentName = \"\",\n): Set<string> {\n const names = new Set<string>();\n\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n\n names.add(fullName);\n\n if (route.children) {\n for (const childName of collectRouteNames(route.children, fullName)) {\n names.add(childName);\n }\n }\n }\n\n return names;\n}\n\n/**\n * Collects all forwardTo mappings from a batch of routes (including children).\n *\n * @param routes - Routes to collect forwardTo from\n * @param parentName - Parent name prefix\n * @returns Map of source route name to target route name\n */\nfunction collectForwardMappings<Dependencies extends DefaultDependencies>(\n routes: readonly Route<Dependencies>[],\n parentName = \"\",\n): Map<string, string> {\n const mappings = new Map<string, string>();\n\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n\n if (route.forwardTo) {\n mappings.set(fullName, route.forwardTo);\n }\n\n if (route.children) {\n for (const [key, value] of collectForwardMappings(\n route.children,\n fullName,\n )) {\n mappings.set(key, value);\n }\n }\n }\n\n return mappings;\n}\n\n/**\n * Checks if a route exists in the tree by navigating through childrenByName.\n *\n * @param tree - Root node of the route tree\n * @param routeName - Full route name (e.g., \"users.profile\")\n * @returns true if route exists, false otherwise\n */\nfunction routeExistsInTree(tree: RouteTree, routeName: string): boolean {\n const segments = routeName.split(\".\");\n let current: RouteTree | undefined = tree;\n\n for (const segment of segments) {\n current = current.childrenByName.get(segment);\n\n if (!current) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Gets the target route parameters for validation.\n */\nfunction getTargetParams<Dependencies extends DefaultDependencies>(\n targetRoute: string,\n existsInTree: boolean,\n tree: RouteTree,\n routes: readonly Route<Dependencies>[],\n): Set<string> {\n if (existsInTree) {\n const toSegments = getSegmentsByName(tree, targetRoute);\n\n // toSegments won't be null since we checked existsInTree\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return getRequiredParams(toSegments!);\n }\n\n // Target is in batch\n return extractParamsFromPaths(collectPathsToRoute(routes, targetRoute));\n}\n\n/**\n * Validates a single forward mapping for target existence and param compatibility.\n *\n * @throws {Error} If target doesn't exist or params are incompatible\n */\nfunction validateSingleForward<Dependencies extends DefaultDependencies>(\n fromRoute: string,\n targetRoute: string,\n routes: readonly Route<Dependencies>[],\n batchNames: Set<string>,\n tree: RouteTree,\n): void {\n const existsInTree = routeExistsInTree(tree, targetRoute);\n const existsInBatch = batchNames.has(targetRoute);\n\n if (!existsInTree && !existsInBatch) {\n throw new Error(\n `[router.addRoute] forwardTo target \"${targetRoute}\" does not exist ` +\n `for route \"${fromRoute}\"`,\n );\n }\n\n // Get source params\n const fromParams = extractParamsFromPaths(\n collectPathsToRoute(routes, fromRoute),\n );\n\n // Get target params\n const toParams = getTargetParams(targetRoute, existsInTree, tree, routes);\n\n // Check for missing params\n const missingParams = [...toParams].filter((p) => !fromParams.has(p));\n\n if (missingParams.length > 0) {\n throw new Error(\n `[router.addRoute] forwardTo target \"${targetRoute}\" requires params ` +\n `[${missingParams.join(\", \")}] that are not available in source route \"${fromRoute}\"`,\n );\n }\n}\n\n/**\n * Validates forwardTo targets and cycles BEFORE any modifications.\n * This ensures atomicity - if validation fails, no routes are added.\n *\n * @param routes - Routes to validate\n * @param existingForwardMap - Current forwardMap from router.config\n * @param tree - Current route tree\n *\n * @throws {Error} If forwardTo target doesn't exist\n * @throws {Error} If circular forwardTo is detected\n */\nexport function validateForwardToTargets<\n Dependencies extends DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n existingForwardMap: Record<string, string>,\n tree: RouteTree,\n): void {\n const batchNames = collectRouteNames(routes);\n const batchForwards = collectForwardMappings(routes);\n\n // Merge with existing forwardMap for cycle detection\n const combinedForwardMap: Record<string, string> = { ...existingForwardMap };\n\n for (const [from, to] of batchForwards) {\n combinedForwardMap[from] = to;\n }\n\n // Validate each forwardTo target exists and params are compatible\n for (const [fromRoute, targetRoute] of batchForwards) {\n validateSingleForward(fromRoute, targetRoute, routes, batchNames, tree);\n }\n\n // Check for cycles in the combined forwardMap\n for (const fromRoute of Object.keys(combinedForwardMap)) {\n resolveForwardChain(fromRoute, combinedForwardMap);\n }\n}\n\n/**\n * Registers route handlers (canActivate).\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteHandlers<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n router: Router<Dependencies>,\n): void {\n if (route.canActivate) {\n router.canActivate(route.name, route.canActivate);\n }\n}\n\n/**\n * Resolves a forwardTo chain to its final destination.\n *\n * Follows the chain of forwardTo references until reaching a route\n * that doesn't forward, or until detecting a cycle or reaching max depth.\n *\n * @param startRoute - Starting route name\n * @param forwardMap - Map of route forwards\n * @param maxDepth - Maximum chain depth (default: 100)\n * @returns Final destination route name\n * @throws {Error} If circular forwardTo is detected or chain exceeds max depth\n *\n * @example\n * ```typescript\n * // Simple chain: A → B → C\n * resolveForwardChain(\"A\", { A: \"B\", B: \"C\" }) // → \"C\"\n *\n * // Cycle detected: A → B → A\n * resolveForwardChain(\"A\", { A: \"B\", B: \"A\" }) // throws Error\n * ```\n */\nexport function resolveForwardChain(\n startRoute: string,\n forwardMap: Record<string, string>,\n maxDepth = 100,\n): string {\n const visited = new Set<string>();\n const chain: string[] = [startRoute];\n let current = startRoute;\n\n while (forwardMap[current]) {\n const next = forwardMap[current];\n\n // Cycle detection: if we've seen this route before, it's a cycle\n if (visited.has(next)) {\n const cycleStart = chain.indexOf(next);\n const cycle = [...chain.slice(cycleStart), next];\n\n throw new Error(`Circular forwardTo: ${cycle.join(\" → \")}`);\n }\n\n visited.add(current);\n chain.push(next);\n current = next;\n\n // Depth limit protection\n if (chain.length > maxDepth) {\n throw new Error(\n `forwardTo chain exceeds maximum depth (${maxDepth}): ${chain.join(\" → \")}`,\n );\n }\n }\n\n return current;\n}\n\n/**\n * Validates and caches all forwardTo chains.\n *\n * This function:\n * 1. Validates that all forwardTo targets exist in the route tree\n * 2. Detects circular forwardTo references\n * 3. Resolves all chains to their final destinations\n * 4. Caches the resolved values for O(1) runtime lookup\n *\n * @param router - Router instance\n * @throws {Error} If a forwardTo target doesn't exist or a cycle is detected\n */\nexport function validateAndCacheForwardMap<\n Dependencies extends DefaultDependencies,\n>(router: Router<Dependencies>): void {\n const { forwardMap } = getConfig(router);\n const resolvedMap: Record<string, string> = {};\n\n for (const fromRoute of Object.keys(forwardMap)) {\n // Resolve the full chain to cache the final destination\n // Note: cycles are caught in Phase 1 (validateForwardToTargets)\n resolvedMap[fromRoute] = resolveForwardChain(fromRoute, forwardMap);\n }\n\n // TODO(RFC-8): Replace with CacheManager.getInstance().setResolvedForwardMap(router, resolvedMap)\n setResolvedForwardMap(router, resolvedMap);\n}\n\n/**\n * Registers route forward configuration.\n *\n * IMPORTANT: forwardTo creates a URL alias, not a transition chain.\n * Guards (canActivate) on routes with forwardTo are NOT executed.\n * Only guards on the final destination are executed.\n *\n * This matches Vue Router and Angular Router behavior where\n * redirect routes bypass guards on the source.\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteForward<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n router: Router<Dependencies>,\n): void {\n if (route.forwardTo) {\n // Warn if route has both forwardTo and canActivate\n // canActivate will be ignored because forwardTo is an alias, not a transition\n if (route.canActivate) {\n logger.warn(\n \"real-router\",\n `Route \"${route.name}\" has both forwardTo and canActivate. ` +\n `canActivate will be ignored because forwardTo creates a redirect (industry standard). ` +\n `Move canActivate to the target route \"${route.forwardTo}\".`,\n );\n }\n\n getConfig(router).forwardMap[route.name] = route.forwardTo;\n }\n}\n\n/**\n * Registers route parameter decoders and encoders.\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteTransformers<\n Dependencies extends DefaultDependencies,\n>(route: Route<Dependencies>, router: Router<Dependencies>): void {\n const config = getConfig(router);\n\n if (route.decodeParams) {\n config.decoders[route.name] = (params: Params): Params =>\n route.decodeParams?.(params) ?? params;\n }\n\n if (route.encodeParams) {\n config.encoders[route.name] = (params: Params): Params =>\n route.encodeParams?.(params) ?? params;\n }\n}\n\n/**\n * Registers route default parameters.\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteDefaults<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n router: Router<Dependencies>,\n): void {\n if (route.defaultParams) {\n getConfig(router).defaultParams[route.name] = route.defaultParams;\n }\n}\n\n/**\n * Recursively registers all route handlers from a route definition.\n */\nexport function registerAllRouteHandlers<\n Dependencies extends DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n router: Router<Dependencies>,\n parentName = \"\",\n): void {\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n const routeWithFullName = { ...route, name: fullName };\n\n registerRouteHandlers(routeWithFullName, router);\n registerRouteForward(routeWithFullName, router);\n registerRouteTransformers(routeWithFullName, router);\n registerRouteDefaults(routeWithFullName, router);\n\n if (route.children) {\n registerAllRouteHandlers(route.children, router, fullName);\n }\n }\n}\n\n/**\n * Clears configuration entries that match the predicate.\n * Helper function for route removal operations.\n *\n * @param config - Configuration object to clean\n * @param matcher - Function to test if entry should be cleared\n */\nexport function clearConfigEntries<T>(\n config: Record<string, T>,\n matcher: (key: string) => boolean,\n): void {\n for (const key of Object.keys(config)) {\n if (matcher(key)) {\n delete config[key];\n }\n }\n}\n\n// ============================================================================\n// Route Tree Helpers\n// ============================================================================\n\n/**\n * Sanitizes a route by keeping only essential properties.\n * Custom properties (meta, permissions, etc.) are removed to optimize memory\n * and ensure a clean contract. Only name, path, and children are preserved.\n *\n * @param route - Route to sanitize\n * @returns Sanitized route definition\n */\nexport function sanitizeRoute<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n): RouteDefinition {\n const sanitized: RouteDefinition = {\n name: route.name,\n path: route.path,\n };\n\n if (route.children) {\n sanitized.children = route.children.map((child) => sanitizeRoute(child));\n }\n\n return sanitized;\n}\n\n/**\n * Recursively removes a route from definitions array.\n * Handles both top-level and nested routes.\n *\n * @param definitions - Route definitions array to modify\n * @param routeName - Full route name to remove\n * @param parentPrefix - Parent route prefix for recursion\n * @returns true if route was removed, false otherwise\n */\nexport function removeFromDefinitions(\n definitions: RouteDefinition[],\n routeName: string,\n parentPrefix = \"\",\n): boolean {\n for (let i = 0; i < definitions.length; i++) {\n const route = definitions[i];\n const fullName = parentPrefix\n ? `${parentPrefix}.${route.name}`\n : route.name;\n\n if (fullName === routeName) {\n definitions.splice(i, 1);\n\n return true;\n }\n\n if (\n route.children &&\n routeName.startsWith(`${fullName}.`) &&\n removeFromDefinitions(route.children, routeName, fullName)\n ) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Updates or removes a config map entry.\n * - undefined: no change\n * - null: remove entry\n * - value: set entry\n *\n * @param map - Config map to modify\n * @param name - Route name key\n * @param value - Value to set, null to remove, undefined to skip\n */\nexport function updateConfigEntry<T>(\n map: Record<string, T>,\n name: string,\n value: T | null | undefined,\n): void {\n if (value === undefined) {\n return;\n }\n\n if (value === null) {\n delete map[name];\n } else {\n map[name] = value;\n }\n}\n\n// ============================================================================\n// Higher-Order Factory Functions\n// ============================================================================\n\n/**\n * Creates a function to clear all configurations associated with a route.\n * Includes config entries (decoders, encoders, defaults, forwards)\n * and lifecycle handlers (canActivate, canDeactivate).\n *\n * @param router - Router instance\n * @returns Function that clears configurations for a route name\n */\nexport function createClearRouteConfigurations<\n Dependencies extends DefaultDependencies,\n>(router: Router<Dependencies>): (routeName: string) => void {\n return (routeName: string): void => {\n const shouldClear = (n: string): boolean =>\n n === routeName || n.startsWith(`${routeName}.`);\n\n const config = getConfig(router);\n\n // Clear config entries\n clearConfigEntries(config.decoders, shouldClear);\n clearConfigEntries(config.encoders, shouldClear);\n clearConfigEntries(config.defaultParams, shouldClear);\n clearConfigEntries(config.forwardMap, shouldClear);\n\n // Clear forwardMap entries pointing TO deleted route\n clearConfigEntries(config.forwardMap, (key) =>\n shouldClear(config.forwardMap[key]),\n );\n\n // Clear lifecycle handlers (silently - they may not exist)\n const [canDeactivateFactories, canActivateFactories] =\n router.getLifecycleFactories();\n\n for (const n of Object.keys(canActivateFactories)) {\n if (shouldClear(n)) {\n router.clearCanActivate(n, true);\n }\n }\n\n for (const n of Object.keys(canDeactivateFactories)) {\n if (shouldClear(n)) {\n router.clearCanDeactivate(n, true);\n }\n }\n };\n}\n\n/**\n * Creates a function to validate and apply forwardTo updates.\n *\n * @param forwardMap - Forward map from router config\n * @returns Function that validates and applies forwardTo\n * @throws {Error} If target doesn't exist, creates cycle, or params mismatch\n */\nexport function createApplyForwardToUpdate(\n forwardMap: Record<string, string>,\n): (\n name: string,\n toRoute: string,\n segments: readonly RouteTree[],\n tree: RouteTree,\n) => void {\n return (\n name: string,\n toRoute: string,\n segments: readonly RouteTree[],\n tree: RouteTree,\n ): void => {\n const toSegments = getSegmentsByName(tree, toRoute);\n\n if (!toSegments) {\n throw new Error(\n `[real-router] updateRoute: forwardTo target \"${toRoute}\" does not exist`,\n );\n }\n\n // Note: Self-reference cycles (name === toRoute) are caught by\n // resolveForwardChain() which runs before this function in updateRoute()\n\n const fromParams = getRequiredParams(segments);\n const toParams = getRequiredParams(toSegments);\n const missingParams = [...toParams].filter((p) => !fromParams.has(p));\n\n if (missingParams.length > 0) {\n throw new Error(\n `[real-router] updateRoute: forwardTo target \"${toRoute}\" requires params ` +\n `[${missingParams.join(\", \")}] that are not available in source route \"${name}\"`,\n );\n }\n\n forwardMap[name] = toRoute;\n };\n}\n\n/**\n * Creates a function to enrich route definitions with config data.\n *\n * @param config - Router config containing forwardMap, decoders, encoders, defaultParams\n * @param canActivateFactories - Map of canActivate factories by route name\n * @returns Recursive function that enriches RouteDefinition to full Route\n */\nexport function createEnrichRoute<Dependencies extends DefaultDependencies>(\n config: Config,\n canActivateFactories: Record<string, ActivationFnFactory<Dependencies>>,\n): (routeDef: RouteDefinition, routeName: string) => Route<Dependencies> {\n const enrichRoute = (\n routeDef: RouteDefinition,\n routeName: string,\n ): Route<Dependencies> => {\n const route: Route<Dependencies> = {\n name: routeDef.name,\n path: routeDef.path,\n };\n\n // Add forwardTo if exists\n const forwardTo = config.forwardMap[routeName];\n\n if (forwardTo) {\n route.forwardTo = forwardTo;\n }\n\n // Add defaultParams if exists\n if (routeName in config.defaultParams) {\n route.defaultParams = config.defaultParams[routeName];\n }\n\n // Add decoder if exists\n if (routeName in config.decoders) {\n route.decodeParams = config.decoders[routeName];\n }\n\n // Add encoder if exists\n if (routeName in config.encoders) {\n route.encodeParams = config.encoders[routeName];\n }\n\n // Add canActivate if exists\n if (routeName in canActivateFactories) {\n route.canActivate = canActivateFactories[routeName];\n }\n\n // Recursively enrich children\n if (routeDef.children) {\n route.children = routeDef.children.map((child) =>\n enrichRoute(child, `${routeName}.${child.name}`),\n );\n }\n\n return route;\n };\n\n return enrichRoute;\n}\n","// packages/real-router/modules/core/routes/routeQuery.ts\n\nimport { logger } from \"logger\";\nimport { routeTreeToDefinitions } from \"route-tree\";\nimport { isString, validateRouteName } from \"type-guards\";\n\nimport { createRouter } from \"@real-router/core\";\n\nimport { validateParams } from \"./routeConfig\";\nimport {\n getConfig,\n getResolvedForwardMap,\n getRouteTree,\n setConfig,\n setResolvedForwardMap,\n} from \"../../internals\";\nimport { getTransitionPath } from \"../../transitionPath\";\n\nimport type {\n Params,\n State,\n Router,\n Route,\n DefaultDependencies,\n} from \"core-types\";\n\n// Constants\nconst DEFAULT_ROUTE_NAME = \"\";\n\n// Cache for validated route names to skip regex validation on repeated calls\n// Key insight: validateRouteName() regex takes ~40ns, but cache lookup is ~1ns\n// This cache is module-level (shared across all router instances) since route name\n// validity is independent of router instance\nconst validatedRouteNames = new Set<string>();\n\n/**\n * Checks if all params from source exist with same values in target.\n * Extracted for cognitive complexity reduction.\n * Small function body allows V8 inlining.\n */\nfunction paramsMatch(source: Params, target: Params): boolean {\n for (const key in source) {\n if (source[key] !== target[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Checks params match, skipping keys present in skipKeys.\n */\nfunction paramsMatchExcluding(\n source: Params,\n target: Params,\n skipKeys: Params,\n): boolean {\n for (const key in source) {\n if (key in skipKeys) {\n continue;\n }\n if (source[key] !== target[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Adds route query and state inspection capabilities to a router instance.\n * Handles route activity checks, route relationships, node update predicates, and cloning.\n *\n * @returns Function to enhance router with query capabilities\n */\nexport function withRouteQuery<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n /**\n * Checks if a route is currently active.\n *\n * Optimized implementation that avoids creating State objects and\n * traversing the route tree when possible.\n *\n * @param name - Route name to check\n * @param params - Route parameters to match\n * @param strictEquality - Whether to require exact match (default: false)\n * @param ignoreQueryParams - Whether to ignore query parameters (default: true)\n * @returns True if route is active, false otherwise\n * @throws {TypeError} If name is not a valid route name or params are invalid\n *\n * @example\n * // Check if specific user view is active\n * router.isActiveRoute('users.view', { id: '123' });\n */\n router.isActiveRoute = (\n name: string,\n params: Params = {},\n strictEquality = false,\n ignoreQueryParams = true,\n ): boolean => {\n // Fast path: skip regex validation for already-validated route names\n // Saves ~40ns per call (regex validation cost)\n if (!validatedRouteNames.has(name)) {\n validateRouteName(name, \"isActiveRoute\");\n validatedRouteNames.add(name);\n }\n\n validateParams(params, \"isActiveRoute\");\n\n // Validate boolean parameters (prevent truthy/falsy coercion bugs)\n // These checks are for JavaScript users who may pass non-boolean values\n /* eslint-disable @typescript-eslint/no-unnecessary-condition -- JS runtime guards */\n if (strictEquality !== undefined && typeof strictEquality !== \"boolean\") {\n throw new TypeError(\n `[router.isActiveRoute] strictEquality must be a boolean, got ${typeof strictEquality}`,\n );\n }\n if (\n ignoreQueryParams !== undefined &&\n typeof ignoreQueryParams !== \"boolean\"\n ) {\n throw new TypeError(\n `[router.isActiveRoute] ignoreQueryParams must be a boolean, got ${typeof ignoreQueryParams}`,\n );\n }\n /* eslint-enable @typescript-eslint/no-unnecessary-condition */\n\n // Warn about empty string usage (likely a bug)\n // Root node (\"\") is not considered a parent of any named route\n if (name === \"\") {\n logger.warn(\n \"real-router\",\n 'isActiveRoute(\"\") called with empty string. ' +\n \"The root node is not considered active for any named route. \" +\n \"To check if router has active state, use: router.getState() !== undefined\",\n );\n\n return false;\n }\n\n const activeState = router.getState();\n\n // Early return if no active state\n if (!activeState) {\n return false;\n }\n\n const activeName = activeState.name;\n\n // Fast path: check if routes are related before any expensive operations\n // Routes are related if: equal, or one is ancestor of the other\n if (\n activeName !== name &&\n !activeName.startsWith(`${name}.`) &&\n !name.startsWith(`${activeName}.`)\n ) {\n return false;\n }\n\n // Get defaultParams once (may be undefined at runtime)\n // Cast needed because Record<string, Params> doesn't include undefined for missing keys\n const defaultParams = getConfig(router).defaultParams[name] as\n | Params\n | undefined;\n\n // Exact match case (strictEquality or same name)\n if (strictEquality || activeName === name) {\n // Optimize: only create merged object if defaultParams exist\n const effectiveParams = defaultParams\n ? { ...defaultParams, ...params }\n : params;\n\n // Use areStatesEqual for proper param comparison\n // Create minimal state object (without buildPath - the expensive part)\n const targetState: State = {\n name,\n params: effectiveParams,\n path: \"\", // Not used for comparison\n };\n\n return router.areStatesEqual(targetState, activeState, ignoreQueryParams);\n }\n\n // Hierarchical check: activeState is a descendant of target (name)\n // At this point we know: activeName.startsWith(`${name}.`)\n // Check that all target params are present in activeState\n const activeParams = activeState.params;\n\n if (!paramsMatch(params, activeParams)) {\n return false;\n }\n\n // Check defaultParams (skip keys already in params)\n return (\n !defaultParams ||\n paramsMatchExcluding(defaultParams, activeParams, params)\n );\n };\n\n /**\n * Creates a predicate function to check if a route node should be updated.\n * Used internally by the transition system and integrations.\n *\n * @param nodeName - Route node name to check\n * @returns Predicate function for update checking\n * @throws {TypeError} If nodeName is not a string\n */\n router.shouldUpdateNode = (nodeName: string) => {\n // Validate nodeName type (can come from user code via React props)\n if (!isString(nodeName)) {\n throw new TypeError(\n `[router.shouldUpdateNode] nodeName must be a string, got ${typeof nodeName}`,\n );\n }\n // No need to validate node existence. Non-existent nodes correctly return false as they won't be in intersection, toActivate, or toDeactivate arrays\n\n return (toState: State, fromState?: State): boolean => {\n // Validate toState is state like obj\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!(toState && typeof toState === \"object\" && \"name\" in toState)) {\n throw new TypeError(\n \"[router.shouldUpdateNode] toState must be valid State object\",\n );\n }\n\n // Force update all nodes when reload option is set\n if (toState.meta?.options.reload) {\n return true;\n }\n\n // Root node should always update on initial navigation\n if (nodeName === DEFAULT_ROUTE_NAME && !fromState) {\n return true;\n }\n\n const { intersection, toActivate, toDeactivate } = getTransitionPath(\n toState,\n fromState,\n );\n\n // Update node at the boundary where paths diverge\n if (nodeName === intersection) {\n return true;\n }\n\n // Check if node is being activated\n if (toActivate.includes(nodeName)) {\n return true;\n }\n\n // Check if node is being deactivated\n return toDeactivate.includes(nodeName);\n };\n };\n\n /**\n * Creates an independent clone of this router with the same configuration.\n *\n * The clone inherits routes, options, middleware, plugins, lifecycle handlers,\n * and config (decoders, encoders, defaultParams, forwardMap), but NOT:\n * - Current state (clone starts unstarted with no active state)\n * - Event listeners/subscribers\n * - Original dependencies (must be passed explicitly)\n *\n * @param dependencies - New dependencies for the cloned router (default: empty object).\n * Original router's dependencies are NOT copied automatically.\n * To copy them: `router.clone(router.getDependencies())`\n * @returns A new independent router instance\n *\n * @example\n * ```typescript\n * // SSR: isolated router per request\n * const requestRouter = baseRouter.clone();\n * requestRouter.start(req.url);\n *\n * // Testing: fresh router with mock dependencies\n * const testRouter = router.clone({ api: mockApi });\n *\n * // Chain cloning is supported\n * const clone2 = clone1.clone();\n * ```\n *\n * @remarks\n * **Limitations:**\n *\n * 1. **Symbol-keyed dependencies are not copied.**\n * The clone uses `for...in` iteration which skips Symbol keys.\n * ```typescript\n * const sym = Symbol('secret');\n * router.clone({ [sym]: value }); // sym will be ignored\n * ```\n *\n * 2. **Functions in `defaultParams` will throw.**\n * The `Params` type excludes functions, but if bypassed via `as any`,\n * `structuredClone` will throw `DataCloneError`.\n * ```typescript\n * // TypeScript prevents this (TS2322), but if bypassed:\n * router.config.defaultParams.x = { fn: () => {} } as any;\n * router.clone(); // throws DataCloneError\n * ```\n *\n * 3. **Middleware/plugin factories are shared references.**\n * State created inside `(router) => { ... }` is isolated per router.\n * State in outer closures is shared between original and clones.\n */\n router.clone = (dependencies = {} as Dependencies): Router<Dependencies> => {\n const tree = getRouteTree(router);\n\n // Convert tree back to definitions and build cloned router\n const clonedRouter = createRouter<Dependencies>(\n routeTreeToDefinitions(tree) as Route<Dependencies>[],\n router.getOptions(),\n dependencies,\n );\n\n // Copy middleware factories\n clonedRouter.useMiddleware(...router.getMiddlewareFactories());\n\n // Copy plugin factories\n clonedRouter.usePlugin(...router.getPlugins());\n\n // Copy config with proper depth:\n // - decoders/encoders: shallow (functions can't be cloned)\n // - defaultParams: deep (may contain nested objects)\n // - forwardMap: shallow (primitive string values only)\n const originalConfig = getConfig(router);\n\n setConfig(clonedRouter, {\n decoders: { ...originalConfig.decoders },\n encoders: { ...originalConfig.encoders },\n defaultParams: structuredClone(originalConfig.defaultParams),\n forwardMap: { ...originalConfig.forwardMap },\n });\n\n // Copy resolved forward map (stored in Symbol)\n // TODO(RFC-8): Replace with CacheManager copy logic\n setResolvedForwardMap(clonedRouter, { ...getResolvedForwardMap(router) });\n\n // Copy lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n router.getLifecycleFactories();\n\n for (const name of Object.keys(canDeactivateFactories)) {\n clonedRouter.canDeactivate(name, canDeactivateFactories[name]);\n }\n\n for (const name of Object.keys(canActivateFactories)) {\n clonedRouter.canActivate(name, canActivateFactories[name]);\n }\n\n return clonedRouter;\n };\n\n return router;\n}\n","// packages/real-router/modules/core/routes/routeTree.ts\n\nimport { logger } from \"logger\";\nimport {\n createRouteTree,\n getSegmentsByName,\n hasSegmentsByName,\n nodeToDefinition,\n validateRoute,\n} from \"route-tree\";\nimport { validateRouteName } from \"type-guards\";\n\nimport {\n createApplyForwardToUpdate,\n createClearRouteConfigurations,\n createEnrichRoute,\n getRequiredParams,\n registerAllRouteHandlers,\n removeFromDefinitions,\n resolveForwardChain,\n sanitizeRoute,\n updateConfigEntry,\n validateAndCacheForwardMap,\n validateForwardToTargets,\n validateRouteProperties,\n} from \"./routeConfig\";\nimport { ROUTE_DEFINITIONS_SYMBOL, ROOT_PATH_SYMBOL } from \"../../constants\";\nimport {\n getConfig,\n getRouteTree,\n setRouteTree,\n setResolvedForwardMap,\n} from \"../../internals\";\n\nimport type { Router, Route, DefaultDependencies } from \"core-types\";\nimport type { RouteDefinition, RouteTree } from \"route-tree\";\n\n// Constants\nconst DEFAULT_ROUTE_NAME = \"\";\n\n// =============================================================================\n// Validation Helpers (extracted to reduce cognitive complexity)\n// =============================================================================\n\n/**\n * Gets the type description for error messages.\n */\nfunction getTypeDescription(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n return typeof value;\n}\n\n/**\n * Validates that updates is a plain object.\n *\n * @throws {TypeError} If updates is not a plain object\n */\nfunction validateUpdatesObject(updates: unknown): void {\n if (\n updates === null ||\n typeof updates !== \"object\" ||\n Array.isArray(updates)\n ) {\n throw new TypeError(\n `[real-router] updateRoute: updates must be an object, got ${getTypeDescription(updates)}`,\n );\n }\n}\n\n/**\n * Validates that defaultParams is an object or null.\n *\n * @throws {TypeError} If defaultParams is not an object or null\n */\nfunction validateDefaultParams(defaultParams: unknown): void {\n if (\n defaultParams !== undefined &&\n defaultParams !== null &&\n (typeof defaultParams !== \"object\" || Array.isArray(defaultParams))\n ) {\n throw new TypeError(\n `[real-router] updateRoute: defaultParams must be an object or null, got ${getTypeDescription(defaultParams)}`,\n );\n }\n}\n\n/**\n * Validates a params transformer function (decodeParams/encodeParams).\n *\n * @throws {TypeError} If value is not a function, null, or is async\n */\nfunction validateParamsTransformer(\n value: unknown,\n fieldName: \"decodeParams\" | \"encodeParams\",\n): void {\n if (value === undefined || value === null) {\n return;\n }\n\n if (typeof value !== \"function\") {\n throw new TypeError(\n `[real-router] updateRoute: ${fieldName} must be a function or null, got ${typeof value}`,\n );\n }\n\n // Async functions break matchPath/buildPath (they return Promise instead of Params)\n if (value.constructor.name === \"AsyncFunction\") {\n throw new TypeError(\n `[real-router] updateRoute: ${fieldName} cannot be an async function`,\n );\n }\n}\n\n/**\n * Adds route tree management capabilities to a router instance.\n * Handles route tree construction, addition, and removal.\n *\n * @param routes - Initial routes array\n * @returns Function to enhance router with route tree capabilities\n */\nexport function withRouteTree<Dependencies extends DefaultDependencies>(\n routes: Route<Dependencies>[],\n): (router: Router<Dependencies>) => Router<Dependencies> {\n return (router: Router<Dependencies>): Router<Dependencies> => {\n /**\n * Clears all configurations associated with a route and its children.\n * Created from factory with router bound.\n */\n const clearRouteConfigurations = createClearRouteConfigurations(router);\n\n /**\n * Validates and applies forwardTo update for a route.\n * Created from factory with forwardMap bound.\n */\n const applyForwardToUpdate = createApplyForwardToUpdate(\n getConfig(router).forwardMap,\n );\n\n /**\n * @deprecated Will be removed in next version.\n * Use `forwardTo` property in route configuration instead.\n *\n * @param fromRoute - Source route name\n * @param toRoute - Target route name\n * @returns Router instance for chaining\n * @throws {Error} If target route requires parameters not available in source route\n */\n router.forward = (fromRoute, toRoute) => {\n logger.warn(\n \"router.forward\",\n \"Method is deprecated. Use `forwardTo` property in route configuration instead.\",\n );\n\n // Get route tree for validation\n const tree = getRouteTree(router);\n\n // Validate source route exists\n const fromSegments = getSegmentsByName(tree, fromRoute);\n\n if (!fromSegments) {\n throw new Error(\n `[real-router] forward: source route \"${fromRoute}\" does not exist`,\n );\n }\n\n // Validate target route exists\n const toSegments = getSegmentsByName(tree, toRoute);\n\n if (!toSegments) {\n throw new Error(\n `[real-router] forward: target route \"${toRoute}\" does not exist`,\n );\n }\n\n // Validate target route doesn't require params not in source\n const fromParams = getRequiredParams(fromSegments);\n const toParams = getRequiredParams(toSegments);\n const missingParams: string[] = [];\n\n for (const param of toParams) {\n if (!fromParams.has(param)) {\n missingParams.push(param);\n }\n }\n\n if (missingParams.length > 0) {\n throw new Error(\n `[real-router] forward: target route \"${toRoute}\" requires params ` +\n `[${missingParams.join(\", \")}] that are not available in source route \"${fromRoute}\"`,\n );\n }\n\n getConfig(router).forwardMap[fromRoute] = toRoute;\n\n // Revalidate and cache after manual forward addition\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n // Internal state: route definitions and root path\n type RouterInternal = Record<symbol, RouteDefinition[] | string>;\n const routerInternal = router as RouterInternal;\n\n // Initialize route definitions and tree\n // Sanitize routes to store only essential properties (name, path, children)\n const routeDefinitions: RouteDefinition[] = routes.map((route) =>\n sanitizeRoute(route),\n );\n\n // Initialize root path (can be changed later via setRootPath)\n routerInternal[ROOT_PATH_SYMBOL] = \"\";\n\n setRouteTree(\n router,\n createRouteTree(\n DEFAULT_ROUTE_NAME,\n routerInternal[ROOT_PATH_SYMBOL],\n routeDefinitions,\n ),\n );\n\n // Initialize resolved forward map cache\n // TODO(RFC-8): Replace with CacheManager.getInstance().setResolvedForwardMap(router, {})\n setResolvedForwardMap(router, {});\n\n // Store definitions for dynamic addition\n routerInternal[ROUTE_DEFINITIONS_SYMBOL] = routeDefinitions;\n\n // Register handlers for all routes\n registerAllRouteHandlers(routes, router);\n\n // Validate and cache forwardTo chains\n validateAndCacheForwardMap(router);\n\n /**\n * Rebuilds the route tree from given definitions.\n *\n * @param definitions - Route definitions to build from\n * @param skipValidation - Skip validation if routes are pre-validated\n */\n function rebuildTree(\n definitions: readonly RouteDefinition[],\n skipValidation = false,\n ): void {\n const rootPath = routerInternal[ROOT_PATH_SYMBOL] as string;\n\n setRouteTree(\n router,\n createRouteTree(DEFAULT_ROUTE_NAME, rootPath, definitions, {\n skipValidation,\n }),\n );\n }\n\n /**\n * Gets the current route tree.\n */\n function getTree(): RouteTree {\n return getRouteTree(router);\n }\n\n /**\n * Validates a batch of routes before adding them.\n * Checks structure, duplicates, and forwardTo targets.\n */\n function validateRouteBatch(routesToAdd: Route<Dependencies>[]): void {\n const seenNames = new Set<string>();\n const seenPathsByParent = new Map<string, Set<string>>();\n\n for (const route of routesToAdd) {\n validateRoute(\n route,\n \"addRoute\",\n getTree(),\n \"\",\n seenNames,\n seenPathsByParent,\n );\n validateRouteProperties(route, route.name);\n }\n\n validateForwardToTargets(\n routesToAdd,\n getConfig(router).forwardMap,\n getTree(),\n );\n }\n\n /**\n * Adds one or more routes to the router tree.\n * Routes are sorted immediately after addition.\n *\n * @param addedRoutes - Route or array of routes to add\n * @returns Router instance for chaining\n * @throws {TypeError} If route structure is invalid\n * @throws {Error} If route already exists or duplicate in batch\n *\n * @example\n * // Single route\n * router.addRoute({ name: 'users', path: '/users' });\n *\n * @example\n * // Multiple routes - prefer batch over loop\n * router.addRoute([\n * { name: 'users', path: '/users' },\n * { name: 'users.view', path: '/:id' }\n * ]);\n */\n router.addRoute = (addedRoutes) => {\n const routesToAdd = Array.isArray(addedRoutes)\n ? [...addedRoutes]\n : [addedRoutes];\n\n // Phase 1: Pre-validation (all routes validated BEFORE any modification)\n validateRouteBatch(routesToAdd);\n\n // Phase 2: Add to definitions and register handlers\n for (const route of routesToAdd) {\n routeDefinitions.push(sanitizeRoute(route));\n }\n\n registerAllRouteHandlers(routesToAdd, router);\n\n // Phase 3: Rebuild tree\n rebuildTree(routeDefinitions, true);\n\n // Phase 4: Validate and cache forwardTo chains\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n /**\n * Removes a route and all its children from the router.\n * Clears all associated configurations, handlers and rebuilds the tree.\n *\n * @param name - Route name to remove (supports dot notation for nested routes)\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a valid route name\n *\n * @example\n * // Remove top-level route\n * router.removeRoute('users');\n *\n * @example\n * // Remove nested route (parent remains)\n * router.removeRoute('users.edit');\n */\n router.removeRoute = (name: string): Router<Dependencies> => {\n validateRouteName(name, \"removeRoute\");\n\n // Check if trying to remove currently active route (or its parent)\n const currentState = router.getState();\n\n if (currentState) {\n const currentName = currentState.name;\n const isExactMatch = currentName === name;\n const isParentOfCurrent = currentName.startsWith(`${name}.`);\n\n if (isExactMatch || isParentOfCurrent) {\n const suffix = isExactMatch ? \"\" : ` (current: \"${currentName}\")`;\n\n logger.warn(\n \"router.removeRoute\",\n `Cannot remove route \"${name}\" — it is currently active${suffix}. Navigate away first.`,\n );\n\n return router;\n }\n }\n\n // Edge case: Warn if navigation is in progress\n // We warn but don't block because we can't determine if this specific route\n // is the navigation target. After FSM migration (RFC-2), this will be improved\n // with RouterState.TRANSITIONING that tracks the target route.\n if (router.isNavigating()) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" removed while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n // Try to remove from definitions\n const wasRemoved = removeFromDefinitions(routeDefinitions, name);\n\n if (!wasRemoved) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" not found. No changes made.`,\n );\n\n return router;\n }\n\n // Clear configurations for removed route\n clearRouteConfigurations(name);\n\n // Rebuild tree with updated definitions\n rebuildTree(routeDefinitions, true);\n\n // Revalidate and cache forwardTo chains after removal\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n /**\n * Clears all routes from the router.\n * Removes all route definitions, configurations, and lifecycle handlers.\n * Preserves: listeners, plugins, dependencies, options, state.\n *\n * @returns Router instance for chaining\n *\n * @example\n * // Clear all routes and add new ones\n * router.clearRoutes().addRoute([\n * { name: 'home', path: '/' },\n * { name: 'about', path: '/about' }\n * ]);\n */\n router.clearRoutes = (): Router<Dependencies> => {\n if (router.isNavigating()) {\n logger.error(\n \"router.clearRoutes\",\n \"Cannot clear routes while navigation is in progress. Wait for navigation to complete.\",\n );\n\n return router;\n }\n\n // Clear all route definitions\n routeDefinitions.length = 0;\n\n const config = getConfig(router);\n\n // Clear all config entries (for...in avoids O(K) array allocation)\n for (const key in config.decoders) {\n delete config.decoders[key];\n }\n\n for (const key in config.encoders) {\n delete config.encoders[key];\n }\n\n for (const key in config.defaultParams) {\n delete config.defaultParams[key];\n }\n\n for (const key in config.forwardMap) {\n delete config.forwardMap[key];\n }\n\n // Clear all lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n router.getLifecycleFactories();\n\n for (const name in canActivateFactories) {\n router.clearCanActivate(name, true);\n }\n\n for (const name in canDeactivateFactories) {\n router.clearCanDeactivate(name, true);\n }\n\n // Clear router state since all routes are removed\n router.setState(undefined);\n\n // Rebuild empty tree\n rebuildTree(routeDefinitions, true);\n\n // Clear forward cache\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n /**\n * Retrieves a route by name with all its configuration.\n * Returns the full Route object reconstructed from internal storage.\n *\n * @param name - Route name (supports dot notation for nested routes)\n * @returns Route object with all properties, or undefined if not found\n * @throws {TypeError} If name is not a valid route name\n *\n * @example\n * // Get a top-level route\n * const usersRoute = router.getRoute('users');\n *\n * @example\n * // Get a nested route\n * const profileRoute = router.getRoute('users.profile');\n */\n router.getRoute = (name: string): Route<Dependencies> | undefined => {\n validateRouteName(name, \"getRoute\");\n\n const tree = getTree();\n const segments = getSegmentsByName(tree, name);\n\n if (!segments) {\n return undefined;\n }\n\n // Get the last segment (the target route)\n // segments is guaranteed to have at least one element here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const targetNode = segments.at(-1)!;\n const definition = nodeToDefinition(targetNode);\n\n // Get lifecycle factories for enrichment\n const [, canActivateFactories] = router.getLifecycleFactories();\n\n // Create enrichRoute function with bound config and factories\n const enrichRoute = createEnrichRoute(\n getConfig(router),\n canActivateFactories,\n );\n\n return enrichRoute(definition, name);\n };\n\n /**\n * Checks if a route exists in the router.\n *\n * @param name - Route name (supports dot notation for nested routes)\n * @returns true if route exists, false otherwise\n * @throws {TypeError} If name is not a valid route name\n */\n router.hasRoute = (name: string): boolean => {\n validateRouteName(name, \"hasRoute\");\n\n const tree = getTree();\n\n return hasSegmentsByName(tree, name);\n };\n\n /**\n * Updates a route's configuration without rebuilding the route tree.\n * Only updates specified properties; unspecified properties remain unchanged.\n * Use `null` to remove a property.\n *\n * @param name - Route name (supports dot notation for nested routes)\n * @param updates - Configuration updates to apply\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a valid route name\n * @throws {ReferenceError} If route does not exist\n * @throws {Error} If forwardTo target doesn't exist or creates cycle\n *\n * @example\n * // Add forwardTo\n * router.updateRoute('old', { forwardTo: 'new' });\n *\n * @example\n * // Remove forwardTo\n * router.updateRoute('old', { forwardTo: null });\n *\n * @example\n * // Update multiple properties\n * router.updateRoute('users', {\n * defaultParams: { page: 1 },\n * canActivate: authGuardFactory\n * });\n */\n router.updateRoute = (name, updates) => {\n validateRouteName(name, \"updateRoute\");\n\n // Validate updates is a plain object (JS runtime guard)\n validateUpdatesObject(updates);\n\n const tree = getTree();\n const segments = getSegmentsByName(tree, name);\n\n if (!segments) {\n throw new ReferenceError(\n `[real-router] updateRoute: route \"${name}\" does not exist`,\n );\n }\n\n // Warn if modifying config during navigation\n // Changes apply immediately but may cause inconsistent behavior\n if (router.isNavigating()) {\n logger.error(\n \"router.updateRoute\",\n `Route \"${name}\" config modified while navigation is in progress. ` +\n \"Changes will apply immediately and may affect the current transition.\",\n );\n }\n\n const config = getConfig(router);\n\n // Cache all property values upfront to protect against mutating getters\n // This ensures consistent behavior regardless of getter side effects\n const {\n forwardTo,\n defaultParams,\n decodeParams,\n encodeParams,\n canActivate,\n } = updates;\n\n // ============================================================\n // PHASE 1: VALIDATION (all validations before any mutations)\n // This ensures atomicity - either all updates apply or none do\n // ============================================================\n\n // Validate forwardTo (check target exists and no cycles)\n if (forwardTo !== undefined && forwardTo !== null) {\n // Check for indirect cycles BEFORE mutation\n // This prevents forwardMap corruption when cycle is detected\n const testMap = {\n ...config.forwardMap,\n [name]: forwardTo,\n };\n\n resolveForwardChain(name, testMap);\n }\n\n // Validate property types\n validateDefaultParams(defaultParams);\n validateParamsTransformer(decodeParams, \"decodeParams\");\n validateParamsTransformer(encodeParams, \"encodeParams\");\n\n // ============================================================\n // PHASE 2: MUTATION (all mutations after validations pass)\n // ============================================================\n\n // Apply forwardTo\n if (forwardTo !== undefined) {\n if (forwardTo === null) {\n delete config.forwardMap[name];\n } else {\n applyForwardToUpdate(name, forwardTo, segments, tree);\n }\n\n validateAndCacheForwardMap(router);\n }\n\n // Apply config entries\n updateConfigEntry(config.defaultParams, name, defaultParams);\n updateConfigEntry(config.decoders, name, decodeParams);\n updateConfigEntry(config.encoders, name, encodeParams);\n\n // Handle canActivate (uses different API)\n if (canActivate !== undefined) {\n if (canActivate === null) {\n router.clearCanActivate(name, true);\n } else {\n router.canActivate(name, canActivate);\n }\n }\n\n return router;\n };\n\n return router;\n };\n}\n","// packages/real-router/modules/core/routes.ts\n\nimport { withRoutePath } from \"./routePath\";\nimport { withRouteQuery } from \"./routeQuery\";\nimport { withRouteTree } from \"./routeTree\";\n\nimport type { Router, Route, DefaultDependencies } from \"core-types\";\n\n/**\n * Adds comprehensive route management capabilities to a router instance.\n * Orchestrates route tree operations, path building/matching, and state queries.\n *\n * This is a composition of specialized modules:\n * - withRouteTree: Route tree construction, addition, and removal\n * - withRoutePath: URL path building and matching\n * - withRouteQuery: Route activity checks and state inspection\n *\n * @param routes - Initial routes array\n * @returns Function to enhance router with route capabilities\n */\nexport function withRoutes<Dependencies extends DefaultDependencies>(\n routes: Route<Dependencies>[],\n): (router: Router<Dependencies>) => Router<Dependencies> {\n return (router: Router<Dependencies>): Router<Dependencies> => {\n // eslint-disable-next-line unicorn/no-array-reduce\n return [withRouteTree(routes), withRoutePath, withRouteQuery].reduce(\n (r, fn) => fn(r),\n router,\n );\n };\n}\n","// packages/real-router/modules/core/state.ts\n\nimport { logger } from \"logger\";\nimport { getSegmentsByName } from \"route-tree\";\nimport {\n isNavigationOptions,\n isParams,\n isString,\n validateState,\n getTypeDescription,\n} from \"type-guards\";\n\nimport { constants } from \"@real-router/core\";\n\nimport { freezeStateInPlace } from \"../helpers\";\nimport { getConfig, getResolvedForwardMap, getRouteTree } from \"../internals\";\nimport { createRouteState } from \"./stateBuilder\";\n\nimport type {\n BuildStateResultWithSegments,\n DefaultDependencies,\n NavigationOptions,\n Params,\n Router,\n SimpleState,\n State,\n StateMetaInput,\n} from \"core-types\";\nimport type { RouteTree, RouteTreeState, RouteTreeStateMeta } from \"route-tree\";\n\n/**\n * Extracts URL param names from RouteTreeStateMeta.\n * This is an O(segments × params) operation but avoids tree traversal.\n *\n * @param meta - RouteTreeStateMeta containing param sources\n * @returns Array of URL param names\n *\n * @internal\n */\nfunction getUrlParamsFromMeta(meta: RouteTreeStateMeta): string[] {\n const urlParams: string[] = [];\n\n // meta structure: { \"segment1\": { param1: \"url\", param2: \"query\" }, ... }\n // Optimization: use for...in instead of Object.entries to avoid array allocation\n for (const segmentName in meta) {\n const paramMap = meta[segmentName];\n\n for (const param in paramMap) {\n if (paramMap[param] === \"url\") {\n urlParams.push(param);\n }\n }\n }\n\n return urlParams;\n}\n\n/**\n * Compares two parameter values for equality.\n * Supports deep equality for arrays (common in route params like tags, ids).\n *\n * @param val1 - First value\n * @param val2 - Second value\n * @returns True if values are equal\n */\nfunction areParamValuesEqual(val1: unknown, val2: unknown): boolean {\n // Fast path: strict equality for primitives and same references\n if (val1 === val2) {\n return true;\n }\n\n // Deep equality for arrays\n if (Array.isArray(val1) && Array.isArray(val2)) {\n if (val1.length !== val2.length) {\n return false;\n }\n\n return val1.every((v, i) => areParamValuesEqual(v, val2[i]));\n }\n\n // Different types or non-equal non-arrays\n return false;\n}\n\n/**\n * Enhances router with state management capabilities.\n *\n * Provides methods for getting, setting, and comparing route states.\n * Implements frozen state caching for performance optimization.\n *\n * @param router - Router instance to enhance\n * @returns Enhanced router with state management methods\n *\n * @internal This is a router enhancement function, not meant for direct use.\n */\nexport function withState<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n // Auto-incrementing state ID for tracking navigation history\n let stateId = 0;\n // Cached frozen state - avoids structuredClone on every getState() call\n let frozenState: State | undefined = undefined;\n // Previous state before the last setState call\n let previousState: State | undefined = undefined;\n\n // Lazy accessor for route tree (set by withRoutes, which runs after withState)\n const getTree = (): RouteTree => getRouteTree(router);\n\n // Cache for urlParams to avoid repeated route tree traversal\n // Key: route name, Value: array of URL param names\n const urlParamsCache = new Map<string, string[]>();\n\n const getUrlParams = (name: string): string[] => {\n // Check cache first\n const cached = urlParamsCache.get(name);\n\n if (cached !== undefined) {\n return cached;\n }\n\n // Compute and cache\n const segments = getSegmentsByName(getTree(), name);\n\n if (!segments) {\n // Cache empty result for non-existent routes\n urlParamsCache.set(name, []);\n\n return [];\n }\n\n const result = segments.flatMap((segment) =>\n /* v8 ignore next -- @preserve segments always have parsers */\n segment.parser ? segment.parser.urlParams : [],\n );\n\n urlParamsCache.set(name, result);\n\n return result;\n };\n\n /**\n * Returns the current router state.\n *\n * The returned state is deeply frozen (immutable) for safety.\n * Returns `undefined` if the router has not been started or has been stopped.\n *\n * @template P - Type of route parameters\n * @template MP - Type of meta parameters (URL vs query param sources)\n * @returns Current frozen state or undefined\n *\n * @example\n * ```typescript\n * const state = router.getState();\n * if (state) {\n * console.log(state.name, state.params);\n * }\n * ```\n */\n router.getState = <P extends Params = Params, MP extends Params = Params>():\n | State<P, MP>\n | undefined => {\n return frozenState as State<P, MP> | undefined;\n };\n\n /**\n * Sets the current router state.\n *\n * The state is deeply frozen before storage to ensure immutability.\n * The previous state is preserved and accessible via `getPreviousState()`.\n *\n * @param state - New state to set, or undefined to clear\n *\n * @remarks\n * This is primarily used internally by the navigation system.\n * Direct usage should be rare and careful.\n *\n * @example\n * ```typescript\n * // Used internally after successful navigation\n * router.setState(newState);\n *\n * // Clear state (e.g., on router.stop())\n * router.setState(undefined);\n * ```\n */\n router.setState = (state: State | undefined) => {\n // Validate state structure if provided\n if (state !== undefined) {\n validateState(state, \"router.setState\");\n }\n\n // Preserve current state as previous before updating\n previousState = frozenState;\n // If state is already frozen (from makeState()), use it directly.\n // For external states, freeze in place without cloning.\n // This allows Proxy states and avoids structuredClone overhead.\n if (!state) {\n frozenState = undefined;\n } else if (Object.isFrozen(state)) {\n // State is already frozen (typically from makeState)\n frozenState = state;\n } else {\n // External state - freeze in place without cloning.\n // Uses Object.freeze recursively, allowing Proxy objects and\n // preserving Symbol/function values in meta.options.\n frozenState = freezeStateInPlace(state);\n }\n };\n\n /**\n * Returns the previous router state (before the last navigation).\n *\n * Useful for implementing \"back\" functionality or transition animations.\n * The returned state is deeply frozen (immutable).\n *\n * @template P - Type of route parameters\n * @template MP - Type of meta parameters\n * @returns Previous frozen state or undefined if no previous navigation\n *\n * @example\n * ```typescript\n * router.navigate('users');\n * router.navigate('settings');\n *\n * const prev = router.getPreviousState();\n * console.log(prev?.name); // 'users'\n * ```\n */\n router.getPreviousState = <\n P extends Params = Params,\n MP extends Params = Params,\n >(): State<P, MP> | undefined => {\n return previousState as State<P, MP> | undefined;\n };\n\n /**\n * Creates a route state object.\n *\n * @template P - Type of route parameters. MUST include all properties from\n * route.defaultParams for proper type safety.\n * @template MP - Type of meta parameters (URL params)\n *\n * @param name - Route name\n * @param params - Route parameters (merged with defaultParams)\n * @param path - URL path (auto-built if not provided)\n * @param meta - State metadata\n * @param forceId - Force specific state ID\n * @returns Route state object\n *\n * @remarks\n * **Type Contract:**\n * The `params` result includes properties from `route.defaultParams`.\n * For correct typing, ensure that `P` includes all defaultParams properties:\n *\n * @example\n * ```typescript\n * // Route definition\n * { name: \"users\", path: \"/users\", defaultParams: { page: 1, limit: 10 } }\n *\n * // Correct usage — P includes defaultParams properties\n * type UsersParams = { page: number; limit: number; filter?: string };\n * router.makeState<UsersParams>('users', { page: 2, limit: 20 });\n *\n * // Incorrect usage — P missing defaultParams properties\n * type BadParams = { filter: string }; // Missing page, limit!\n * router.makeState<BadParams>('users', { filter: 'active' });\n * // Runtime: state.params = { page: 1, limit: 10, filter: 'active' }\n * // TypeScript: state.params = { filter: 'active' } — type mismatch!\n * ```\n */\n router.makeState = <P extends Params = Params, MP extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: StateMetaInput<MP>,\n forceId?: number,\n ): State<P, MP> => {\n // Validate name is a string\n if (!isString(name)) {\n throw new TypeError(\n `[router.makeState] Invalid name: ${getTypeDescription(name)}. Expected string.`,\n );\n }\n\n // Validate params if provided\n if (params !== undefined && !isParams(params)) {\n throw new TypeError(\n `[router.makeState] Invalid params: ${getTypeDescription(params)}. Expected plain object.`,\n );\n }\n\n // Validate path if provided\n if (path !== undefined && !isString(path)) {\n throw new TypeError(\n `[router.makeState] Invalid path: ${getTypeDescription(path)}. Expected string.`,\n );\n }\n\n // Validate forceId if provided\n if (forceId !== undefined && typeof forceId !== \"number\") {\n throw new TypeError(\n `[router.makeState] Invalid forceId: ${getTypeDescription(forceId)}. Expected number.`,\n );\n }\n\n const madeMeta = meta\n ? {\n ...meta,\n id: forceId ?? ++stateId,\n params: meta.params,\n options: meta.options,\n redirected: meta.redirected,\n }\n : undefined;\n\n // Optimization: avoid spreading when no defaultParams exist\n const routerDefaultParams = getConfig(router).defaultParams;\n const hasDefaultParams = Object.hasOwn(routerDefaultParams, name);\n // Contract: P MUST include all properties from defaultParams[name]\n // Note: always spread params when provided to handle Proxy objects correctly\n let mergedParams: P;\n\n if (hasDefaultParams) {\n mergedParams = { ...routerDefaultParams[name], ...params } as P;\n } else if (params) {\n mergedParams = { ...params };\n } else {\n mergedParams = {} as P;\n }\n\n const state: State<P, MP> = {\n name,\n params: mergedParams,\n path: path ?? router.buildPath(name, params),\n // write guard is meta\n meta: madeMeta,\n };\n\n // Freeze state immediately after creation for immutability guarantee.\n // This eliminates need for deepFreezeState in invokeEventListeners.\n return freezeStateInPlace(state);\n };\n\n /**\n * Creates a state for an unmatched (404) route.\n *\n * Used when no route matches the requested path.\n * The state name is set to `constants.UNKNOWN_ROUTE` (\"@@real-router/UNKNOWN_ROUTE\").\n *\n * @param path - The unmatched URL path\n * @param options - Optional navigation options (reload, replace, etc.)\n * @returns State object representing the unknown route\n *\n * @example\n * ```typescript\n * const notFound = router.makeNotFoundState('/non-existent-page');\n * // { name: '@@real-router/UNKNOWN_ROUTE', params: { path: '/non-existent-page' }, ... }\n * ```\n */\n router.makeNotFoundState = (\n path: string,\n options?: NavigationOptions,\n ): State => {\n // Validate path\n if (!isString(path)) {\n throw new TypeError(\n `[router.makeNotFoundState] Invalid path: ${getTypeDescription(path)}. Expected string.`,\n );\n }\n\n // Validate options if provided\n if (options !== undefined && !isNavigationOptions(options)) {\n throw new TypeError(\n `[router.makeNotFoundState] Invalid options: ${getTypeDescription(options)}. Expected NavigationOptions object.`,\n );\n }\n\n return router.makeState<{ path: string }>(\n constants.UNKNOWN_ROUTE,\n { path },\n path,\n options\n ? {\n options,\n params: {},\n redirected: false,\n }\n : undefined,\n );\n };\n\n /**\n * Compares two states for equality.\n *\n * By default, only URL path parameters are compared (query params ignored).\n * This matches typical navigation behavior where query params don't trigger\n * route change events.\n *\n * **Precondition:** States must be valid State objects (created via makeState, buildState, etc.).\n * No runtime validation is performed for performance reasons.\n *\n * @param state1 - First state to compare\n * @param state2 - Second state to compare\n * @param ignoreQueryParams - If true (default), only compare URL path params\n * @returns True if states are considered equal\n *\n * @example\n * ```typescript\n * // Same route, different query params — considered equal by default\n * router.areStatesEqual(\n * { name: 'users', params: { page: '1' } },\n * { name: 'users', params: { page: '2' } }\n * ); // true (page is a query param)\n *\n * // Compare all params including query params\n * router.areStatesEqual(state1, state2, false);\n * ```\n */\n router.areStatesEqual = (\n state1: State | null | undefined,\n state2: State | null | undefined,\n ignoreQueryParams = true,\n ): boolean => {\n // Handle null/undefined cases: both falsy = equal, one falsy = not equal\n if (!state1 || !state2) {\n return !!state1 === !!state2;\n }\n\n // No runtime validation for performance — states are validated at creation time\n\n // Different route names = definitely not equal\n if (state1.name !== state2.name) {\n return false;\n }\n\n // When ignoring query params, only compare URL path parameters\n // Optimization: use meta.params if available (avoids tree traversal)\n // Note: meta.params is RouteTreeStateMeta, not route params\n if (ignoreQueryParams) {\n // Try to get URL params from state meta (O(segments × params) but no tree lookup)\n // State meta is available when state was created via buildStateWithSegments/makeState\n const stateMeta = (state1.meta?.params ?? state2.meta?.params) as\n | RouteTreeStateMeta\n | undefined;\n\n const urlParams = stateMeta\n ? getUrlParamsFromMeta(stateMeta)\n : getUrlParams(state1.name);\n\n return urlParams.every((param) =>\n areParamValuesEqual(state1.params[param], state2.params[param]),\n );\n }\n\n // Full comparison: check all params from both states\n // Must verify BOTH:\n // 1. Same keys in both objects (not just same length)\n // 2. Same values for each key (with deep equality for arrays)\n const state1Keys = Object.keys(state1.params);\n const state2Keys = Object.keys(state2.params);\n\n // Different number of keys = not equal\n if (state1Keys.length !== state2Keys.length) {\n return false;\n }\n\n // Check that state2 has all keys from state1 AND values are equal\n // This also implicitly checks state1 has all keys from state2\n // (since lengths are equal, if all state1 keys exist in state2, they must be the same set)\n return state1Keys.every(\n (param) =>\n param in state2.params &&\n areParamValuesEqual(state1.params[param], state2.params[param]),\n );\n };\n\n /**\n * Checks if childState is a descendant of parentState in the route hierarchy.\n *\n * @deprecated This method will be removed in the next major version.\n * Use `router.isActiveRoute()` instead for most use cases.\n *\n * @example\n * ```typescript\n * // Instead of:\n * router.areStatesDescendants(parentState, childState);\n *\n * // Use isActiveRoute to check against current state:\n * router.isActiveRoute(parentState.name, parentState.params);\n * ```\n *\n * @param parentState - Potential parent state\n * @param childState - Potential child state\n * @returns True if childState is a descendant of parentState\n */\n router.areStatesDescendants = (\n parentState: State,\n childState: State,\n ): boolean => {\n // Validate states\n validateState(parentState, \"areStatesDescendants\");\n validateState(childState, \"areStatesDescendants\");\n\n logger.warn(\n \"real-router\",\n \"areStatesDescendants is deprecated and will be removed in the next major version. \" +\n \"Use router.isActiveRoute() instead.\",\n );\n\n // Check if childState.name starts with \"parentState.name.\"\n // Using startsWith instead of regex to avoid ReDoS and improve performance\n const parentPrefix = `${parentState.name}.`;\n\n if (!childState.name.startsWith(parentPrefix)) {\n return false;\n }\n\n // If child state name extends parent state name, and all parent state params\n // are in child state params (with deep equality for arrays).\n return Object.keys(parentState.params).every((p) =>\n areParamValuesEqual(parentState.params[p], childState.params[p]),\n );\n };\n\n /**\n * Resolves route forwarding and merges defaultParams.\n *\n * @template P - Type of route parameters. MUST include all properties from\n * defaultParams of both source route and forwarded route.\n *\n * @param routeName - Original route name\n * @param routeParams - Route parameters\n * @returns Resolved route name and merged parameters\n *\n * @remarks\n * **Type Contract:**\n * When using forwardTo, defaultParams from BOTH routes are merged:\n * 1. defaultParams[originalRoute]\n * 2. defaultParams[forwardedRoute]\n * 3. provided routeParams\n *\n * Ensure P includes properties from all sources.\n *\n * @example\n * ```typescript\n * // Route definitions\n * { name: \"old-users\", path: \"/old-users\", forwardTo: \"users\" }\n * { name: \"users\", path: \"/users\", defaultParams: { page: 1 } }\n *\n * router.forwardState(\"old-users\", { filter: \"active\" });\n * // Returns: { name: \"users\", params: { page: 1, filter: \"active\" } }\n * ```\n */\n router.forwardState = <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ): SimpleState<P> => {\n // Validate routeName is a string\n if (!isString(routeName)) {\n throw new TypeError(\n `[router.forwardState] Invalid routeName: ${getTypeDescription(routeName)}. Expected string.`,\n );\n }\n\n // Validate params\n if (!isParams(routeParams)) {\n throw new TypeError(\n `[router.forwardState] Invalid routeParams: ${getTypeDescription(routeParams)}. Expected plain object.`,\n );\n }\n\n // Use cached resolved forwardTo chain (O(1) lookup)\n // TODO(RFC-8): Replace with CacheManager.getInstance().getForwardTarget(router, routeName)\n const resolvedMap = getResolvedForwardMap(router);\n const name = resolvedMap[routeName] ?? routeName;\n const { defaultParams } = getConfig(router);\n\n // Contract: P MUST include all properties from defaultParams of both routes\n // Optimization: avoid spreading when no defaultParams exist\n const hasRouteDefaults = Object.hasOwn(defaultParams, routeName);\n const hasNameDefaults = Object.hasOwn(defaultParams, name);\n\n // Type assertion needed: merged params satisfy P contract per JSDoc\n let params: P;\n\n if (hasRouteDefaults && hasNameDefaults) {\n // Both routes have defaults - need all three spreads\n params = {\n ...defaultParams[routeName],\n ...defaultParams[name],\n ...routeParams,\n } as P;\n } else if (hasRouteDefaults) {\n // Only source route has defaults\n params = { ...defaultParams[routeName], ...routeParams } as P;\n } else if (hasNameDefaults) {\n // Only target route has defaults\n params = { ...defaultParams[name], ...routeParams } as P;\n } else {\n // No defaults - use routeParams directly\n params = routeParams;\n }\n\n return {\n name,\n params,\n };\n };\n\n /**\n * Builds a route tree state from route name and parameters.\n *\n * Resolves forwarding, applies defaultParams, and creates a state\n * with segment metadata. Returns undefined if the route doesn't exist.\n *\n * @template P - Type of route parameters\n * @param routeName - Route name (may be forwarded to another route)\n * @param routeParams - Route parameters\n * @returns Route tree state with segment info, or undefined if route not found\n *\n * @example\n * ```typescript\n * const state = router.buildState('users.view', { id: '123' });\n * if (state) {\n * console.log(state.name, state.params, state.meta);\n * }\n * ```\n */\n router.buildState = <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ): RouteTreeState<P> | undefined => {\n // Validate routeName is a string\n if (!isString(routeName)) {\n throw new TypeError(\n `[router.buildState] Invalid routeName: ${getTypeDescription(routeName)}. Expected string.`,\n );\n }\n\n // Validate params\n if (!isParams(routeParams)) {\n throw new TypeError(\n `[router.buildState] Invalid routeParams: ${getTypeDescription(routeParams)}. Expected plain object.`,\n );\n }\n\n // Resolve forwarding and merge defaultParams\n const { name, params } = router.forwardState(routeName, routeParams);\n\n // Get route segments from the tree\n const segments = getSegmentsByName(getTree(), name);\n\n if (!segments) {\n return undefined;\n }\n\n // Build state with segment metadata (URL vs query param sources)\n return createRouteState({ segments, params }, name);\n };\n\n /**\n * Builds state with segments for internal use.\n * Avoids duplicate getSegmentsByName call when path building is needed.\n *\n * @internal\n */\n router.buildStateWithSegments = <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ): BuildStateResultWithSegments<P> | undefined => {\n // Validate routeName is a string\n if (!isString(routeName)) {\n throw new TypeError(\n `[router.buildStateWithSegments] Invalid routeName: ${getTypeDescription(routeName)}. Expected string.`,\n );\n }\n\n // Validate params\n if (!isParams(routeParams)) {\n throw new TypeError(\n `[router.buildStateWithSegments] Invalid routeParams: ${getTypeDescription(routeParams)}. Expected plain object.`,\n );\n }\n\n // Resolve forwarding and merge defaultParams\n const { name, params } = router.forwardState(routeName, routeParams);\n\n // Get route segments from the tree\n const segments = getSegmentsByName(getTree(), name);\n\n if (!segments) {\n return undefined;\n }\n\n // Build state with segment metadata (URL vs query param sources)\n const state = createRouteState<P>({ segments, params }, name);\n\n return { state, segments };\n };\n\n return router;\n}\n","// packages/real-router/modules/typeGuards.ts\n\n/**\n * Re-export common type guards from centralized type-guards package\n */\nimport type { LoggerConfig, LogLevelConfig } from \"logger\";\n\nexport {\n isObjKey,\n isString,\n isState,\n isParams,\n isNavigationOptions,\n isPromise,\n isBoolean,\n validateRouteName,\n} from \"type-guards\";\n\n/**\n * RealRouter-specific type guards for logger configuration\n */\n\nconst VALID_LEVELS_SET = new Set<string>([\"all\", \"warn-error\", \"error-only\"]);\n\nfunction isValidLevel(value: unknown): value is LogLevelConfig {\n return typeof value === \"string\" && VALID_LEVELS_SET.has(value);\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === \"string\") {\n return `\"${value}\"`;\n }\n if (typeof value === \"object\") {\n return JSON.stringify(value);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return String(value);\n}\n\nexport function isLoggerConfig(config: unknown): config is LoggerConfig {\n if (typeof config !== \"object\" || config === null) {\n throw new TypeError(\"Logger config must be an object\");\n }\n\n const obj = config;\n\n // Check for unknown properties\n for (const key of Object.keys(obj)) {\n if (key !== \"level\" && key !== \"callback\") {\n throw new TypeError(`Unknown logger config property: \"${key}\"`);\n }\n }\n\n // Validate level if present\n if (\"level\" in obj && obj.level !== undefined && !isValidLevel(obj.level)) {\n throw new TypeError(\n `Invalid logger level: ${formatValue(obj.level)}. Expected: \"all\" | \"warn-error\" | \"error-only\"`,\n );\n }\n\n // Validate callback if present\n if (\n \"callback\" in obj &&\n obj.callback !== undefined &&\n typeof obj.callback !== \"function\"\n ) {\n throw new TypeError(\n `Logger callback must be a function, got ${typeof obj.callback}`,\n );\n }\n\n return true;\n}\n","// packages/real-router/modules/createRouter.ts\n\nimport { logger } from \"logger\";\n\nimport { CONFIG_SYMBOL } from \"./constants\";\nimport { withDependencies } from \"./core/dependencies\";\nimport { withMiddleware } from \"./core/middleware\";\nimport { withNavigation } from \"./core/navigation\";\nimport { withObservability } from \"./core/observable\";\nimport { withOptions } from \"./core/options\";\nimport { withPlugins } from \"./core/plugins\";\nimport { withRouteLifecycle } from \"./core/routeLifecycle\";\nimport { withRouterLifecycle } from \"./core/routerLifecycle\";\nimport { withRoutes } from \"./core/routes\";\nimport { withState } from \"./core/state\";\nimport { isLoggerConfig } from \"./typeGuards\";\n\nimport type {\n Config,\n DefaultDependencies,\n Options,\n Route,\n Router,\n} from \"core-types\";\n\ntype Enhancer<Dependencies extends DefaultDependencies = DefaultDependencies> =\n (router: Router<Dependencies>) => Router<Dependencies>;\n\nconst pipe =\n <Dependencies extends DefaultDependencies = DefaultDependencies>(\n ...fns: Enhancer<Dependencies>[]\n ) =>\n (arg: Router<Dependencies>): Router<Dependencies> =>\n // eslint-disable-next-line unicorn/no-array-reduce\n fns.reduce((prev: Router<Dependencies>, fn) => fn(prev), arg);\n\n/**\n * Creates a new router instance.\n */\nexport const createRouter = <\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: Route<Dependencies>[] = [],\n options: Partial<Options> = {},\n dependencies: Dependencies = {} as Dependencies,\n): Router<Dependencies> => {\n if (options.logger && isLoggerConfig(options.logger)) {\n logger.configure(options.logger);\n\n delete options.logger;\n }\n\n const config: Config = {\n decoders: {},\n encoders: {},\n defaultParams: {},\n forwardMap: {},\n };\n\n const uninitializedRouter = {\n [CONFIG_SYMBOL]: config,\n };\n\n return pipe<Dependencies>(\n withOptions(options),\n withDependencies(dependencies),\n withObservability,\n withState,\n withRouterLifecycle,\n withRouteLifecycle,\n withNavigation,\n withPlugins,\n withMiddleware,\n withRoutes(routes),\n )(uninitializedRouter as unknown as Router<Dependencies>);\n};\n"]}
1
+ {"version":3,"sources":["../../src/constants.ts","../../../type-guards/src/guards/navigation.ts","../../../type-guards/src/internal/router-error.ts","../../../type-guards/src/guards/routes.ts","../../../type-guards/src/guards/params.ts","../../../type-guards/src/internal/meta-fields.ts","../../../type-guards/src/guards/state.ts","../../../type-guards/src/guards/primitives.ts","../../../type-guards/src/validators/routes.ts","../../../type-guards/src/utilities/type-description.ts","../../../type-guards/src/validators/state.ts","../../src/helpers.ts","../../src/RouterError.ts","../../src/core/dependencies.ts","../../src/core/middleware.ts","../../src/transition/makeError.ts","../../src/transition/mergeStates.ts","../../src/transition/processLifecycleResult.ts","../../src/transition/wrapSyncError.ts","../../src/transition/executeLifecycleHooks.ts","../../src/transition/executeMiddleware.ts","../../src/transitionPath.ts","../../src/transition/index.ts","../../src/core/navigation.ts","../../src/core/observable.ts","../../src/core/options.ts","../../src/core/plugins.ts","../../src/core/routeLifecycle.ts","../../../search-params/src/decode.ts","../../../search-params/src/strategies/array.ts","../../../search-params/src/strategies/boolean.ts","../../../search-params/src/strategies/null.ts","../../../search-params/src/strategies/index.ts","../../../search-params/src/encode.ts","../../../search-params/src/utils.ts","../../../search-params/src/searchParams.ts","../../../route-tree/src/parser/path-parser/buildPathFromPattern.ts","../../../route-tree/src/parser/path-parser/constants.ts","../../../route-tree/src/parser/path-parser/encoding.ts","../../../route-tree/src/parser/path-parser/tokeniser.ts","../../../route-tree/src/parser/path-parser/Path.ts","../../../route-tree/src/parser/defaultParserFactory.ts","../../../route-tree/src/builder/buildTree.ts","../../../route-tree/src/builder/computeCaches.ts","../../../route-tree/src/builder/sortTree.ts","../../../route-tree/src/validation/errors.ts","../../../route-tree/src/builder/validateRoutes.ts","../../../route-tree/src/builder/createRouteTree.ts","../../../route-tree/src/operations/match.ts","../../../route-tree/src/operations/query.ts","../../../route-tree/src/operations/build.ts","../../../route-tree/src/operations/meta.ts","../../../route-tree/src/operations/routeTreeToDefinitions.ts","../../../route-tree/src/validation/routes.ts","../../../route-tree/src/validation/route-batch.ts","../../src/internals.ts","../../src/core/stateBuilder.ts","../../src/core/routes/routePath.ts","../../src/core/routerLifecycle.ts","../../src/core/routes/routeConfig.ts","../../src/core/routes/routeQuery.ts","../../src/core/routes/routeTree.ts","../../src/core/routes/index.ts","../../src/core/state.ts","../../src/typeGuards.ts","../../src/createRouter.ts"],"names":["isState","logger","safeCallback","plugins","encodeValue","hasPrefix","getSearch","createRouterError","FULL_ROUTE_PATTERN","HAS_NON_WHITESPACE","MAX_ROUTE_NAME_LENGTH","getTypeDescription","validateRouteName","DEFAULT_ROUTE_NAME","noop"],"mappings":";AAgBO,IAAM,gBAAA,0BAA0B,uBAAuB,CAAA;AAQvD,IAAM,wBAAA,0BAAkC,8BAA8B,CAAA;AAwBtE,IAAM,2BAAA,mBAA8B,MAAA;AAAA,EACzC;AACF,CAAA;AAOO,IAAM,gBAAA,0BAA0B,sBAAsB,CAAA;AAQtD,IAAM,aAAA,0BAAuB,oBAAoB,CAAA;AAiBjD,IAAM,UAAA,GAAkC,OAAO,MAAA,CAAO;AAAA,EAC3D,kBAAA,EAAoB,aAAA;AAAA;AAAA,EACpB,sBAAA,EAAwB,wBAAA;AAAA;AAAA,EACxB,sBAAA,EAAwB,iBAAA;AAAA;AAAA,EACxB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,WAAA,EAAa,aAAA;AAAA;AAAA,EACb,iBAAA,EAAmB,mBAAA;AAAA;AAAA,EACnB,eAAA,EAAiB,iBAAA;AAAA;AAAA,EACjB,cAAA,EAAgB,gBAAA;AAAA;AAAA,EAChB,oBAAA,EAAsB;AAAA;AACxB,CAAC;AAMM,IAAM,SAAA,GAAuB;AAAA,EAClC,aAAA,EAAe;AAAA;AACjB;AAMO,IAAM,OAA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;AC7CA,IAAM,IAAA,GACJ,CAAA,GACK,GAAA,KAEL,CAAC,GAAA;AAAA;AAAA,EAEC,GAAA,CAAI,OAAO,CAAC,IAAA,EAA4B,OAAO,EAAA,CAAG,IAAI,GAAG,GAAG;AAAA,CAAA;AAKzD,IAAM,YAAA,GAAe,CAG1B,MAAA,GAAgC,EAAC,EACjC,UAA4B,EAAC,EAC7B,YAAA,GAA6B,EAAC,KACL;AACzB,EAAA,IAAI,OAAA,CAAQ,MAAA,IAAU,cAAA,CAAe,OAAA,CAAQ,MAAM,CAAA,EAAG;AACpD,IAAAA,MAAAA,CAAO,SAAA,CAAU,OAAA,CAAQ,MAAM,CAAA;AAE/B,IAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,EACjB;AAEA,EAAA,MAAM,MAAA,GAAiB;AAAA,IACrB,UAAU,EAAC;AAAA,IACX,UAAU,EAAC;AAAA,IACX,eAAe,EAAC;AAAA,IAChB,YAAY;AAAC,GACf;AAEA,EAAA,MAAM,mBAAA,GAAsB;AAAA,IAC1B,CAAC,aAAa,GAAG;AAAA,GACnB;AAEA,EAAA,OAAO,IAAA;AAAA,IACL,YAAY,OAAO,CAAA;AAAA,IACnB,iBAAiB,YAAY,CAAA;AAAA,IAC7B,iBAAA;AAAA,IACA,SAAA;AAAA,IACA,mBAAA;AAAA,IACA,kBAAA;AAAA,IACA,cAAA;AAAA,IACA,WAAA;AAAA,IACA,cAAA;AAAA,IACA,WAAW,MAAM;AAAA,IACjB,mBAAsD,CAAA;AAC1D","file":"index.mjs","sourcesContent":["// packages/real-router/modules/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n} from \"core-types\";\n\n/**\n * Internal Symbol for storing the route tree.\n * Using Symbol to simulate a \"private\" property that won't appear in Object.keys().\n *\n * @internal\n */\nexport const ROOT_TREE_SYMBOL = Symbol(\"real-router.routeTree\");\n\n/**\n * Internal Symbol for storing route definitions.\n * Used for dynamic route addition support.\n *\n * @internal\n */\nexport const ROUTE_DEFINITIONS_SYMBOL = Symbol(\"real-router.routeDefinitions\");\n\n/**\n * Internal Symbol for storing resolved forwardTo chains cache.\n * Maps route names to their final destination after following the entire chain.\n *\n * @internal\n * @todo RFC-8: This is a stopgap solution until CacheManager is implemented.\n * Once CacheManager is available, migrate to:\n * CacheManager.getInstance().setResolvedForwardMap(router, resolvedMap)\n *\n * **Current approach (temporary)**:\n * ```typescript\n * router[RESOLVED_FORWARD_MAP_SYMBOL] = { \"A\": \"C\", \"B\": \"C\" };\n * ```\n *\n * **Future approach (RFC-8)**:\n * ```typescript\n * CacheManager.getInstance().setResolvedForwardMap(router, resolvedMap);\n * ```\n *\n * See: .claude/issues/1-dx-improve-rfc-list/rfc-7-route-guard-check.md\n * See: .claude/issues/2-fsm-migration-rfc-list/rfc-8-cache-manager.md\n */\nexport const RESOLVED_FORWARD_MAP_SYMBOL = Symbol(\n \"real-router.resolvedForwardMap\",\n);\n\n/**\n * Internal Symbol for storing root path.\n *\n * @internal\n */\nexport const ROOT_PATH_SYMBOL = Symbol(\"real-router.rootPath\");\n\n/**\n * Internal Symbol for storing router configuration.\n * Hides config from public API to prevent bypassing validation in updateRoute().\n *\n * @internal\n */\nexport const CONFIG_SYMBOL = Symbol(\"real-router.config\");\n\nexport type ConstantsKeys = \"UNKNOWN_ROUTE\";\n\nexport type Constants = Record<ConstantsKeys, string>;\n\n// =============================================================================\n// Error Codes (migrated from router-error)\n// =============================================================================\n\nexport type ErrorCodes = Record<ErrorCodeKeys, ErrorCodeValues>;\n\n/**\n * Error codes for router operations.\n * Used to identify specific failure scenarios in navigation and lifecycle.\n * Frozen to prevent accidental modifications.\n */\nexport const errorCodes: ErrorCodeToValueMap = Object.freeze({\n ROUTER_NOT_STARTED: \"NOT_STARTED\", // navigate() called before start()\n NO_START_PATH_OR_STATE: \"NO_START_PATH_OR_STATE\", // start() without initial route\n ROUTER_ALREADY_STARTED: \"ALREADY_STARTED\", // start() called twice\n ROUTE_NOT_FOUND: \"ROUTE_NOT_FOUND\", // Navigation to non-existent route\n SAME_STATES: \"SAME_STATES\", // Navigate to current route without reload\n CANNOT_DEACTIVATE: \"CANNOT_DEACTIVATE\", // canDeactivate guard blocked navigation\n CANNOT_ACTIVATE: \"CANNOT_ACTIVATE\", // canActivate guard blocked navigation\n TRANSITION_ERR: \"TRANSITION_ERR\", // Generic transition failure\n TRANSITION_CANCELLED: \"CANCELLED\", // Navigation cancelled by user or new navigation\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const constants: Constants = {\n UNKNOWN_ROUTE: \"@@router/UNKNOWN_ROUTE\", // Special route for 404/not found states\n};\n\n/**\n * Plugin method names.\n * Maps to methods that plugins can implement to hook into router lifecycle.\n */\nexport const plugins: EventToPluginMap = {\n ROUTER_START: \"onStart\", // Plugin method called when router starts\n ROUTER_STOP: \"onStop\", // Plugin method called when router stops\n TRANSITION_START: \"onTransitionStart\", // Plugin method called when navigation begins\n TRANSITION_CANCEL: \"onTransitionCancel\", // Plugin method called when navigation cancelled\n TRANSITION_SUCCESS: \"onTransitionSuccess\", // Plugin method called when navigation succeeds\n TRANSITION_ERROR: \"onTransitionError\", // Plugin method called when navigation fails\n};\n\n/**\n * Event names for router event system.\n * Used with addEventListener/removeEventListener for reactive subscriptions.\n */\nexport const events: EventToNameMap = {\n ROUTER_START: \"$start\", // Emitted when router.start() succeeds\n ROUTER_STOP: \"$stop\", // Emitted when router.stop() is called\n TRANSITION_START: \"$$start\", // Emitted when navigation begins\n TRANSITION_CANCEL: \"$$cancel\", // Emitted when navigation is cancelled\n TRANSITION_SUCCESS: \"$$success\", // Emitted when navigation completes successfully\n TRANSITION_ERROR: \"$$error\", // Emitted when navigation fails\n};\n","// packages/type-guards/modules/guards/navigation.ts\n\nimport type { NavigationOptions } from \"core-types\";\n\n// Constant in module scope - created once, not on every call\nconst NAVIGATION_OPTIONS_FIELDS = [\n \"replace\",\n \"reload\",\n \"skipTransition\",\n \"force\",\n \"forceDeactivate\",\n \"redirected\",\n] as const;\n\n/**\n * Type guard for NavigationOptions.\n * Validates all optional boolean fields.\n *\n * @param value - Value to check\n * @returns true if value is a valid NavigationOptions object\n *\n * @example\n * isNavigationOptions({ replace: true }); // true\n * isNavigationOptions({ reload: false, force: true }); // true\n * isNavigationOptions({ replace: \"true\" }); // false (not boolean)\n * isNavigationOptions(null); // false\n */\nexport function isNavigationOptions(\n value: unknown,\n): value is NavigationOptions {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n // for-of instead of .every() - no iterator/callback allocation\n for (const field of NAVIGATION_OPTIONS_FIELDS) {\n const fieldValue = obj[field];\n\n if (fieldValue !== undefined && typeof fieldValue !== \"boolean\") {\n return false;\n }\n }\n\n return true;\n}\n","// packages/type-guards/modules/internal/router-error.ts\n\n/**\n * Checks if string contains at least one non-whitespace character.\n * Used to validate that route name is not empty or only whitespace.\n * Matches: any non-whitespace character (\\S = [^ \\t\\n\\r\\f])\n *\n * @internal\n */\nexport const HAS_NON_WHITESPACE = /\\S/;\n\n/**\n * Pattern for complete route validation (all segments at once).\n * Matches: single segment or multiple segments separated by dots.\n * Each segment must start with letter/underscore, followed by alphanumeric/hyphen/underscore.\n * Rejects: leading/trailing/consecutive dots, segments starting with numbers/hyphens.\n * Note: Empty string is handled by early return in validateRouteName.\n *\n * @internal\n */\nexport const FULL_ROUTE_PATTERN = /^[A-Z_a-z][\\w-]*(?:\\.[A-Z_a-z][\\w-]*)*$/;\n\n/**\n * Maximum route name length to prevent DoS and performance issues.\n * This is a technical limit, not a business constraint.\n * Real route names rarely exceed 200 characters even with deep nesting.\n *\n * @internal\n */\nexport const MAX_ROUTE_NAME_LENGTH = 10_000;\n\n/**\n * Creates a TypeError with consistent router error message format.\n *\n * @param methodName - Name of the method that triggered the error\n * @param message - Error message\n * @returns TypeError with formatted message\n * @internal\n */\nexport function createRouterError(\n methodName: string,\n message: string,\n): TypeError {\n return new TypeError(`[router.${methodName}] ${message}`);\n}\n","// packages/type-guards/modules/guards/routes.ts\n\nimport {\n FULL_ROUTE_PATTERN,\n MAX_ROUTE_NAME_LENGTH,\n} from \"../internal/router-error\";\n\n/**\n * Type guard that checks if a value is a valid route name.\n *\n * Route name rules:\n * - Must be a string\n * - Empty string (\"\") is valid and represents the root node\n * - Can use dots (.) for hierarchy (e.g., \"users.profile\")\n * - Each segment must match [a-zA-Z_][a-zA-Z0-9_-]*\n * - No consecutive dots (..)\n * - No leading/trailing dots\n * - Cannot contain only whitespace\n * - System routes (starting with @@) bypass pattern validation\n *\n * @param name - Value to check\n * @returns true if name is a valid route name string\n *\n * @example\n * // Valid names\n * isRouteName(\"\"); // true (root node)\n * isRouteName(\"home\"); // true\n * isRouteName(\"users.profile\"); // true\n * isRouteName(\"admin_panel\"); // true\n * isRouteName(\"api-v2\"); // true\n * isRouteName(\"@@router/UNKNOWN_ROUTE\"); // true (system route)\n *\n * @example\n * // Invalid names\n * isRouteName(\" \"); // false (only whitespace)\n * isRouteName(\".users\"); // false (leading dot)\n * isRouteName(\"users.\"); // false (trailing dot)\n * isRouteName(\"users..profile\"); // false (consecutive dots)\n * isRouteName(\"users.123\"); // false (segment starts with number)\n * isRouteName(\"users profile\"); // false (contains space)\n */\nexport function isRouteName(name: unknown): name is string {\n if (typeof name !== \"string\") {\n return false;\n }\n\n // Empty string is valid (represents root node)\n if (name === \"\") {\n return true;\n }\n\n // Too long is invalid\n if (name.length > MAX_ROUTE_NAME_LENGTH) {\n return false;\n }\n\n // System routes are valid (bypass pattern validation)\n if (name.startsWith(\"@@\")) {\n return true;\n }\n\n // Regular routes must match pattern\n // Note: FULL_ROUTE_PATTERN rejects whitespace-only strings\n return FULL_ROUTE_PATTERN.test(name);\n}\n","// packages/type-guards/modules/guards/params.ts\n\nimport type { Params } from \"core-types\";\n\n/**\n * Internal helper to check if value is serializable (no circular refs, functions, instances).\n * Recursively validates the entire object tree with protection against circular references.\n *\n * @param value - Value to check\n * @param visited - Set of visited objects to detect circular references\n * @returns true if value can be serialized\n * @internal\n */\nfunction isSerializable(\n value: unknown,\n visited = new WeakSet<object>(),\n): boolean {\n // null/undefined are serializable (JSON.stringify handles them)\n if (value === null || value === undefined) {\n return true;\n }\n\n const type = typeof value;\n\n // Primitives: string, boolean\n if (type === \"string\" || type === \"boolean\") {\n return true;\n }\n\n // Numbers: must be finite (reject NaN and Infinity)\n if (type === \"number\") {\n return Number.isFinite(value);\n }\n\n // Functions and symbols cannot be serialized\n if (type === \"function\" || type === \"symbol\") {\n return false;\n }\n\n // Arrays (including nested arrays)\n if (Array.isArray(value)) {\n // Circular reference detection\n if (visited.has(value)) {\n return false;\n }\n\n visited.add(value);\n\n // Recursively check all items\n return value.every((item) => isSerializable(item, visited));\n }\n\n // Objects\n if (type === \"object\") {\n // Circular reference detection\n if (visited.has(value)) {\n return false;\n }\n\n // Add to visited set\n visited.add(value);\n\n // Only allow plain objects (reject Date, RegExp, Map, Set, etc.)\n const proto = Object.getPrototypeOf(value) as object | null;\n\n if (proto !== null && proto !== Object.prototype) {\n return false; // Instance of a class\n }\n\n // Recursively check all values\n return Object.values(value).every((v) => isSerializable(v, visited));\n }\n\n return false;\n}\n\n/**\n * Fast path check for primitive values (no recursion needed).\n * Returns true if primitive, false if needs deeper inspection.\n *\n * @internal\n */\nfunction isPrimitiveValue(value: unknown): boolean {\n if (value === null || value === undefined) {\n return true;\n }\n\n const type = typeof value;\n\n if (type === \"string\" || type === \"boolean\") {\n return true;\n }\n\n if (type === \"number\") {\n return Number.isFinite(value);\n }\n\n // object, array, function, symbol — need deeper check\n return false;\n}\n\n/**\n * Type guard for Params object.\n * Validates that all values are serializable (primitives, arrays, nested arrays, or nested objects).\n * Rejects circular references, functions, symbols, and class instances.\n * Allows null/undefined anywhere (objects and arrays).\n *\n * Performance optimization: Uses two-phase validation.\n * Phase 1 (fast path): Check if all values are primitives — O(p) without recursion.\n * Phase 2 (slow path): Full recursive validation only if nested structures detected.\n *\n * @param value - Value to check\n * @returns true if value is a valid Params object\n *\n * @example\n * // Valid\n * isParams({ id: '123', page: 1 }); // true (fast path)\n * isParams({ sort: ['name', 'age'] }); // true (slow path)\n * isParams({ filter: { status: 'active' } }); // true (slow path)\n * isParams({ teamId: null, orgId: undefined }); // true (fast path)\n * isParams({ matrix: [[1, 2], [3, 4]] }); // true (slow path)\n * isParams({ users: [{ id: 1 }, { id: 2 }] }); // true (slow path)\n * isParams({ scores: [100, null, 85] }); // true (slow path)\n *\n * // Invalid\n * isParams({ fn: () => {} }); // false (function)\n * isParams({ date: new Date() }); // false (class instance)\n * isParams({ self: circularRef }); // false (circular reference)\n * isParams(null); // false (not an object)\n * isParams([]); // false (array, not object)\n */\nexport function isParams(value: unknown): value is Params {\n // Reject null, undefined, and arrays (must be a plain object)\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n // Reject objects with custom prototype (e.g., Object.create(proto), class instances)\n // This check is required for both fast and slow paths\n const proto = Object.getPrototypeOf(value) as object | null;\n\n if (proto !== null && proto !== Object.prototype) {\n return false;\n }\n\n // Phase 1: Fast path for flat objects (95%+ of real-world params)\n // Check if all values are primitives — no recursion, no WeakSet allocation\n let needsDeepCheck = false;\n\n for (const key in value) {\n // Skip inherited properties (only check own properties for fast path)\n // Note: With proto === Object.prototype check above, inherited properties\n // would only come from Object.prototype, which has no enumerable properties.\n // This check is defensive against Object.prototype pollution.\n /* v8 ignore next 3 -- @preserve Defensive: Object.prototype pollution */\n if (!Object.hasOwn(value, key)) {\n continue;\n }\n\n const val = (value as Record<string, unknown>)[key];\n\n if (!isPrimitiveValue(val)) {\n // Found non-primitive — need full validation\n // But first check for obvious invalids (functions, symbols)\n const type = typeof val;\n\n if (type === \"function\" || type === \"symbol\") {\n return false; // Early reject\n }\n\n needsDeepCheck = true;\n\n break; // Exit fast path, proceed to slow path\n }\n }\n\n // Fast path: all primitives, valid params\n if (!needsDeepCheck) {\n return true;\n }\n\n // Phase 2: Slow path — full recursive validation\n return isSerializable(value);\n}\n\n/**\n * Internal helper for strict param validation (browser plugin).\n * Only allows primitives and arrays of primitives, no nested objects.\n *\n * @param value - Value to check\n * @returns true if value is valid\n * @internal\n */\nexport function isValidParamValueStrict(value: unknown): boolean {\n if (value === null || value === undefined) {\n return true;\n }\n\n const type = typeof value;\n\n // Primitives: string, boolean, finite number\n if (type === \"string\" || type === \"boolean\") {\n return true;\n }\n\n if (type === \"number\") {\n return Number.isFinite(value as number);\n }\n\n // Arrays of primitives only\n if (Array.isArray(value)) {\n return value.every((item) => {\n const itemType = typeof item;\n\n // Primitives: string, boolean, finite number\n if (itemType === \"string\" || itemType === \"boolean\") {\n return true;\n }\n\n if (itemType === \"number\") {\n return Number.isFinite(item);\n }\n\n // Reject everything else (objects, arrays, functions, symbols, etc.)\n return false;\n });\n }\n\n // Reject objects, functions, symbols, etc.\n return false;\n}\n\n/**\n * Strict type guard for Params (browser plugin version).\n * Only allows primitives and arrays of primitives, no nested objects.\n *\n * @param value - Value to check\n * @returns true if value is a valid Params object\n */\nexport function isParamsStrict(value: unknown): value is Params {\n // Check if value is an object (null returns \"object\" but fails Array.isArray and other checks)\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n\n // Check all own properties have valid param values\n for (const key in value) {\n if (!Object.hasOwn(value, key)) {\n continue; // Skip inherited properties\n }\n\n const val = (value as Record<string, unknown>)[key];\n\n if (!isValidParamValueStrict(val)) {\n return false;\n }\n }\n\n return true;\n}\n","// packages/type-guards/modules/internal/meta-fields.ts\n\nimport { isParams, isParamsStrict } from \"../guards/params\";\nimport { isRouteName } from \"../guards/routes\";\n\nimport type { Params, StateMeta } from \"core-types\";\n\n/**\n * Type guard for meta object fields if present.\n * Used by both isStateStrict and isHistoryState.\n *\n * @param meta - Value to check\n * @returns true if meta has valid StateMeta structure\n * @internal\n */\nexport function isMetaFields<MP extends Params = Params>(\n meta: unknown,\n): meta is StateMeta<MP> {\n // Early check: must be a non-null object\n if (typeof meta !== \"object\" || meta === null) {\n return false;\n }\n\n const obj = meta as Record<string, unknown>;\n\n // Check params field if present\n if (\"params\" in obj && !isParamsStrict(obj.params)) {\n return false;\n }\n\n // Check options field if present\n if (\"options\" in obj && typeof obj.options !== \"object\") {\n return false;\n }\n\n // Check id field if present\n if (\"id\" in obj && typeof obj.id !== \"number\") {\n return false;\n }\n\n // Check redirected field if present\n if (\"redirected\" in obj && typeof obj.redirected !== \"boolean\") {\n return false;\n }\n\n // Check source field if present\n return !(\"source\" in obj && typeof obj.source !== \"string\");\n}\n\n/**\n * Type guard helper that checks if required State fields have valid types.\n * Validates that name, path, and params exist and have correct types.\n * Used by both isStateStrict and isHistoryState.\n *\n * @param obj - Object to check\n * @returns true if object has valid required fields\n * @internal\n */\nexport function isRequiredFields(obj: Record<string, unknown>): boolean {\n return (\n isRouteName(obj.name) &&\n typeof obj.path === \"string\" &&\n isParams(obj.params)\n );\n}\n","// packages/type-guards/modules/guards/state.ts\n\nimport { isMetaFields, isRequiredFields } from \"../internal/meta-fields\";\n\nimport type { Params, State } from \"core-types\";\n\n/**\n * Type guard for State object.\n * Checks for required fields: name, params, path.\n * Does NOT validate meta field deeply.\n *\n * @param value - Value to check\n * @returns true if value is a valid State object\n *\n * @example\n * isState({ name: 'home', params: {}, path: '/' }); // true\n * isState({ name: 'home', path: '/' }); // false (missing params)\n */\nexport function isState<P extends Params = Params, MP extends Params = Params>(\n value: unknown,\n): value is State<P, MP> {\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n return isRequiredFields(obj);\n}\n\n/**\n * Enhanced type guard for State with deep validation.\n * Checks not only presence but also types of all required fields.\n * Validates params using isParams and meta structure if present.\n *\n * @param value - Value to check\n * @returns true if value is a valid State object with correct types\n *\n * @example\n * isStateStrict({ name: 'home', params: {}, path: '/', meta: { id: 1 } }); // true\n * isStateStrict({ name: 'home', params: 'invalid', path: '/' }); // false\n */\nexport function isStateStrict<\n P extends Params = Params,\n MP extends Params = Params,\n>(value: unknown): value is State<P, MP> {\n // Basic structure check\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n // Check required fields and their types\n if (!isRequiredFields(obj)) {\n return false;\n }\n\n // Validate meta if present\n if (obj.meta !== undefined) {\n return isMetaFields(obj.meta);\n }\n\n return true;\n}\n\n/**\n * Type guard for HistoryState (browser plugin).\n * HistoryState must have meta object with specific structure.\n * This is stricter than regular State validation.\n *\n * @param value - Value to check\n * @returns true if value is a valid HistoryState object\n */\nexport function isHistoryState(value: unknown): value is State & {\n meta: NonNullable<State[\"meta\"]>;\n} {\n // Basic structure check\n if (typeof value !== \"object\" || value === null) {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n // Check required fields and their types\n if (!isRequiredFields(obj)) {\n return false;\n }\n\n // HistoryState requires meta to be present and valid\n // Note: The check !(\"meta\" in obj) is redundant because isMetaFields(undefined) returns false\n // However, we keep it for clarity and explicit error semantics\n return \"meta\" in obj && isMetaFields(obj.meta);\n}\n","// packages/type-guards/modules/primitives.ts\n\n/**\n * Type guard for string type.\n *\n * @param value - Value to check\n * @returns true if value is a string\n */\nexport function isString(value: unknown): value is string {\n return typeof value === \"string\";\n}\n\n/**\n * Type guard for boolean type.\n *\n * @param value - Value to check\n * @returns true if value is a boolean\n */\nexport function isBoolean(value: unknown): value is boolean {\n return typeof value === \"boolean\";\n}\n\n/**\n * Type guard for Promise type.\n *\n * @param value - Value to check\n * @returns true if value is a Promise\n */\nexport function isPromise<T = unknown>(value: unknown): value is Promise<T> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"then\" in value &&\n typeof value.then === \"function\"\n );\n}\n\n/**\n * Type guard for object key existence.\n * Narrows the key type to a valid key of the object.\n *\n * @param key - Key to check\n * @param obj - Object to check in\n * @returns true if key exists in object\n */\nexport function isObjKey<T extends object>(\n key: string,\n obj: T,\n): key is Extract<keyof T, string> {\n return key in obj;\n}\n\n/**\n * Type guard for primitive values suitable for URL parameters.\n * Only string, number, and boolean are allowed.\n * Rejects NaN and Infinity for numbers.\n *\n * @param value - Value to check\n * @returns true if value is string, number, or boolean\n */\nexport function isPrimitiveValue(\n value: unknown,\n): value is string | number | boolean {\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n\n return typeof value === \"string\" || typeof value === \"boolean\";\n}\n","// packages/type-guards/modules/validators/routes.ts\n\nimport {\n createRouterError,\n FULL_ROUTE_PATTERN,\n HAS_NON_WHITESPACE,\n MAX_ROUTE_NAME_LENGTH,\n} from \"../internal/router-error\";\n\n/**\n * Validates that a route name is a valid string and matches the expected format.\n * Throws a descriptive error if validation fails.\n *\n * Route name rules:\n * - Must be a string\n * - Empty string (\"\") is valid and represents the root node\n * - Can use dots (.) for hierarchy (e.g., \"users.profile\")\n * - Each segment must match [a-zA-Z_][a-zA-Z0-9_-]*\n * - No consecutive dots (..)\n * - No leading/trailing dots\n * - Cannot contain only whitespace\n * - System routes (starting with @@) bypass pattern validation\n *\n * @param name - Route name to validate\n * @param methodName - Name of calling method for error messages\n * @throws {TypeError} If name is invalid\n *\n * @example\n * // Valid names\n * validateRouteName(\"\", \"add\"); // ok (root node)\n * validateRouteName(\"home\", \"add\"); // ok\n * validateRouteName(\"users.profile\", \"add\"); // ok\n * validateRouteName(\"@@router/UNKNOWN_ROUTE\", \"add\"); // ok (system route)\n *\n * @example\n * // Invalid names (throws)\n * validateRouteName(\" \", \"add\"); // throws (only whitespace)\n * validateRouteName(\".users\", \"add\"); // throws (leading dot)\n * validateRouteName(\"users.\", \"add\"); // throws (trailing dot)\n * validateRouteName(\"users..profile\", \"add\"); // throws (consecutive dots)\n * validateRouteName(\"users.123\", \"add\"); // throws (segment starts with number)\n * validateRouteName(\"users profile\", \"add\"); // throws (contains space)\n */\nexport function validateRouteName(\n name: unknown,\n methodName: string,\n): asserts name is string {\n // Type check\n if (typeof name !== \"string\") {\n throw createRouterError(\n methodName,\n `Route name must be a string, got ${typeof name}`,\n );\n }\n\n // Empty string is valid (represents root node) - fast path\n if (name === \"\") {\n return;\n }\n\n // Whitespace-only strings are invalid\n if (!HAS_NON_WHITESPACE.test(name)) {\n throw createRouterError(\n methodName,\n \"Route name cannot contain only whitespace\",\n );\n }\n\n // Length check for technical safety\n if (name.length > MAX_ROUTE_NAME_LENGTH) {\n throw createRouterError(\n methodName,\n `Route name exceeds maximum length of ${MAX_ROUTE_NAME_LENGTH} characters. This is a technical safety limit.`,\n );\n }\n\n // System routes bypass validation (e.g., @@router/UNKNOWN_ROUTE)\n // SECURITY NOTE: System routes are currently created ONLY in router code,\n // not from user input. If this changes, add sanitization for <>\"'&\\x00-\\x1F\n if (name.startsWith(\"@@\")) {\n return;\n }\n\n // Validate route pattern\n if (!FULL_ROUTE_PATTERN.test(name)) {\n throw createRouterError(\n methodName,\n `Invalid route name \"${name}\". Each segment must start with a letter or underscore, followed by letters, numbers, underscores, or hyphens. Segments are separated by dots (e.g., \"users.profile\").`,\n );\n }\n}\n","// packages/type-guards/modules/internal/type-description.ts\n\n/**\n * Gets a human-readable description of a value's type.\n * Used for error messages to provide helpful debugging information.\n *\n * @param value - Value to describe\n * @returns String description of the value's type\n *\n * @example\n * getTypeDescription(null); // \"null\"\n * getTypeDescription([1, 2, 3]); // \"array[3]\"\n * getTypeDescription(new Date()); // \"Date\"\n * getTypeDescription({}); // \"object\"\n * getTypeDescription(\"hello\"); // \"string\"\n */\nexport function getTypeDescription(value: unknown): string {\n // Handle null explicitly (typeof null === \"object\")\n if (value === null) {\n return \"null\";\n }\n\n // Array with length info\n if (Array.isArray(value)) {\n return `array[${value.length}]`;\n }\n\n if (typeof value === \"object\") {\n // Return constructor name for class instances\n if (\"constructor\" in value && value.constructor.name !== \"Object\") {\n return value.constructor.name;\n }\n\n // Plain object\n return \"object\";\n }\n\n // Primitive types (string, number, boolean, undefined, etc.)\n // Note: typeof undefined === \"undefined\", so we don't need explicit check\n return typeof value;\n}\n","// packages/type-guards/modules/validators/state.ts\n\nimport { isState } from \"../guards\";\nimport { getTypeDescription } from \"../utilities/type-description\";\n\nimport type { State } from \"core-types\";\n\n/**\n * Validates that a state has the correct structure.\n * Throws a descriptive error if validation fails.\n *\n * @param state - State to validate\n * @param method - Context for error message\n * @throws {TypeError} If state structure is invalid\n *\n * @example\n * validateState({ name: 'home', params: {}, path: '/' }, 'navigate'); // ok\n * validateState({ name: 'home' }, 'navigate'); // throws (missing params, path)\n * validateState(null, 'navigate'); // throws (not an object)\n */\nexport function validateState(\n state: unknown,\n method: string,\n): asserts state is State {\n if (!isState(state)) {\n throw new TypeError(\n `[${method}] Invalid state structure: ${getTypeDescription(state)}. ` +\n `Expected State object with name, params, and path properties.`,\n );\n }\n}\n","// packages/real-router/modules/helpers.ts\n\nimport type { State, Options } from \"core-types\";\nimport type { BuildOptions, TrailingSlashMode } from \"route-tree\";\n\nexport { getTypeDescription } from \"type-guards\";\n\n// =============================================================================\n// State Helpers (migrated from router-error)\n// =============================================================================\n\n/**\n * Simple type guard for State object structure.\n * Checks for required fields: name, params, path.\n *\n * @param value - Value to check\n * @returns true if value has State structure\n * @internal\n */\nfunction isState(value: unknown): value is State {\n // Check null first to avoid type narrowing issues (typeof null === \"object\" in JS)\n if (value === null || typeof value !== \"object\") {\n return false;\n }\n\n const obj = value as Record<string, unknown>;\n\n return (\n typeof obj.name === \"string\" &&\n typeof obj.path === \"string\" &&\n typeof obj.params === \"object\" &&\n obj.params !== null\n );\n}\n\n/**\n * Deep freezes State object to prevent mutations.\n * Creates a deep clone first, then recursively freezes the clone and all nested objects.\n * Uses simple recursive freezing after cloning (no need for WeakSet since clone has no circular refs).\n *\n * @param state - The State object to freeze\n * @returns A frozen deep clone of the state\n * @throws {TypeError} If state is not a valid State object\n *\n * @example\n * const state = { name: 'home', params: {}, path: '/' };\n * const frozen = deepFreezeState(state);\n * // frozen.params is now immutable\n * // original state is unchanged\n */\nexport function deepFreezeState<T extends State>(state: T): T {\n // Early return for null/undefined\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Validate State structure\n if (!isState(state)) {\n throw new TypeError(\n `[deepFreezeState] Expected valid State object, got: ${typeof state}`,\n );\n }\n\n // Create a deep clone to avoid mutating the original\n // structuredClone preserves circular references, so we need to track visited objects\n const clonedState = structuredClone(state);\n\n // WeakSet to track visited objects (prevent infinite recursion with circular refs)\n const visited = new WeakSet<object>();\n\n // Recursive freeze function with circular reference protection\n function freezeClonedRecursive(obj: unknown): void {\n // Skip primitives, null, undefined\n // Note: typeof undefined === \"undefined\" !== \"object\", so checking undefined is redundant\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already visited objects (circular reference protection)\n if (visited.has(obj)) {\n return;\n }\n\n // Mark as visited\n visited.add(obj);\n\n // Freeze the object/array itself\n Object.freeze(obj);\n\n // Get all values to freeze recursively\n const values = Array.isArray(obj) ? obj : Object.values(obj);\n\n // Recursively freeze nested values\n for (const value of values) {\n freezeClonedRecursive(value);\n }\n }\n\n // Freeze the entire cloned state tree\n freezeClonedRecursive(clonedState);\n\n return clonedState;\n}\n\n// WeakSet to track already frozen root objects for O(1) re-freeze check\nconst frozenRoots = new WeakSet<object>();\n\n// Module-scope recursive freeze function - better JIT optimization, no allocation per call\nfunction freezeRecursive(obj: unknown): void {\n // Skip primitives, null\n if (obj === null || typeof obj !== \"object\") {\n return;\n }\n\n // Skip already frozen objects (handles potential shared refs)\n if (Object.isFrozen(obj)) {\n return;\n }\n\n // Freeze the object/array\n Object.freeze(obj);\n\n // Iterate without Object.values() allocation\n if (Array.isArray(obj)) {\n for (const item of obj) {\n freezeRecursive(item);\n }\n } else {\n for (const key in obj) {\n freezeRecursive((obj as Record<string, unknown>)[key]);\n }\n }\n}\n\n/**\n * Freezes State object in-place without cloning.\n * Optimized for hot paths where state is known to be a fresh object.\n *\n * IMPORTANT: Only use this when you know the state is a fresh object\n * that hasn't been exposed to external code yet (e.g., from makeState()).\n *\n * @param state - The State object to freeze (must be a fresh object)\n * @returns The same state object, now frozen\n * @internal\n */\nexport function freezeStateInPlace<T extends State>(state: T): T {\n // Early return for null/undefined - state from makeState() is never null\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!state) {\n return state;\n }\n\n // Fast path: already processed root object - O(1) check\n if (frozenRoots.has(state)) {\n return state;\n }\n\n // Freeze the entire state tree\n freezeRecursive(state);\n\n // Mark root as processed for future calls\n frozenRoots.add(state);\n\n return state;\n}\n\n// =============================================================================\n// Route Options Helpers\n// =============================================================================\n\n/**\n * Maps real-router trailingSlash option to route-tree's trailingSlashMode.\n *\n * @param trailingSlash - real-router trailing slash option\n * @returns route-tree trailing slash mode\n * @internal\n */\nfunction mapTrailingSlashMode(\n trailingSlash: Options[\"trailingSlash\"],\n): TrailingSlashMode {\n switch (trailingSlash) {\n case \"never\": {\n return \"never\";\n }\n case \"always\": {\n return \"always\";\n }\n default: {\n return \"default\";\n }\n }\n}\n\n/**\n * Creates route-tree BuildOptions from real-router Options.\n * Used for buildPath caching in routerLifecycle.ts.\n *\n * @param options - real-router options\n * @returns route-tree build options\n */\nexport function createBuildOptions(options: Options): BuildOptions {\n const buildOptions: BuildOptions = {\n trailingSlashMode: mapTrailingSlashMode(options.trailingSlash),\n queryParamsMode: options.queryParamsMode,\n urlParamsEncoding: options.urlParamsEncoding,\n };\n\n // Only include queryParams if defined (exactOptionalPropertyTypes)\n if (options.queryParams !== undefined) {\n buildOptions.queryParams = options.queryParams;\n }\n\n return buildOptions;\n}\n","// packages/real-router/modules/RouterError.ts\n\nimport { errorCodes } from \"./constants\";\nimport { deepFreezeState } from \"./helpers\";\n\nimport type { State } from \"core-types\";\n\n// Pre-compute Set of error code values for O(1) lookup in setCode()\n// This avoids creating array and doing linear search on every setCode() call\nconst errorCodeValues = new Set(Object.values(errorCodes));\n\n// Reserved built-in properties - throw error if user tries to set these\nconst reservedProperties = new Set([\"code\", \"segment\", \"path\", \"redirect\"]);\n\n// Reserved method names - silently ignore attempts to overwrite these\nconst reservedMethods = new Set([\n \"setCode\",\n \"setErrorInstance\",\n \"setAdditionalFields\",\n \"hasField\",\n \"getField\",\n \"toJSON\",\n]);\n\nexport class RouterError extends Error {\n [key: string]: unknown;\n\n // Using public properties to ensure structural compatibility\n // with RouterError interface in core-types\n readonly segment: string | undefined;\n readonly path: string | undefined;\n readonly redirect: State | undefined;\n\n // Note: code appears to be writable but setCode() should be used\n // to properly update both code and message together\n code: string;\n\n /**\n * Creates a new RouterError instance.\n *\n * The options object accepts built-in fields (message, segment, path, redirect)\n * and any additional custom fields, which will all be attached to the error instance.\n *\n * @param code - The error code (e.g., \"ROUTE_NOT_FOUND\", \"CANNOT_ACTIVATE\")\n * @param options - Optional configuration object\n * @param options.message - Custom error message (defaults to code if not provided)\n * @param options.segment - The route segment where the error occurred\n * @param options.path - The full path where the error occurred\n * @param options.redirect - Optional redirect state for navigation errors\n *\n * @example\n * ```typescript\n * // Basic error\n * const err1 = new RouterError(\"ROUTE_NOT_FOUND\");\n *\n * // Error with custom message\n * const err2 = new RouterError(\"ERR\", { message: \"Something went wrong\" });\n *\n * // Error with context and custom fields\n * const err3 = new RouterError(\"CANNOT_ACTIVATE\", {\n * message: \"Insufficient permissions\",\n * segment: \"admin\",\n * path: \"/admin/users\",\n * userId: \"123\" // custom field\n * });\n *\n * // Error with redirect\n * const err4 = new RouterError(\"TRANSITION_ERR\", {\n * redirect: { name: \"home\", path: \"/\", params: {} }\n * });\n * ```\n */\n constructor(\n code: string,\n {\n message,\n segment,\n path,\n redirect,\n ...rest\n }: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n path?: string | undefined;\n redirect?: State | undefined;\n } = {},\n ) {\n super(message ?? code);\n\n this.code = code;\n this.segment = segment;\n this.path = path;\n // Deep freeze redirect to prevent mutations (creates a frozen clone)\n this.redirect = redirect ? deepFreezeState(redirect) : undefined;\n\n // Assign custom fields, checking reserved properties and filtering out reserved method names\n // Issue #39: Throw for reserved properties to match setAdditionalFields behavior\n for (const [key, value] of Object.entries(rest)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Updates the error code and conditionally updates the message.\n *\n * If the current message is one of the standard error code values\n * (e.g., \"ROUTE_NOT_FOUND\", \"SAME_STATES\"), it will be replaced with the new code.\n * This allows keeping error messages in sync with codes when using standard error codes.\n *\n * If the message is custom (not a standard error code), it will be preserved.\n *\n * @param newCode - The new error code to set\n *\n * @example\n * // Message follows code (standard error code as message)\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", { message: \"ROUTE_NOT_FOUND\" });\n * err.setCode(\"CUSTOM_ERROR\"); // message becomes \"CUSTOM_ERROR\"\n *\n * @example\n * // Custom message is preserved\n * const err = new RouterError(\"ERR\", { message: \"Custom error message\" });\n * err.setCode(\"NEW_CODE\"); // message stays \"Custom error message\"\n */\n setCode(newCode: string): void {\n this.code = newCode;\n\n // Only update message if it's a standard error code value (not a custom message)\n if (errorCodeValues.has(this.message)) {\n this.message = newCode;\n }\n }\n\n /**\n * Copies properties from another Error instance to this RouterError.\n *\n * This method updates the message, cause, and stack trace from the provided error.\n * Useful for wrapping native errors while preserving error context.\n *\n * @param err - The Error instance to copy properties from\n * @throws {TypeError} If err is null or undefined\n *\n * @example\n * ```typescript\n * const routerErr = new RouterError(\"TRANSITION_ERR\");\n * try {\n * // some operation that might fail\n * } catch (nativeErr) {\n * routerErr.setErrorInstance(nativeErr);\n * throw routerErr;\n * }\n * ```\n */\n setErrorInstance(err: Error): void {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!err) {\n throw new TypeError(\n \"[RouterError.setErrorInstance] err parameter is required and must be an Error instance\",\n );\n }\n\n this.message = err.message;\n this.cause = err.cause;\n this.stack = err.stack ?? \"\";\n }\n\n /**\n * Adds custom fields to the error object.\n *\n * This method allows attaching arbitrary data to the error for debugging or logging purposes.\n * All fields become accessible as properties on the error instance and are included in JSON serialization.\n *\n * Reserved method names (setCode, setErrorInstance, setAdditionalFields, hasField, getField, toJSON)\n * are automatically filtered out to prevent accidental overwriting of class methods.\n *\n * @param fields - Object containing custom fields to add to the error\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"CANNOT_ACTIVATE\");\n * err.setAdditionalFields({\n * userId: \"123\",\n * attemptedRoute: \"/admin\",\n * reason: \"insufficient permissions\"\n * });\n *\n * console.log(err.userId); // \"123\"\n * console.log(JSON.stringify(err)); // includes all custom fields\n * ```\n */\n setAdditionalFields(fields: Record<string, unknown>): void {\n // Assign fields, throwing for reserved properties, silently ignoring methods\n for (const [key, value] of Object.entries(fields)) {\n if (reservedProperties.has(key)) {\n throw new TypeError(\n `[RouterError.setAdditionalFields] Cannot set reserved property \"${key}\"`,\n );\n }\n\n if (!reservedMethods.has(key)) {\n this[key] = value;\n }\n }\n }\n\n /**\n * Checks if a custom field exists on the error object.\n *\n * This method checks for both custom fields added via setAdditionalFields()\n * and built-in fields (code, message, segment, etc.).\n *\n * @param key - The field name to check\n * @returns `true` if the field exists, `false` otherwise\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\", { segment: \"users\" });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * err.hasField(\"userId\"); // true\n * err.hasField(\"segment\"); // true\n * err.hasField(\"unknown\"); // false\n * ```\n */\n hasField(key: string): boolean {\n return key in this;\n }\n\n /**\n * Retrieves a custom field value from the error object.\n *\n * This method can access both custom fields and built-in fields.\n * Returns `undefined` if the field doesn't exist.\n *\n * @param key - The field name to retrieve\n * @returns The field value, or `undefined` if it doesn't exist\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ERR\");\n * err.setAdditionalFields({ userId: \"123\", role: \"admin\" });\n *\n * err.getField(\"userId\"); // \"123\"\n * err.getField(\"role\"); // \"admin\"\n * err.getField(\"code\"); // \"ERR\" (built-in field)\n * err.getField(\"unknown\"); // undefined\n * ```\n */\n getField(key: string): unknown {\n return this[key];\n }\n\n /**\n * Serializes the error to a JSON-compatible object.\n *\n * This method is automatically called by JSON.stringify() and includes:\n * - Built-in fields: code, message, segment (if set), path (if set), redirect (if set)\n * - All custom fields added via setAdditionalFields() or constructor\n * - Excludes: stack trace (for security/cleanliness)\n *\n * @returns A plain object representation of the error, suitable for JSON serialization\n *\n * @example\n * ```typescript\n * const err = new RouterError(\"ROUTE_NOT_FOUND\", {\n * message: \"Route not found\",\n * path: \"/admin/users/123\"\n * });\n * err.setAdditionalFields({ userId: \"123\" });\n *\n * JSON.stringify(err);\n * // {\n * // \"code\": \"ROUTE_NOT_FOUND\",\n * // \"message\": \"Route not found\",\n * // \"path\": \"/admin/users/123\",\n * // \"userId\": \"123\"\n * // }\n * ```\n */\n toJSON(): Record<string, unknown> {\n const result: Record<string, unknown> = {\n code: this.code,\n message: this.message,\n };\n\n if (this.segment !== undefined) {\n result.segment = this.segment;\n }\n if (this.path !== undefined) {\n result.path = this.path;\n }\n if (this.redirect !== undefined) {\n result.redirect = this.redirect;\n }\n\n // add all public fields\n // Using Set.has() for O(1) lookup instead of Array.includes() O(n)\n // Overall complexity: O(n) instead of O(n*m)\n const excludeKeys = new Set([\n \"code\",\n \"message\",\n \"segment\",\n \"path\",\n \"redirect\",\n \"stack\",\n ]);\n\n for (const key in this) {\n if (Object.hasOwn(this, key) && !excludeKeys.has(key)) {\n result[key] = this[key];\n }\n }\n\n return result;\n }\n}\n","// packages/real-router/modules/core/dependencies.ts\n\nimport { logger } from \"@real-router/logger\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type { DefaultDependencies, Router } from \"core-types\";\n\nfunction validateStringKey(\n methodName: string,\n key: unknown,\n): asserts key is string {\n if (typeof key !== \"string\") {\n throw new TypeError(\n `[router.${methodName}]: dependency name must be a string, got ${typeof key}`,\n );\n }\n}\n\nconst DEPENDENCY_LIMITS = {\n WARN: 20,\n ERROR: 50,\n HARD_LIMIT: 100,\n} as const;\n\nfunction checkDependencyCount(deps: object, methodName: string): void {\n const currentCount = Object.keys(deps).length;\n\n if (currentCount === DEPENDENCY_LIMITS.WARN) {\n logger.warn(\n `router.${methodName}`,\n `${DEPENDENCY_LIMITS.WARN} dependencies registered. ` +\n `Consider if all are necessary.`,\n );\n } else if (currentCount === DEPENDENCY_LIMITS.ERROR) {\n logger.error(\n `router.${methodName}`,\n `${DEPENDENCY_LIMITS.ERROR} dependencies registered! ` +\n `This indicates architectural problems. ` +\n `Hard limit at ${DEPENDENCY_LIMITS.HARD_LIMIT}.`,\n );\n } else if (currentCount >= DEPENDENCY_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.${methodName}] Dependency limit exceeded (${DEPENDENCY_LIMITS.HARD_LIMIT}). ` +\n `Current: ${currentCount}. This is likely a bug in your code. ` +\n `If you genuinely need more dependencies, your architecture needs refactoring.`,\n );\n }\n}\n\nexport function withDependencies<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(dependencies: Partial<Dependencies>) {\n const dependencyNotFoundError = (method: string, name: keyof Dependencies) =>\n new ReferenceError(\n `[router.${method}]: dependency \"${String(name)}\" not found`,\n );\n\n const setDependencies = (deps: Partial<Dependencies>) => {\n // Reject non-plain objects (classes, Date, Map, Array)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!(deps && typeof deps === \"object\" && deps.constructor === Object)) {\n throw new TypeError(\n `[router.setDependencies] Invalid argument: expected plain object, received ${getTypeDescription(\n deps,\n )}`,\n );\n }\n\n // Getters can throw, return different values, or have side effects\n for (const dependencyName in deps) {\n if (Object.getOwnPropertyDescriptor(deps, dependencyName)?.get) {\n throw new TypeError(\n `[router.setDependencies] Getters not allowed: \"${dependencyName}\"`,\n );\n }\n }\n\n // Atomic limit check - either all set or none\n checkDependencyCount(\n {\n ...routerDependencies,\n ...deps,\n },\n \"setDependencies\",\n );\n\n const overwrittenKeys = [];\n\n for (const key in deps) {\n if (deps[key] !== undefined) {\n if (Object.hasOwn(routerDependencies, key)) {\n overwrittenKeys.push(key);\n }\n\n routerDependencies[key] = deps[key];\n }\n }\n\n if (overwrittenKeys.length > 0) {\n logger.warn(\n \"router.setDependencies\",\n \"Overwritten:\",\n overwrittenKeys.join(\", \"),\n );\n }\n };\n\n // Create null-prototype object to avoid prototype pollution\n\n const routerDependencies: Partial<Dependencies> = Object.create(\n null,\n ) as Partial<Dependencies>;\n\n setDependencies(dependencies);\n\n return (router: Router<Dependencies>): Router<Dependencies> => {\n router.setDependency = <K extends keyof Dependencies & string>(\n dependencyName: K,\n dependencyValue: Dependencies[K],\n ): Router<Dependencies> => {\n // undefined = \"don't set\" (feature for conditional setting)\n if (dependencyValue === undefined) {\n return router;\n }\n\n validateStringKey(\"setDependency\", dependencyName);\n\n const isNewKey = !Object.hasOwn(routerDependencies, dependencyName);\n\n if (isNewKey) {\n // Only check limit when adding new keys (overwrites don't increase count)\n checkDependencyCount(routerDependencies, \"setDependency\");\n } else {\n const oldValue = routerDependencies[dependencyName];\n const isChanging = oldValue !== dependencyValue;\n // Special case for NaN idempotency (NaN !== NaN is always true)\n const bothAreNaN =\n Number.isNaN(oldValue) && Number.isNaN(dependencyValue);\n\n if (isChanging && !bothAreNaN) {\n logger.warn(\n \"router.setDependency\",\n \"Router dependency already exists and is being overwritten:\",\n dependencyName,\n );\n }\n }\n\n routerDependencies[dependencyName] = dependencyValue;\n\n return router;\n };\n\n router.setDependencies = (\n deps: Partial<Dependencies>,\n ): Router<Dependencies> => {\n setDependencies(deps);\n\n return router;\n };\n\n router.getDependency = <K extends keyof Dependencies>(\n dependencyName: K,\n ): Dependencies[K] => {\n validateStringKey(\"getDependency\", dependencyName);\n\n const dependency = routerDependencies[dependencyName];\n\n if (dependency === undefined) {\n throw dependencyNotFoundError(\"getDependency\", dependencyName);\n }\n\n return dependency;\n };\n\n router.getDependencies = (): Partial<Dependencies> => ({\n ...routerDependencies,\n });\n\n router.removeDependency = (\n dependencyName: keyof Dependencies,\n ): Router<Dependencies> => {\n if (!Object.hasOwn(routerDependencies, dependencyName)) {\n logger.warn(\n `router.removeDependency`,\n `Attempted to remove non-existent dependency: \"${getTypeDescription(dependencyName)}\"`,\n );\n }\n\n delete routerDependencies[dependencyName];\n\n return router;\n };\n\n router.hasDependency = (dependencyName: keyof Dependencies): boolean => {\n return Object.hasOwn(routerDependencies, dependencyName);\n };\n\n router.resetDependencies = (): Router<Dependencies> => {\n for (const key in routerDependencies) {\n delete routerDependencies[key];\n }\n\n return router;\n };\n\n return router;\n };\n}\n","// packages/real-router/modules/core/middleware.ts\n\nimport { logger } from \"@real-router/logger\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type {\n Unsubscribe,\n DefaultDependencies,\n Middleware,\n MiddlewareFactory,\n Router,\n} from \"core-types\";\n\n/**\n * Gets a displayable name for a factory function.\n * Returns \"anonymous\" for arrow functions or unnamed functions.\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\nfunction getFactoryName(factory: Function): string {\n if (factory.name) {\n return factory.name;\n }\n\n return \"anonymous\";\n}\n\n/**\n * Middleware registry limits to prevent memory leaks and architectural issues.\n * Based on practical experience with production routers.\n */\nconst MIDDLEWARE_LIMITS = {\n WARN: 15, // Log warning - consider refactoring\n ERROR: 30, // Log error - architectural problem\n HARD_LIMIT: 50, // Throw error - critical issue\n} as const;\n\n/**\n * Validates that a value is a valid middleware factory function.\n * Provides clear error messages for debugging.\n *\n * @param middlewareFactory - Value to validate\n * @param index - Position in the array for better error messages\n * @throws {TypeError} If the value is not a function\n */\nfunction validateMiddlewareFactory<Dependencies extends DefaultDependencies>(\n middlewareFactory: unknown,\n index: number,\n): asserts middlewareFactory is MiddlewareFactory<Dependencies> {\n if (typeof middlewareFactory !== \"function\") {\n throw new TypeError(\n `[router.useMiddleware] Expected middleware factory function at index ${index}, ` +\n `got ${getTypeDescription(middlewareFactory)}`,\n );\n }\n}\n\n/**\n * Validates that a middleware factory returned a valid middleware function.\n * Runtime protection against incorrect middleware implementations.\n *\n * @param middleware - Return value from middleware factory\n * @param factory - The factory that produced this middleware (for error context)\n * @throws {TypeError} If the middleware is not a function\n */\nfunction validateMiddleware<Dependencies extends DefaultDependencies>(\n middleware: unknown,\n factory: MiddlewareFactory<Dependencies>,\n): asserts middleware is Middleware {\n if (typeof middleware !== \"function\") {\n throw new TypeError(\n `[router.useMiddleware] Middleware factory must return a function, ` +\n `got ${getTypeDescription(middleware)}. ` +\n `Factory: ${getFactoryName(factory)}`,\n );\n }\n}\n\n/**\n * Checks the total middleware count and emits warnings/errors based on thresholds.\n * Prevents memory leaks and architectural degradation.\n *\n * @param newCount - Number of middleware to be added\n * @param currentSize - Current number of registered middleware\n * @throws {Error} If adding would exceed hard limit\n */\nfunction validateMiddlewareCount(newCount: number, currentSize: number): void {\n const totalSize = newCount + currentSize;\n\n // Hard limit check - fail fast to prevent memory issues\n if (totalSize > MIDDLEWARE_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.useMiddleware] Middleware limit exceeded (${MIDDLEWARE_LIMITS.HARD_LIMIT}). ` +\n `Current: ${currentSize}, Attempting to add: ${newCount}. ` +\n `This indicates an architectural problem. Consider consolidating middleware.`,\n );\n }\n\n // Graduated warnings for early problem detection\n if (totalSize >= MIDDLEWARE_LIMITS.ERROR) {\n logger.error(\n \"router.useMiddleware\",\n `${totalSize} middleware registered! ` +\n `This is excessive and will impact performance. ` +\n `Hard limit at ${MIDDLEWARE_LIMITS.HARD_LIMIT}.`,\n );\n } else if (totalSize >= MIDDLEWARE_LIMITS.WARN) {\n logger.warn(\n \"router.useMiddleware\",\n `${totalSize} middleware registered. ` + `Consider if all are necessary.`,\n );\n }\n}\n\n/**\n * Adds middleware capabilities to a router instance.\n * Middleware functions are executed during navigation transitions.\n *\n * Design decisions:\n * - Uses Set for O(1) duplicate detection and removal\n * - Maintains Map for factory->function mapping\n * - Preserves insertion order (important for middleware chain)\n * - Atomic operations with rollback on failure\n * - Prevents duplicate registrations\n *\n * @param router - Router instance to enhance\n * @returns Enhanced router with middleware methods\n */\nexport function withMiddleware<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n // Use Set for efficient O(1) operations and automatic deduplication\n const middlewareFactories = new Set<MiddlewareFactory<Dependencies>>();\n\n // Map factories to their produced middleware for efficient lookup\n const factoryToMiddleware = new Map<\n MiddlewareFactory<Dependencies>,\n Middleware\n >();\n\n /**\n * Registers one or more middleware factories with the router.\n * Middleware are executed in order during navigation transitions.\n *\n * @param passedMiddlewareFactories - Factory functions that create middleware\n * @returns Unsubscribe function to remove all added middleware\n * @throws {TypeError} If any factory is not a function\n * @throws {Error} If factory is already registered or limit exceeded\n *\n * @example\n * const unsubscribe = router.useMiddleware(\n * authMiddleware,\n * loggingMiddleware\n * );\n * // Later: unsubscribe() to remove both\n */\n router.useMiddleware = (\n ...passedMiddlewareFactories: MiddlewareFactory<Dependencies>[]\n ): Unsubscribe => {\n // Early validation before any state changes\n validateMiddlewareCount(\n passedMiddlewareFactories.length,\n middlewareFactories.size,\n );\n\n // Validate ALL factories first (atomicity principle)\n passedMiddlewareFactories.forEach((factory, index) => {\n validateMiddlewareFactory<Dependencies>(factory, index);\n\n // Prevent duplicate registrations to avoid confusion\n if (middlewareFactories.has(factory)) {\n throw new Error(\n `[router.useMiddleware] Middleware factory already registered. ` +\n `To re-register, first unsubscribe the existing middleware. ` +\n `Factory: ${getFactoryName(factory)}`,\n );\n }\n });\n\n // Track successfully initialized middleware for potential rollback\n const initialized: {\n factory: MiddlewareFactory<Dependencies>;\n middleware: Middleware;\n }[] = [];\n\n // Initialize phase with rollback capability\n try {\n for (const factory of passedMiddlewareFactories) {\n // Create middleware instance with router context\n const middleware = factory(router, router.getDependency);\n\n // Validate the produced middleware\n validateMiddleware<Dependencies>(middleware, factory);\n\n initialized.push({ factory, middleware });\n }\n } catch (error) {\n // Rollback: Clean up any successfully initialized middleware\n // This ensures atomicity - either all succeed or none are registered\n logger.error(\n \"router.useMiddleware\",\n \"Failed to initialize middleware, rolling back\",\n error,\n );\n\n // No cleanup needed as we haven't modified state yet\n throw error;\n }\n\n // Commit phase: All validations passed, update state atomically\n for (const { factory, middleware } of initialized) {\n middlewareFactories.add(factory);\n factoryToMiddleware.set(factory, middleware);\n }\n\n // Return unsubscribe function specific to THIS call's middleware\n return (): void => {\n // Remove only the middleware added in THIS specific call\n for (const { factory } of initialized) {\n const wasDeleted = middlewareFactories.delete(factory);\n\n if (!wasDeleted) {\n // This shouldn't happen but log for debugging\n logger.warn(\n \"router.useMiddleware\",\n `Attempted to remove non-existent middleware factory. ` +\n `This might indicate a memory leak or incorrect cleanup logic.`,\n );\n }\n\n // Clean up the mapping\n factoryToMiddleware.delete(factory);\n }\n };\n };\n\n /**\n * Removes all registered middleware from the router.\n * Useful for testing or complete router reset.\n *\n * @returns The router instance for chaining\n */\n router.clearMiddleware = (): Router<Dependencies> => {\n // Clear both collections efficiently\n middlewareFactories.clear();\n factoryToMiddleware.clear();\n\n return router;\n };\n\n /**\n * Returns a copy of registered middleware factories.\n * Preserves insertion order (important for middleware chain).\n *\n * @internal Used by router.clone(). Will be removed from public API.\n * @deprecated Use behavior testing instead of checking internal state\n * @returns Array of middleware factories in registration order\n */\n router.getMiddlewareFactories = (): MiddlewareFactory<Dependencies>[] => {\n // Return a copy to prevent external mutations\n // Set iterator preserves insertion order (ES2015 guarantee)\n return [...middlewareFactories];\n };\n\n /**\n * Returns the actual middleware functions in execution order.\n * Used internally by the transition system.\n *\n * @internal Used by transition execution. Not part of public API.\n * @returns Array of middleware functions ready for execution\n */\n router.getMiddlewareFunctions = (): Middleware[] => {\n // Return middleware functions in insertion order\n // Map preserves insertion order (ES2015 guarantee)\n return [...factoryToMiddleware.values()];\n };\n\n return router;\n}\n","// packages/real-router/modules/transition/makeError.ts\n\nimport type { RouterError } from \"@real-router/core\";\n\n// Helper: Creating an error with code\nexport const makeError = (\n code: string,\n err?: RouterError,\n): RouterError | undefined => {\n if (!err) {\n return undefined;\n }\n\n err.setCode(code);\n\n return err;\n};\n","// packages/real-router/modules/transition/mergeStates.ts\n\nimport type { Params, State, StateMeta } from \"core-types\";\n\n/**\n * Merges two states with toState taking priority over fromState.\n *\n * Priority order for state fields: toState > fromState\n * Priority order for meta fields: toState.meta > fromState.meta > defaults\n *\n * Special case: meta.params are merged (not replaced):\n * { ...toState.meta.params, ...fromState.meta.params }\n *\n * @param toState - Target state (higher priority)\n * @param fromState - Source state (lower priority)\n * @returns New merged state object\n */\nexport const mergeStates = (toState: State, fromState: State): State => {\n const toMeta = toState.meta;\n const fromMeta = fromState.meta;\n\n // Optimization #1: Conditional merge for params\n // Use spread only when both are defined\n const toParams = toMeta?.params;\n const fromParams = fromMeta?.params;\n\n // Both have params - need to merge; otherwise use whichever is defined\n const metaParams: Params =\n toParams && fromParams\n ? { ...toParams, ...fromParams }\n : (toParams ?? fromParams ?? {});\n\n // Optimization #2: Build meta with defaults, then apply fromMeta, then toMeta\n // Note: StateMeta can have custom fields added by guards/middleware, so we preserve them\n const resultMeta: StateMeta = {\n // Defaults first\n id: 1,\n options: {},\n redirected: false,\n // fromMeta fields (lower priority, may include custom fields)\n ...fromMeta,\n // toMeta fields (higher priority, may include custom fields)\n ...toMeta,\n // Explicitly set params to our merged version (override spread)\n params: metaParams,\n };\n\n // Optimization #4: Copy all toState fields (including custom ones)\n // then explicitly set meta to our merged version\n // Note: State can have custom fields added by middleware, so we must preserve them\n return {\n ...toState,\n meta: resultMeta,\n };\n};\n","// packages/real-router/modules/transition/processLifecycleResult.ts\n\n/* eslint-disable promise/always-return, promise/no-callback-in-promise */\nimport { isPromise, isState } from \"type-guards\";\n\nimport { errorCodes, RouterError } from \"@real-router/core\";\n\nimport type { DoneFn, State, ActivationFn } from \"core-types\";\n\n// Helper: Lifecycle results Processing Function\nexport const processLifecycleResult = (\n result: ReturnType<ActivationFn>,\n done: DoneFn,\n segment?: string,\n): void => {\n const errorData = segment ? { segment } : {};\n\n if (result === undefined) {\n // We expect a Done call\n return;\n }\n\n if (typeof result === \"boolean\") {\n if (result) {\n done();\n } else {\n done(new RouterError(errorCodes.TRANSITION_ERR, errorData));\n }\n\n return;\n }\n\n if (isState(result)) {\n // Type guard should narrow, but TypeScript needs help\n done(undefined, result);\n\n return;\n }\n\n if (isPromise<State | boolean | undefined>(result)) {\n // Callback-based API: promise handled internally, not returned\n // Mixing promises with callbacks is intentional for backward compatibility\n // Type assertion needed due to complex union type narrowing\n // Optimization: .then(onFulfill, onReject) instead of .then().catch()\n // This saves 1 Promise allocation per async middleware call\n void result.then(\n (resVal) => {\n // Issue #38: Handle Promise<boolean> same as sync boolean\n if (typeof resVal === \"boolean\") {\n if (resVal) {\n done();\n } else {\n done(new RouterError(errorCodes.TRANSITION_ERR, errorData));\n }\n } else {\n done(undefined, resVal);\n }\n },\n (error_: unknown) => {\n let error: {\n [key: string]: unknown;\n message?: string | undefined;\n segment?: string | undefined;\n } = errorData;\n\n if (error_ instanceof Error) {\n error = {\n ...errorData,\n message: error_.message,\n stack: error_.stack,\n };\n\n // Error.cause requires ES2022+ - safely access it if present\n if (\"cause\" in error_ && error_.cause !== undefined) {\n error.cause = error_.cause;\n }\n } else if (error_ && typeof error_ === \"object\") {\n error = { ...errorData, ...error_ };\n }\n\n done(new RouterError(errorCodes.TRANSITION_ERR, error));\n },\n );\n\n return;\n }\n\n // This should never be reached - all valid ActivationFn return types are handled above\n // If we get here, it means the activation function returned an unexpected type\n done(\n new RouterError(errorCodes.TRANSITION_ERR, {\n ...errorData,\n message: `Invalid lifecycle result type: ${typeof result}`,\n }),\n );\n};\n","// packages/real-router/modules/transition/wrapSyncError.ts\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// Reserved properties that conflict with RouterError constructor\n// Issue #39: Filter these when wrapping sync errors to avoid TypeError\nconst reservedRouterErrorProps = new Set([\n \"code\",\n \"segment\",\n \"path\",\n \"redirect\",\n]);\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 - Optional route segment name (for lifecycle hooks)\n * @returns Structured error metadata for RouterError\n *\n * @example\n * ```typescript\n * try {\n * hookFn();\n * } catch (error) {\n * const metadata = wrapSyncError(error, \"users.profile\");\n * done(new RouterError(errorCodes.TRANSITION_ERR, metadata));\n * }\n * ```\n */\nexport function wrapSyncError(\n thrown: unknown,\n segment?: string,\n): SyncErrorMetadata {\n // Base metadata - always include segment if provided\n const base: SyncErrorMetadata = segment ? { 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 // Issue #39: Skip reserved properties to avoid RouterError constructor TypeError\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","// packages/real-router/modules/transition/executeLifecycleHooks.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { isState } from \"type-guards\";\n\nimport { errorCodes, RouterError } from \"@real-router/core\";\n\nimport { makeError } from \"./makeError\";\nimport { mergeStates } from \"./mergeStates\";\nimport { processLifecycleResult } from \"./processLifecycleResult\";\nimport { wrapSyncError } from \"./wrapSyncError\";\n\nimport type {\n DoneFn,\n State,\n ActivationFn,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\n/**\n * Strict callback type where state is always provided.\n *\n * @internal\n */\ntype StrictDoneFn = (error: RouterErrorType | undefined, state: State) => void;\n\n/**\n * Safely invokes a callback, catching and logging any errors.\n *\n * @internal\n */\nfunction safeCallback(\n callback: StrictDoneFn,\n error: RouterErrorType | undefined,\n state: State,\n): void {\n try {\n callback(error, state);\n } catch (error_) {\n logger.error(\"core:lifecycle\", \"Error in lifecycle callback:\", error_);\n }\n}\n\n// Helper: execution of the Lifecycle Hooks group\nexport const executeLifecycleHooks = (\n hooks: Map<string, ActivationFn>,\n toState: State,\n fromState: State | undefined,\n segments: string[],\n errorCode: string,\n isCancelled: () => boolean,\n callback: StrictDoneFn,\n): void => {\n let currentState = toState;\n const segmentsToProcess = segments.filter((name) => hooks.has(name));\n\n if (segmentsToProcess.length === 0) {\n safeCallback(callback, undefined, currentState);\n\n return;\n }\n\n let index = 0;\n\n // If the transition is cancelled, we will not process the hooks\n // Guards cannot redirect - they can only allow (true/undefined) or block (false/error)\n const done: DoneFn = (err, state) => {\n if (err) {\n // Guards cannot redirect - convert any redirect to error\n if (err.redirect) {\n const errorWithoutRedirect = new RouterError(errorCode, {\n message: \"Guards cannot redirect. Use middleware for redirects.\",\n attemptedRedirect: err.redirect,\n });\n\n processNext(errorWithoutRedirect);\n } else {\n processNext(err);\n }\n } else {\n processNext(undefined, state);\n }\n };\n\n const processNext = (err?: RouterErrorType, newState?: State): void => {\n if (isCancelled()) {\n safeCallback(\n callback,\n new RouterError(errorCodes.TRANSITION_CANCELLED),\n currentState,\n );\n\n return;\n }\n\n if (err) {\n safeCallback(callback, makeError(errorCode, err), currentState);\n\n return;\n }\n\n // Processing a new state\n // Optimization: Early return for undefined newState (most common case ~90%+)\n // This avoids isState() call and subsequent checks\n if (!newState) {\n // Fast path: skip all checks\n } else if (newState !== currentState && isState(newState)) {\n // Guards cannot redirect to a different route\n if (newState.name !== currentState.name) {\n const redirectNotAllowedErr = new RouterError(errorCode, {\n message: \"Guards cannot redirect to different route. Use middleware.\",\n attemptedRedirect: {\n name: newState.name,\n params: newState.params,\n path: newState.path,\n },\n });\n\n safeCallback(callback, redirectNotAllowedErr, currentState);\n\n return;\n }\n\n // Same route - safe to merge (param modifications, meta changes)\n const hasChanged =\n newState.params !== currentState.params ||\n newState.path !== currentState.path;\n\n if (hasChanged) {\n logger.error(\n \"core:transition\",\n \"Warning: State mutated during transition\",\n { from: currentState, to: newState },\n );\n }\n\n currentState = mergeStates(newState, currentState);\n }\n\n if (index >= segmentsToProcess.length) {\n safeCallback(callback, undefined, currentState);\n\n return;\n }\n\n const segment = segmentsToProcess[index++];\n // Safe cast: segmentsToProcess only contains names that exist in hooks (filtered above)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed by filter\n const hookFn = hooks.get(segment)!;\n\n try {\n const result = hookFn.call(null, currentState, fromState, done);\n\n processLifecycleResult(result, done, segment);\n } catch (syncError: unknown) {\n // Note: TRANSITION_ERR is placeholder - makeError() will set correct code\n done(\n new RouterError(\n errorCodes.TRANSITION_ERR,\n wrapSyncError(syncError, segment),\n ),\n );\n }\n };\n\n processNext();\n};\n","// packages/real-router/modules/transition/executeMiddleware.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { isState } from \"type-guards\";\n\nimport { errorCodes, RouterError } from \"@real-router/core\";\n\nimport { makeError } from \"./makeError\";\nimport { mergeStates } from \"./mergeStates\";\nimport { processLifecycleResult } from \"./processLifecycleResult\";\nimport { wrapSyncError } from \"./wrapSyncError\";\n\nimport type {\n DoneFn,\n State,\n ActivationFn,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\n/**\n * Strict callback type where state is always provided.\n *\n * @internal\n */\ntype StrictDoneFn = (error: RouterErrorType | undefined, state: State) => void;\n\n/**\n * Safely invokes a callback, catching and logging any errors.\n *\n * @internal\n */\nfunction safeCallback(\n callback: StrictDoneFn,\n error: RouterErrorType | undefined,\n state: State,\n): void {\n try {\n callback(error, state);\n } catch (error_) {\n logger.error(\n \"real-router:middleware\",\n \"Error in middleware callback:\",\n error_,\n );\n }\n}\n\n// Helper: processing middleware\nexport const executeMiddleware = (\n middlewareFunctions: ActivationFn[],\n toState: State,\n fromState: State | undefined,\n isCancelled: () => boolean,\n callback: StrictDoneFn,\n): void => {\n let currentState = toState;\n let index = 0;\n\n // If the transition is cancelled, we will not process the middleware\n // Note: Middleware redirects are not supported - errors pass through\n const done: DoneFn = (err, state) => {\n if (err) {\n processNext(err);\n } else {\n processNext(undefined, state);\n }\n };\n\n const processNext = (err?: RouterErrorType, newState?: State): void => {\n if (isCancelled()) {\n safeCallback(\n callback,\n new RouterError(errorCodes.TRANSITION_CANCELLED),\n currentState,\n );\n\n return;\n }\n\n if (err) {\n safeCallback(\n callback,\n makeError(errorCodes.TRANSITION_ERR, err),\n currentState,\n );\n\n return;\n }\n\n // Processing a new state\n // Optimization: Early return for undefined newState (most common case ~90%+)\n // This avoids isState() call and subsequent checks\n if (!newState) {\n // Fast path: skip all checks\n } else if (newState !== currentState && isState(newState)) {\n const hasChanged =\n newState.name !== currentState.name ||\n newState.params !== currentState.params ||\n newState.path !== currentState.path;\n\n if (hasChanged) {\n logger.error(\n \"real-router:middleware\",\n \"Warning: State mutated during middleware execution\",\n { from: currentState, to: newState },\n );\n }\n\n currentState = mergeStates(newState, currentState);\n }\n\n if (index >= middlewareFunctions.length) {\n safeCallback(callback, undefined, currentState);\n\n return;\n }\n\n const middlewareFn = middlewareFunctions[index++];\n\n try {\n const result = middlewareFn.call(null, currentState, fromState, done);\n\n processLifecycleResult(result, done);\n } catch (syncError: unknown) {\n done(\n new RouterError(errorCodes.TRANSITION_ERR, wrapSyncError(syncError)),\n );\n }\n };\n\n processNext();\n};\n","// packages/real-router/modules/transitionPath.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { validateState } from \"type-guards\";\n\nimport type { Params, State } from \"core-types\";\n\n/**\n * Parameters extracted from a route segment.\n * Maps parameter names to their string values.\n */\ntype SegmentParams = Record<string, string>;\n\n/**\n * Represents a transition path between two router states.\n * Contains information about which route segments need to be activated/deactivated.\n */\ninterface TransitionPath {\n /** The common ancestor route segment where paths diverge */\n intersection: string;\n /** Route segments that need to be deactivated (in reverse order) */\n toDeactivate: string[];\n /** Route segments that need to be activated (in order) */\n toActivate: string[];\n}\n\n// Constants for better maintainability\nconst ROUTE_SEGMENT_SEPARATOR = \".\";\nconst EMPTY_INTERSECTION = \"\";\nconst DEFAULT_ROUTE_NAME = \"\";\n\n/**\n * Builds a reversed copy of a string array.\n * Optimization: single pass instead of creating intermediate array with .toReversed().\n *\n * @param arr - Source array\n * @returns New array with elements in reverse order\n * @internal\n */\nfunction reverseArray(arr: string[]): string[] {\n const len = arr.length;\n const result: string[] = [];\n\n for (let i = len - 1; i >= 0; i--) {\n result.push(arr[i]);\n }\n\n return result;\n}\n\n/**\n * Handles conversion of route names with many segments (5+).\n * Internal helper for nameToIDs function.\n *\n * Uses optimized hybrid approach: split to get segments, then slice original\n * string to build cumulative paths. This approach is 65-81% faster than\n * string concatenation for typical cases (5-10 segments).\n *\n * @param name - Route name with 5 or more segments\n * @returns Array of cumulative segment IDs\n * @throws {Error} If route depth exceeds maximum allowed\n * @internal\n */\nfunction nameToIDsGeneral(name: string): string[] {\n // We know there are at least 5 segments at this point (after fast paths)\n const segments = name.split(ROUTE_SEGMENT_SEPARATOR);\n const segmentCount = segments.length;\n\n // First segment is always just itself\n const ids: string[] = [segments[0]];\n\n // Calculate cumulative lengths and slice from original string\n // This avoids repeated string concatenation (O(k²) → O(k))\n let cumulativeLen = segments[0].length;\n\n for (let i = 1; i < segmentCount - 1; i++) {\n cumulativeLen += 1 + segments[i].length; // +1 for dot separator\n ids.push(name.slice(0, cumulativeLen));\n }\n\n // Last segment is always the full route name\n ids.push(name);\n\n return ids;\n}\n\n/**\n * Extracts segment-specific parameters from a state object.\n * Only includes parameters that are valid for serialization (primitives).\n *\n * @param name - Segment name to extract parameters for\n * @param state - State containing the parameters\n * @returns Object with extracted segment parameters\n */\nfunction extractSegmentParams(name: string, state: State): SegmentParams {\n const keys = state.meta?.params[name];\n\n // No parameters defined for this segment\n if (!keys || typeof keys !== \"object\") {\n return {};\n }\n\n const result: SegmentParams = {};\n\n for (const key in keys as Params) {\n // Skip inherited properties\n if (!Object.hasOwn(keys, key)) {\n continue;\n }\n\n // Skip undefined values for consistent behavior (treat { key: undefined } same as missing key)\n // Edge case: can appear from manual State creation or object merging\n // @ts-expect-error Params type doesn't allow undefined, but it can appear at runtime\n if (keys[key] === undefined) {\n continue;\n }\n\n const value = state.params[key];\n\n // Skip null/undefined values\n if (value == null) {\n continue;\n }\n\n // Check type and add to result\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n result[key] = String(value);\n } else {\n // Warn about unsupported complex types (arrays, nested objects)\n // Note: After null check and primitive check, only objects remain here.\n // symbol/function/bigint are rejected by isParams validation before reaching this code.\n logger.warn(\n \"transitionPath.extractSegmentParams\",\n `Unsupported param type for key \"${key}\": ${typeof value}. ` +\n `Only primitives (string, number, boolean) are supported.`,\n typeof value,\n );\n }\n }\n\n return result;\n}\n\n/**\n * Finds the point where two state paths diverge based on segments and parameters.\n * Compares both segment names and their parameters to find the first difference.\n *\n * @param toState - Target state\n * @param fromState - Source state\n * @param toStateIds - Segment IDs for target state\n * @param fromStateIds - Segment IDs for source state\n * @param maxI - Maximum index to check (minimum of both arrays)\n * @returns Index of first difference, or maxI if all checked segments match\n */\nfunction pointOfDifference(\n toState: State,\n fromState: State,\n toStateIds: string[],\n fromStateIds: string[],\n maxI: number,\n): number {\n for (let i = 0; i < maxI; i++) {\n const toSegment = toStateIds[i];\n const fromSegment = fromStateIds[i];\n\n // Different segment names - immediate difference\n if (toSegment !== fromSegment) {\n return i;\n }\n\n // Same segment name - check parameters\n const toParams = extractSegmentParams(toSegment, toState);\n const fromParams = extractSegmentParams(fromSegment, fromState);\n\n // Fast check: different number of parameters\n const toKeys = Object.keys(toParams);\n const fromKeys = Object.keys(fromParams);\n\n if (toKeys.length !== fromKeys.length) {\n return i;\n }\n\n // Detailed check: compare parameter values\n for (const key of toKeys) {\n if (toParams[key] !== fromParams[key]) {\n return i;\n }\n }\n }\n\n return maxI;\n}\n\n/**\n * Converts a route name to an array of hierarchical segment identifiers.\n * Each segment ID includes all parent segments in the path.\n *\n * @param name - Route name in dot notation (e.g., 'users.profile.edit')\n * @returns Array of cumulative segment IDs\n * @throws {Error} If route depth exceeds maximum allowed depth\n *\n * @example\n * // Simple route\n * nameToIDs('users');\n * // Returns: ['users']\n *\n * @example\n * // Nested route\n * nameToIDs('users.profile.edit');\n * // Returns: ['users', 'users.profile', 'users.profile.edit']\n *\n * @example\n * // Empty string (root route)\n * nameToIDs('');\n * // Returns: ['']\n *\n * @remarks\n * Input parameter is NOT validated in this function for performance reasons.\n * Validation significantly slows down nameToIDs execution.\n * The input should be validated by the function/method that calls nameToIDs.\n */\nexport function nameToIDs(name: string): string[] {\n // ===== FAST PATH 1: Empty string (root route) =====\n // Most common in initial navigation\n if (!name) {\n return [DEFAULT_ROUTE_NAME];\n }\n\n // ===== FAST PATH 2: Single segment (no dots) =====\n // Very common: 'home', 'users', 'settings', etc.\n const firstDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR);\n\n if (firstDot === -1) {\n return [name];\n }\n\n // ===== FAST PATH 3: Two segments =====\n // Common: 'users.list', 'admin.dashboard', etc.\n const secondDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR, firstDot + 1);\n\n if (secondDot === -1) {\n return [\n name.slice(0, firstDot), // 'users'\n name, // 'users.list'\n ];\n }\n\n // ===== FAST PATH 4: Three segments =====\n // Common: 'users.profile.edit', 'app.settings.general', etc.\n const thirdDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR, secondDot + 1);\n\n if (thirdDot === -1) {\n return [\n name.slice(0, firstDot), // 'users'\n name.slice(0, secondDot), // 'users.profile'\n name, // 'users.profile.edit'\n ];\n }\n\n // ===== FAST PATH 5: Four segments =====\n const fourthDot = name.indexOf(ROUTE_SEGMENT_SEPARATOR, thirdDot + 1);\n\n if (fourthDot === -1) {\n return [\n name.slice(0, firstDot),\n name.slice(0, secondDot),\n name.slice(0, thirdDot),\n name,\n ];\n }\n\n // ===== STANDARD PATH: 5+ segments =====\n // Less common, use general algorithm with optimizations\n return nameToIDsGeneral(name);\n}\n\n/**\n * Calculates the transition path between two router states.\n * Determines which route segments need to be deactivated and activated\n * to transition from one state to another.\n *\n * @param toState - Target state to transition to\n * @param fromState - Current state to transition from (optional)\n * @returns Transition path with intersection and segments to activate/deactivate\n *\n * @throws {TypeError} When toState is null or undefined\n * @throws {TypeError} When toState is not an object\n * @throws {TypeError} When toState.name is missing or not a string\n * @throws {TypeError} When toState.params is missing or not an object\n * @throws {TypeError} When toState.path is missing or not a string\n * @throws {TypeError} When toState.name contains invalid route format:\n * - Contains only whitespace (e.g., \" \")\n * - Has consecutive dots (e.g., \"users..profile\")\n * - Has leading/trailing dots (e.g., \".users\" or \"users.\")\n * - Segments don't match pattern [a-zA-Z_][a-zA-Z0-9_-]* (e.g., \"users.123\")\n * - Contains spaces or special characters (e.g., \"users profile\")\n * - Exceeds maximum length (8192 characters)\n * @throws {TypeError} When fromState is provided and has any of the validation errors listed above for toState\n *\n * @example\n * // ✅ Valid calls\n * getTransitionPath({ name: 'users.profile', params: {}, path: '/users/profile' });\n * getTransitionPath(toState, fromState);\n * getTransitionPath({ name: '', params: {}, path: '/' }); // root route\n *\n * @example\n * // ❌ Invalid calls that throw TypeError\n * getTransitionPath(null); // toState is null\n * getTransitionPath(undefined); // toState is undefined\n * getTransitionPath({}); // missing required fields\n * getTransitionPath({ name: 123, params: {}, path: '/' }); // name not a string\n * getTransitionPath({ name: 'home', path: '/' }); // missing params\n * getTransitionPath({ name: 'users..profile', params: {}, path: '/' }); // consecutive dots\n * getTransitionPath({ name: '.users', params: {}, path: '/' }); // leading dot\n * getTransitionPath({ name: 'users.', params: {}, path: '/' }); // trailing dot\n * getTransitionPath({ name: 'users profile', params: {}, path: '/' }); // contains space\n * getTransitionPath({ name: 'users.123', params: {}, path: '/' }); // segment starts with number\n * getTransitionPath(validToState, { name: 'invalid..route', params: {}, path: '/' }); // fromState invalid\n *\n * @example\n * // Full activation (no fromState)\n * getTransitionPath(makeState('users.profile'));\n * // Returns: {\n * // intersection: '',\n * // toActivate: ['users', 'users.profile'],\n * // toDeactivate: []\n * // }\n *\n * @example\n * // Partial transition with common ancestor\n * getTransitionPath(\n * makeState('users.profile'),\n * makeState('users.list')\n * );\n * // Returns: {\n * // intersection: 'users',\n * // toActivate: ['users.profile'],\n * // toDeactivate: ['users.list']\n * // }\n *\n * @example\n * // Complete route change\n * getTransitionPath(\n * makeState('admin.dashboard'),\n * makeState('users.profile')\n * );\n * // Returns: {\n * // intersection: '',\n * // toActivate: ['admin', 'admin.dashboard'],\n * // toDeactivate: ['users.profile', 'users']\n * // }\n */\nexport function getTransitionPath(\n toState: State,\n fromState?: State,\n): TransitionPath {\n // Validate required toState\n validateState(toState, \"getTransitionPath\");\n\n // ===== FAST PATH 1: Initial navigation (no fromState) =====\n // This is the best performing case in benchmarks (5M ops/sec)\n if (!fromState) {\n return {\n intersection: EMPTY_INTERSECTION,\n toActivate: nameToIDs(toState.name),\n toDeactivate: [],\n };\n }\n\n // Validate optional fromState\n validateState(fromState, \"getTransitionPath\");\n\n const toStateOptions = toState.meta?.options ?? {};\n\n // ===== FAST PATH 2: Force reload =====\n // Skip all optimization when reload is requested\n if (toStateOptions.reload) {\n return {\n intersection: EMPTY_INTERSECTION,\n toActivate: nameToIDs(toState.name),\n toDeactivate: reverseArray(nameToIDs(fromState.name)),\n };\n }\n\n // ===== FAST PATH 3: Missing meta or meta.params requires full reload =====\n // Check if meta or meta.params is actually missing (not just empty)\n const toHasMeta = toState.meta?.params !== undefined;\n const fromHasMeta = fromState.meta?.params !== undefined;\n\n if (!toHasMeta && !fromHasMeta) {\n // Both states missing meta.params - require full reload\n return {\n intersection: EMPTY_INTERSECTION,\n toActivate: nameToIDs(toState.name),\n toDeactivate: reverseArray(nameToIDs(fromState.name)),\n };\n }\n\n // ===== FAST PATH 4: Same routes with empty meta.params =====\n // If both have empty meta.params {}, no parameter checking needed\n if (toState.name === fromState.name && toHasMeta && fromHasMeta) {\n const toParamsEmpty =\n toState.meta && Object.keys(toState.meta.params).length === 0;\n const fromParamsEmpty =\n fromState.meta && Object.keys(fromState.meta.params).length === 0;\n\n if (toParamsEmpty && fromParamsEmpty) {\n // Both have empty params - no transition needed\n return {\n intersection: toState.name,\n toActivate: [],\n toDeactivate: [],\n };\n }\n }\n\n // ===== STANDARD PATH: Routes with parameters =====\n // Use original algorithm for complex cases with parameters\n const toStateIds = nameToIDs(toState.name);\n const fromStateIds = nameToIDs(fromState.name);\n const maxI = Math.min(fromStateIds.length, toStateIds.length);\n\n // Find where paths diverge based on segments and parameters\n // not obvious validate toState and fromState\n const i = pointOfDifference(\n toState,\n fromState,\n toStateIds,\n fromStateIds,\n maxI,\n );\n\n // Optimization: Build deactivation list in reverse order directly\n // instead of slice(i).toReversed() which creates 2 arrays\n const toDeactivate: string[] = [];\n\n for (let j = fromStateIds.length - 1; j >= i; j--) {\n toDeactivate.push(fromStateIds[j]);\n }\n\n // Build activation list (forward order for proper initialization)\n const toActivate = toStateIds.slice(i);\n\n // Determine intersection point (common ancestor)\n // Note: fromState is guaranteed to be defined here (early return on line 366)\n const intersection = i > 0 ? fromStateIds[i - 1] : EMPTY_INTERSECTION;\n\n return {\n intersection,\n toDeactivate,\n toActivate,\n };\n}\n","// packages/real-router/modules/transition/index.ts\n\nimport { RouterError, constants, errorCodes } from \"@real-router/core\";\n\nimport { executeLifecycleHooks } from \"./executeLifecycleHooks\";\nimport { executeMiddleware } from \"./executeMiddleware\";\nimport { getTransitionPath, nameToIDs } from \"../transitionPath\";\n\nimport type {\n NavigationOptions,\n CancelFn,\n State,\n DefaultDependencies,\n Router,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\n/**\n * Strict callback type where state is always provided.\n * Used internally in transition chain where state is guaranteed.\n */\ntype StrictDoneFn = (error: RouterErrorType | undefined, state: State) => void;\n\nexport function transition<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n transitionCallback: (err: RouterErrorType | undefined, state: State) => void,\n): CancelFn {\n // The state of transaction\n let cancelled = false;\n let completed = false;\n\n // We're caching the necessary data\n const [canDeactivateFunctions, canActivateFunctions] =\n router.getLifecycleFunctions();\n const middlewareFunctions = router.getMiddlewareFunctions();\n const isUnknownRoute = toState.name === constants.UNKNOWN_ROUTE;\n\n // State management functions\n // Issue #36: Check both explicit cancellation AND router shutdown\n // Issue #50: Use isActive() instead of isStarted() for two-phase start support\n // isActive() is true during initial start transition, isStarted() is false\n const isCancelled = () => cancelled || !router.isActive();\n\n const cancel = () => {\n if (!cancelled && !completed) {\n cancelled = true;\n complete(new RouterError(errorCodes.TRANSITION_CANCELLED));\n }\n };\n\n const complete = (err: RouterErrorType | undefined, state?: State) => {\n if (completed) {\n return;\n }\n\n completed = true;\n transitionCallback(err, state ?? toState);\n };\n\n // The main transaction logic\n const runTransition = (): void => {\n const { toDeactivate, toActivate } = getTransitionPath(toState, fromState);\n\n // determine the necessary steps\n const shouldDeactivate =\n fromState && !opts.forceDeactivate && toDeactivate.length > 0;\n const shouldActivate = !isUnknownRoute && toActivate.length > 0;\n const shouldRunMiddleware = middlewareFunctions.length > 0;\n\n // The chain of execution\n const runDeactivation = (callback: StrictDoneFn) => {\n if (shouldDeactivate) {\n executeLifecycleHooks(\n canDeactivateFunctions,\n toState,\n fromState,\n toDeactivate,\n errorCodes.CANNOT_DEACTIVATE,\n isCancelled,\n callback,\n );\n } else {\n callback(undefined, toState);\n }\n };\n\n const runActivation = (state: State, callback: StrictDoneFn) => {\n if (shouldActivate) {\n executeLifecycleHooks(\n canActivateFunctions,\n state,\n fromState,\n toActivate,\n errorCodes.CANNOT_ACTIVATE,\n isCancelled,\n (err, newState) => {\n callback(err, newState);\n },\n );\n } else {\n // State is already frozen from makeState()\n callback(undefined, state);\n }\n };\n\n const runMiddleware = (state: State, callback: StrictDoneFn) => {\n if (shouldRunMiddleware) {\n executeMiddleware(\n middlewareFunctions,\n state,\n fromState,\n isCancelled,\n (err, newState) => {\n callback(err, newState);\n },\n );\n } else {\n // State is already frozen from makeState()\n callback(undefined, state);\n }\n };\n\n // perform a chain\n runDeactivation((err, state) => {\n if (err) {\n complete(err, state);\n\n return;\n }\n\n runActivation(state, (runActivationErr, runActivationState) => {\n if (runActivationErr) {\n complete(runActivationErr, runActivationState);\n\n return;\n }\n\n runMiddleware(\n runActivationState,\n (runMiddlewareErr, runMiddlewareState) => {\n if (runMiddlewareErr) {\n complete(runMiddlewareErr, runMiddlewareState);\n\n return;\n }\n\n // Automatic cleaning of inactive segments\n if (fromState) {\n const activeSegments = nameToIDs(toState.name);\n const previousActiveSegments = nameToIDs(fromState.name);\n const activeSet = new Set(activeSegments);\n\n for (const name of previousActiveSegments) {\n if (!activeSet.has(name) && canDeactivateFunctions.has(name)) {\n router.clearCanDeactivate(name);\n }\n }\n }\n\n complete(undefined, runMiddlewareState);\n },\n );\n });\n });\n };\n\n // Launch transition\n runTransition();\n\n return cancel;\n}\n","// packages/real-router/modules/core/navigation.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { getTypeDescription, isNavigationOptions } from \"type-guards\";\n\nimport { events, errorCodes, constants, RouterError } from \"@real-router/core\";\n\nimport { transition } from \"../transition\";\n\nimport type {\n CancelFn,\n DoneFn,\n NavigationOptions,\n Params,\n State,\n DefaultDependencies,\n Router,\n} from \"core-types\";\n\nconst noop = () => {};\n\n/**\n * Safely invokes a callback, catching and logging any errors.\n * Prevents user callback errors from crashing the router.\n *\n * @internal\n */\nfunction safeCallback(\n callback: DoneFn,\n ...args: [error?: RouterError, state?: State]\n): void {\n try {\n callback(...args);\n } catch (error) {\n logger.error(\"router.navigate\", \"Error in navigation callback:\", error);\n }\n}\n\n/**\n * Result of parsing polymorphic navigate() arguments.\n *\n * @internal\n */\ninterface ParsedNavigateArgs {\n params: Params;\n opts: NavigationOptions;\n callback: DoneFn;\n}\n\n/**\n * Parses the polymorphic arguments of navigate().\n *\n * Handles all valid call signatures:\n * - navigate(name, callback)\n * - navigate(name, params)\n * - navigate(name, params, callback)\n * - navigate(name, params, opts)\n * - navigate(name, params, opts, callback)\n *\n * @internal\n */\nfunction parseNavigateArgs(\n paramsOrDone?: Params | DoneFn,\n optsOrDone?: NavigationOptions | DoneFn,\n done?: DoneFn,\n): ParsedNavigateArgs {\n if (typeof paramsOrDone === \"function\") {\n // Form: navigate(name, callback)\n return { params: {}, opts: {}, callback: paramsOrDone };\n }\n\n // Forms: navigate(name), navigate(name, params), navigate(name, params, callback),\n // navigate(name, params, opts), navigate(name, params, opts, callback)\n // Also handles: navigate(name, null/undefined, callback) - runtime defense\n const params = paramsOrDone ?? {};\n\n if (typeof optsOrDone === \"function\") {\n return { params, opts: {}, callback: optsOrDone };\n }\n\n return {\n params,\n opts: optsOrDone ?? {},\n callback: done ?? noop,\n };\n}\n\nexport function withNavigation<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n let cancelCurrentTransition: CancelFn | null = null;\n let navigating = false;\n\n // Cancel of the previous transition\n const cancel = (): Router<Dependencies> => {\n if (cancelCurrentTransition) {\n cancelCurrentTransition();\n cancelCurrentTransition = null;\n }\n\n navigating = false;\n\n return router;\n };\n\n /**\n * Internal navigation function that accepts pre-built state\n *\n * @internal\n */\n const navigateToState = (\n toState: State,\n fromState: State | undefined,\n opts: NavigationOptions,\n callback: DoneFn,\n emitSuccess: boolean,\n ): CancelFn => {\n // Warn about concurrent navigation (potential SSR race condition)\n if (navigating) {\n logger.warn(\n \"router.navigate\",\n \"Concurrent navigation detected on shared router instance. \" +\n \"For SSR, use router.clone() to create isolated instance per request.\",\n );\n }\n\n // Cancel previous transition\n cancel();\n\n // Set navigating flag BEFORE emitting TRANSITION_START\n // This ensures isNavigating() returns true during event handlers\n navigating = true;\n\n // Emit TRANSITION_START (after navigating flag is set)\n router.invokeEventListeners(events.TRANSITION_START, toState, fromState);\n\n // Create callback for transition\n const transitionCallback = (err: RouterError | undefined, state: State) => {\n navigating = false;\n cancelCurrentTransition = null;\n\n if (!err) {\n // Route was already validated in navigate() via buildState().\n // Since guards can no longer redirect (Issue #55), the state.name cannot change.\n // However, routes can be dynamically removed during async navigation,\n // so we do a lightweight check with hasRoute() instead of full buildState().\n // UNKNOWN_ROUTE is always valid (used for 404 handling).\n if (\n state.name === constants.UNKNOWN_ROUTE ||\n router.hasRoute(state.name)\n ) {\n router.setState(state);\n\n // Emit TRANSITION_SUCCESS only if requested\n if (emitSuccess) {\n router.invokeEventListeners(\n events.TRANSITION_SUCCESS,\n state,\n fromState,\n opts,\n );\n }\n\n // State is already frozen from transition module\n safeCallback(callback, undefined, state);\n } else {\n // Route was removed during async navigation\n const notFoundErr = new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: state.name,\n });\n\n safeCallback(callback, notFoundErr);\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n router.getState(),\n notFoundErr,\n );\n }\n\n return;\n }\n\n // Error handling\n if (err.code === errorCodes.TRANSITION_CANCELLED) {\n router.invokeEventListeners(\n events.TRANSITION_CANCEL,\n toState,\n fromState,\n );\n } else {\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n toState,\n fromState,\n err,\n );\n }\n\n safeCallback(callback, err);\n };\n\n // Launch transition\n cancelCurrentTransition = transition(\n router,\n toState,\n fromState,\n opts,\n transitionCallback,\n );\n\n return cancelCurrentTransition;\n };\n\n router.navigate = function navigate(\n name: string,\n paramsOrDone?: Params | DoneFn,\n optsOrDone?: NavigationOptions | DoneFn,\n done?: DoneFn,\n ): CancelFn {\n // Parse polymorphic arguments first (needed for callback in error case)\n const { params, opts, callback } = parseNavigateArgs(\n paramsOrDone,\n optsOrDone,\n done,\n );\n\n // Quick check of the state of the router\n if (!router.isStarted()) {\n const err = new RouterError(errorCodes.ROUTER_NOT_STARTED);\n\n safeCallback(callback, err);\n\n return noop;\n }\n\n // Validate opts after polymorphic argument resolution\n // Note: Empty object {} is valid, but invalid types/fields are rejected\n if (!isNavigationOptions(opts)) {\n throw new TypeError(\n `[router.navigate] Invalid options: ${getTypeDescription(opts)}. Expected NavigationOptions object.`,\n );\n }\n\n // build route state with segments (avoids duplicate getSegmentsByName call)\n const result = router.buildStateWithSegments(name, params);\n\n if (!result) {\n const err = new RouterError(errorCodes.ROUTE_NOT_FOUND);\n\n safeCallback(callback, err);\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n router.getState(),\n err,\n );\n\n return noop;\n }\n\n const { state: route, segments } = result;\n\n // create a target state\n // Use buildPathWithSegments to avoid duplicate getSegmentsByName in buildPath\n const toState = router.makeState(\n route.name,\n route.params,\n router.buildPathWithSegments(route.name, route.params, segments),\n {\n params: route.meta,\n options: opts,\n redirected: opts.redirected ?? false,\n },\n );\n\n // Early return for skipTransition - no state equality check needed\n // eslint-disable-next-line @typescript-eslint/no-deprecated,sonarjs/deprecation\n if (opts.skipTransition) {\n // toState is already frozen from makeState()\n safeCallback(callback, undefined, toState);\n\n return noop;\n }\n\n const fromState = router.getState();\n\n // Fast verification for the same states\n if (\n !opts.reload &&\n !opts.force &&\n router.areStatesEqual(fromState, toState, false)\n ) {\n const err = new RouterError(errorCodes.SAME_STATES);\n\n safeCallback(callback, err);\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n toState,\n fromState,\n err,\n );\n\n return noop;\n }\n\n // transition execution with TRANSITION_SUCCESS emission\n // Use router.navigateToState instead of local variable to allow mocking in tests\n // Note: Guards cannot redirect - redirects are handled in middleware only\n return router.navigateToState(toState, fromState, opts, callback, true); // emitSuccess = true for public navigate()\n };\n\n router.navigateToDefault = function navigateToDefault(\n optsOrDone?: NavigationOptions | DoneFn,\n done?: DoneFn,\n ): CancelFn {\n const options = router.getOptions();\n\n if (!options.defaultRoute) {\n return noop;\n }\n\n let opts: NavigationOptions = {};\n let callback: DoneFn = noop;\n\n if (typeof optsOrDone === \"function\") {\n callback = optsOrDone;\n } else if (optsOrDone) {\n opts = optsOrDone;\n callback = done ?? noop;\n }\n\n // Validate opts for better error messages (specific to navigateToDefault)\n if (!isNavigationOptions(opts)) {\n throw new TypeError(\n `[router.navigateToDefault] Invalid options: ${getTypeDescription(opts)}. Expected NavigationOptions object.`,\n );\n }\n\n return router.navigate(\n options.defaultRoute,\n options.defaultParams,\n opts,\n callback,\n );\n };\n\n // Expose internal navigation for use by plugins and lifecycle\n router.navigateToState = navigateToState;\n\n /**\n * Checks if a navigation transition is currently in progress.\n *\n * @returns true if navigation is active, false otherwise\n *\n * @example\n * if (router.isNavigating()) {\n * console.log('Navigation in progress...');\n * }\n *\n * @remarks\n * After FSM migration (RFC-2), this will be replaced with:\n * `router.getRouterState() === RouterState.TRANSITIONING`\n */\n router.isNavigating = (): boolean => router.isStarted() && navigating;\n\n return router;\n}\n","// packages/real-router/modules/core/observable.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { isNavigationOptions, isState } from \"type-guards\";\n\nimport { events, RouterError } from \"@real-router/core\";\n\nimport type { plugins } from \"../constants\";\nimport type {\n DefaultDependencies,\n EventName,\n EventsKeys,\n NavigationOptions,\n Plugin,\n Router,\n RouterError as RouterErrorType,\n State,\n SubscribeFn,\n Unsubscribe,\n} from \"core-types\";\n\n/**\n * Symbol.observable polyfill declaration for TC39 proposal\n *\n * @see https://github.com/tc39/proposal-observable\n */\ndeclare global {\n interface SymbolConstructor {\n readonly observable: unique symbol;\n }\n}\n\ntype EventMethodMap = {\n [K in EventsKeys as (typeof events)[K]]: (typeof plugins)[K];\n};\n\n/**\n * Max recursion depth to prevent stack overflow from circular event triggers\n */\nconst MAX_EVENT_DEPTH = 5;\n\n/**\n * Hard limit to prevent memory leaks from exponential listener creation\n */\nconst MAX_LISTENERS_HARD_LIMIT = 10_000;\n\n/**\n * Invoke all listeners for a given event.\n *\n * @template E - Event literal type.\n * @param eventName - The event being dispatched (used only for logging).\n * @param set - Array of callbacks (or undefined).\n * @param args - Arguments to pass to each callback.\n */\nfunction invokeFor<E extends EventName>(\n eventName: E,\n set: Set<Plugin[EventMethodMap[E]]>,\n ...args: Parameters<NonNullable<Plugin[EventMethodMap[E]]>>\n): void {\n if (set.size === 0) {\n return;\n }\n\n // Clone the listeners array so that removals/additions\n // during iteration won't affect this loop.\n const listeners = [...set];\n\n for (const cb of listeners) {\n // Note: cb is guaranteed to be a function because addEventListener\n // validates typeof cb === \"function\" before adding to the set\n try {\n // We can't use cb(...args) due to TypeScript limitations with\n // conditional types, so we use this pattern to invoke the callback\n // with the correct number of arguments from the args array\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type -- Function.prototype.apply requires Function type\n Function.prototype.apply.call(cb as Function, undefined, args);\n } catch (error) {\n logger.error(\"Router\", `Error in listener for ${eventName}:`, error);\n }\n }\n}\n\nexport function withObservability<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n /**\n * Event listeners storage. Using Set for O(1) operations and automatic deduplication.\n * Sets are created lazily to reduce memory footprint when events are not used.\n *\n * Type-safe lazy map that preserves the relationship between event names and their callback types.\n */\n type CallbackSet<E extends EventName> = Set<Plugin[EventMethodMap[E]]>;\n type CallbacksMap = {\n [E in EventName]?: CallbackSet<E>;\n };\n const callbacks: CallbacksMap = {};\n\n /**\n * Gets or creates a Set for the given event name (lazy initialization)\n */\n function getCallbackSet<E extends EventName>(eventName: E): CallbackSet<E> {\n const existing = callbacks[eventName];\n\n if (existing) {\n return existing;\n }\n\n const set = new Set<Plugin[EventMethodMap[E]]>();\n\n // Type assertion needed: TS can't narrow generic E to specific event name\n (callbacks as Record<E, CallbackSet<E>>)[eventName] = set;\n\n return set;\n }\n\n /**\n * Tracks current recursion depth for each event type.\n * Created lazily to reduce memory footprint when events are not dispatched.\n */\n let eventDepthMap: Record<EventName, number> | null = null;\n\n /**\n * Gets or creates the event depth map (lazy initialization)\n */\n const getEventDepthMap = (): Record<EventName, number> => {\n eventDepthMap ??= {\n [events.ROUTER_START]: 0,\n [events.TRANSITION_START]: 0,\n [events.TRANSITION_SUCCESS]: 0,\n [events.TRANSITION_ERROR]: 0,\n [events.TRANSITION_CANCEL]: 0,\n [events.ROUTER_STOP]: 0,\n };\n\n return eventDepthMap;\n };\n\n /**\n * Valid event names for validation (avoids creating objects just for hasOwn check)\n */\n const validEventNames = new Set<EventName>([\n events.ROUTER_START,\n events.TRANSITION_START,\n events.TRANSITION_SUCCESS,\n events.TRANSITION_ERROR,\n events.TRANSITION_CANCEL,\n events.ROUTER_STOP,\n ]);\n\n /**\n * Validates arguments for invokeEventListeners to prevent runtime errors.\n * Checks event name validity, recursion depth, and parameter types.\n * Throws descriptive errors for debugging instead of silent failures.\n */\n const isInvokeEventListenersArgumentsValid = (\n eventName: (typeof events)[EventsKeys],\n ) => {\n if (!validEventNames.has(eventName)) {\n throw new Error(`Invalid event name: ${eventName}`);\n }\n\n const depthMap = getEventDepthMap();\n const depth = depthMap[eventName];\n\n if (depth >= MAX_EVENT_DEPTH) {\n throw new Error(\n `[Router] Maximum recursion depth (${MAX_EVENT_DEPTH}) exceeded for event: ${eventName}`,\n );\n }\n };\n\n /**\n * Validates arguments for add/removeEventListener operations.\n * Ensures event name is valid and callback is a function.\n * Critical for preventing invalid subscriptions that could cause memory leaks.\n */\n const isAddRemoveEventListenersArgumentsValid = <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => {\n if (!validEventNames.has(eventName)) {\n throw new Error(`Invalid event name: ${eventName}`);\n }\n\n if (typeof cb !== \"function\") {\n throw new TypeError(\n `Expected callback to be a function for event ${eventName}`,\n );\n }\n };\n\n /**\n * @internal Central event dispatcher for router core\n * * Uses only for navigate method.\n */\n router.invokeEventListeners = (\n eventName: (typeof events)[EventsKeys],\n toState?: State,\n fromState?: State,\n arg?: RouterErrorType | NavigationOptions,\n // eslint-disable-next-line sonarjs/cognitive-complexity\n ) => {\n isInvokeEventListenersArgumentsValid(eventName);\n\n const depthMap = getEventDepthMap();\n\n try {\n depthMap[eventName]++;\n\n switch (eventName) {\n case events.TRANSITION_START:\n case events.TRANSITION_CANCEL: {\n if (!toState) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is required for event \"${eventName}\"`,\n );\n }\n\n // TODO(private-api): Remove isState() validation when method becomes protected.\n // All internal callers pass states from makeState() (already validated) or getState().\n // Potential savings: ~56-877 ns per call (depends on params depth)\n if (!isState(toState)) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // TODO(private-api): Remove when method becomes protected (fromState from getState())\n if (fromState && !isState(fromState)) {\n throw new TypeError(\n `[router.invokeEventListeners] fromState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // States are already frozen: toState from makeState(), fromState from getState()\n // Use getCallbackSet for lazy initialization\n invokeFor(eventName, getCallbackSet(eventName), toState, fromState);\n\n break;\n }\n case events.TRANSITION_ERROR: {\n // TODO(private-api): Remove isState() validations when method becomes protected.\n // States come from makeState() or getState() - already validated.\n if (toState && !isState(toState)) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // TODO(private-api): Remove when method becomes protected\n if (fromState && !isState(fromState)) {\n throw new TypeError(\n `[router.invokeEventListeners] fromState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n if (!arg) {\n throw new TypeError(\n `[router.invokeEventListeners] error is required for event \"${eventName}\"`,\n );\n }\n\n if (!(arg instanceof RouterError)) {\n throw new TypeError(\n `[router.invokeEventListeners] error must be a RouterError instance for event \"${eventName}\". ` +\n `Got: ${typeof arg === \"object\" ? arg.constructor.name : typeof arg}`,\n );\n }\n\n // States are already frozen if provided: toState from makeState(), fromState from getState()\n // Use getCallbackSet for lazy initialization\n invokeFor(\n eventName,\n getCallbackSet(eventName),\n toState,\n fromState,\n arg,\n );\n\n break;\n }\n case events.TRANSITION_SUCCESS: {\n if (!toState) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is required for event \"${eventName}\"`,\n );\n }\n\n // TODO(private-api): Remove isState() validations when method becomes protected.\n // States come from makeState() or getState() - already validated.\n if (!isState(toState)) {\n throw new TypeError(\n `[router.invokeEventListeners] toState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n // TODO(private-api): Remove when method becomes protected\n if (fromState && !isState(fromState)) {\n throw new TypeError(\n `[router.invokeEventListeners] fromState is invalid for event \"${eventName}\". ` +\n `Expected State object with name, path, and params.`,\n );\n }\n\n if (!arg) {\n throw new TypeError(\n `[router.invokeEventListeners] options is required for event \"${eventName}\"`,\n );\n }\n\n if (arg instanceof RouterError) {\n throw new TypeError(\n `[router.invokeEventListeners] options cannot be a RouterError for event \"${eventName}\". ` +\n `Use TRANSITION_ERROR event for errors.`,\n );\n }\n\n if (!isNavigationOptions(arg)) {\n throw new TypeError(\n `[router.invokeEventListeners] options is invalid for event \"${eventName}\". ` +\n `Expected NavigationOptions object.`,\n );\n }\n\n // States are already frozen: toState from makeState(), fromState from getState()\n // Use getCallbackSet for lazy initialization\n invokeFor(\n eventName,\n getCallbackSet(eventName),\n toState,\n fromState,\n arg,\n );\n\n break;\n }\n // for events.ROUTER_START, events.ROUTER_STOP\n default: {\n // Exhaustive check: at this point only ROUTER_START and ROUTER_STOP should remain\n // TypeScript will error if new event types are added without handling them above\n const _exhaustiveCheck:\n | typeof events.ROUTER_START\n | typeof events.ROUTER_STOP = eventName;\n\n // Use getCallbackSet for lazy initialization\n invokeFor(_exhaustiveCheck, getCallbackSet(_exhaustiveCheck));\n\n break;\n }\n }\n } finally {\n depthMap[eventName]--;\n }\n };\n\n /**\n * Checks if there are any listeners registered for a given event.\n * Used for performance optimization to skip event emission when no listeners exist.\n *\n * @param eventName - The event to check for listeners\n * @returns true if at least one listener is registered, false otherwise\n *\n * @example\n * ```typescript\n * // Skip expensive event emission if no listeners\n * if (router.hasListeners(events.TRANSITION_ERROR)) {\n * router.invokeEventListeners(events.TRANSITION_ERROR, ...);\n * }\n * ```\n *\n * @internal\n */\n router.hasListeners = (eventName: (typeof events)[EventsKeys]): boolean => {\n if (!validEventNames.has(eventName)) {\n return false;\n }\n\n const set = callbacks[eventName];\n\n return set !== undefined && set.size > 0;\n };\n\n /**\n * @internal Use unsubscribe function returned by addEventListener\n * Uses only for plugins.\n * @deprecated Will be protected in next major version\n */\n router.removeEventListener = <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => {\n isAddRemoveEventListenersArgumentsValid(eventName, cb);\n\n // Don't create Set just for removal - check if it exists first\n const set = callbacks[eventName];\n\n if (!set || set.size === 0) {\n return;\n }\n\n const deleted = set.delete(cb);\n\n if (!deleted) {\n // Need for debugging purposes, as it is not an error to remove a listener that was never added.\n // This can happen if the listener was already removed or never added.\n logger.warn(\n \"Router\",\n `Attempted to remove non-existent listener for \"${eventName}\". ` +\n `This might indicate a memory leak or incorrect cleanup logic.`,\n );\n }\n };\n\n router.addEventListener = <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ): Unsubscribe => {\n isAddRemoveEventListenersArgumentsValid(eventName, cb);\n\n const set = getCallbackSet(eventName);\n\n if (set.has(cb)) {\n throw new Error(\n `[router.addEventListener] Listener already exists for event \"${eventName}\". ` +\n `Each listener function can only be registered once per event. ` +\n `Store the returned unsubscribe function to remove the listener.`,\n );\n }\n\n if (set.size === 1000) {\n logger.warn(\n \"router.addEventListener\",\n `Warning: Event \"${eventName}\" has ${set.size} listeners. ` +\n `This might indicate a memory leak.`,\n );\n }\n\n if (set.size >= MAX_LISTENERS_HARD_LIMIT) {\n throw new Error(\n `[router.addEventListener] Maximum listener limit (${MAX_LISTENERS_HARD_LIMIT}) ` +\n `reached for event \"${eventName}\". ` +\n `This is a critical memory leak. The application is creating listeners ` +\n `exponentially. Check for loops or recursive calls that register listeners.`,\n );\n }\n\n set.add(cb);\n\n return () => {\n router.removeEventListener(eventName, cb);\n };\n };\n\n /**\n * Simple subscription API for navigation success events\n */\n function subscribe(listener: SubscribeFn): Unsubscribe {\n if (typeof listener !== \"function\") {\n throw new TypeError(\n \"[router.subscribe] Expected a function. \" +\n \"For Observable pattern use router[Symbol.observable]().subscribe(observer)\",\n );\n }\n\n return router.addEventListener(\n events.TRANSITION_SUCCESS,\n (toState: State, fromState?: State) => {\n // States are already frozen: toState from makeState(), fromState from getState()\n listener({\n route: toState,\n previousRoute: fromState,\n });\n },\n );\n }\n\n router.subscribe = subscribe;\n\n /**\n * Observable symbol - TC39 proposal with fallback\n * Runtime check needed despite type declaration because Symbol.observable\n * is not yet standard in all environments\n *\n * @see https://github.com/tc39/proposal-observable\n */\n const $$observable: typeof Symbol.observable =\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- runtime check for environments without Symbol.observable\n (typeof Symbol === \"function\" && Symbol.observable) ||\n (\"@@observable\" as unknown as typeof Symbol.observable);\n\n /**\n * Track active observers for deduplication\n * Using WeakMap to allow garbage collection of observers\n */\n const observerSubscriptions = new WeakMap<\n Observer,\n { unsubscribe: Unsubscribe; active: boolean }\n >();\n\n /**\n * Observer interface per Observable spec\n */\n interface Observer {\n next?: (value: SubscribeState) => void;\n error?: (err: unknown) => void;\n complete?: () => void;\n }\n\n /**\n * Subscription interface per Observable spec\n */\n interface Subscription {\n unsubscribe: () => void;\n readonly closed: boolean;\n }\n\n /**\n * Observable options for enhanced control\n */\n interface ObservableOptions {\n /** AbortSignal for automatic unsubscription */\n signal?: AbortSignal;\n /** Replay current state to new subscribers (default: true) */\n replay?: boolean;\n }\n\n interface SubscribeState {\n route: State;\n previousRoute: State | undefined;\n }\n\n /**\n * Observable interface for TC39 compliance\n */\n interface RouterObservable {\n [key: symbol]: () => RouterObservable;\n subscribe: (\n observer: Observer | ((value: SubscribeState) => void),\n options?: ObservableOptions,\n ) => Subscription;\n }\n\n /**\n * Modern Observable implementation with:\n * - Deduplication: same observer can only subscribe once\n * - Error isolation: errors in one observer don't affect others\n * - Replay: new subscribers receive current state immediately\n * - AbortSignal: automatic cleanup with AbortController\n * - TC39 Observable spec compliance\n */\n function observable(): RouterObservable {\n return {\n /**\n * Subscribe to router state changes\n *\n * @example\n * // Basic subscription\n * const subscription = router[Symbol.observable]().subscribe({\n * next: ({ route, previousRoute }) => console.log(route.name)\n * });\n *\n * @example\n * // With AbortController\n * const controller = new AbortController();\n * router[Symbol.observable]().subscribe(\n * { next: ({ route }) => console.log(route) },\n * { signal: controller.signal }\n * );\n * // Later: controller.abort();\n */\n subscribe(\n observer: Observer | ((value: SubscribeState) => void),\n options: ObservableOptions = {},\n ): Subscription {\n // Normalize observer\n const normalizedObserver: Observer =\n typeof observer === \"function\" ? { next: observer } : observer;\n\n // Check for duplicate subscription\n const existing = observerSubscriptions.get(normalizedObserver);\n\n if (existing?.active) {\n logger.warn(\n \"router.observable\",\n \"Duplicate subscription prevented. Same observer already subscribed.\",\n );\n\n return {\n unsubscribe: existing.unsubscribe,\n get closed() {\n return !existing.active;\n },\n };\n }\n\n const { signal, replay = true } = options;\n\n // Check if already aborted\n if (signal?.aborted) {\n return {\n unsubscribe: () => {},\n closed: true,\n };\n }\n\n let closed = false;\n\n // Create safe invoker with error isolation\n const safeNext = (value: SubscribeState) => {\n if (closed) {\n return;\n }\n\n if (normalizedObserver.next) {\n try {\n normalizedObserver.next(value);\n } catch (error) {\n logger.error(\n \"router.observable\",\n \"Error in observer.next:\",\n error,\n );\n\n // Call error handler if provided\n if (normalizedObserver.error) {\n try {\n normalizedObserver.error(error);\n } catch (errorHandlerError) {\n logger.error(\n \"router.observable\",\n \"Error in observer.error:\",\n errorHandlerError,\n );\n }\n }\n }\n }\n };\n\n // Internal event listener\n const eventListener = (toState: State, fromState?: State) => {\n safeNext({\n route: toState,\n previousRoute: fromState,\n });\n };\n\n // Subscribe to transition success events\n const unsubscribeListener = router.addEventListener(\n events.TRANSITION_SUCCESS,\n eventListener,\n );\n\n // Create subscription object\n const subscription: { unsubscribe: Unsubscribe; active: boolean } = {\n unsubscribe: () => {\n if (closed) {\n return;\n }\n\n closed = true;\n subscription.active = false;\n unsubscribeListener();\n\n // Call complete handler\n if (normalizedObserver.complete) {\n try {\n normalizedObserver.complete();\n } catch (error) {\n logger.error(\n \"router.observable\",\n \"Error in observer.complete:\",\n error,\n );\n }\n }\n },\n active: true,\n };\n\n // Track subscription for deduplication\n observerSubscriptions.set(normalizedObserver, subscription);\n\n // Handle AbortSignal\n if (signal) {\n const abortHandler = () => {\n subscription.unsubscribe();\n };\n\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n // Replay current state if requested and available\n if (replay) {\n const currentState = router.getState();\n\n if (currentState) {\n // Use queueMicrotask for async replay to match Observable semantics\n queueMicrotask(() => {\n safeNext({\n route: currentState,\n previousRoute: undefined,\n });\n });\n }\n }\n\n return {\n unsubscribe: subscription.unsubscribe,\n get closed() {\n return closed;\n },\n };\n },\n\n /**\n * Observable symbol for interop with RxJS and other libraries\n */\n [$$observable](): RouterObservable {\n return this;\n },\n };\n }\n\n // Attach observable to router\n router[$$observable] = observable;\n\n return router;\n}\n","// packages/real-router/modules/core/options.ts\n\nimport { isObjKey, isString } from \"type-guards\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type { DefaultDependencies, Options, Router } from \"core-types\";\n\nconst defaultOptions: Options = {\n defaultRoute: \"\",\n defaultParams: {},\n trailingSlash: \"preserve\",\n queryParamsMode: \"loose\",\n queryParams: {\n arrayFormat: \"none\",\n booleanFormat: \"none\",\n nullFormat: \"default\",\n },\n caseSensitive: false,\n urlParamsEncoding: \"default\",\n allowNotFound: true,\n rewritePathOnMatch: true,\n} satisfies Options;\n\n/**\n * Valid values for string enum options.\n * Used for runtime validation in setOption/withOptions.\n */\nconst VALID_OPTION_VALUES = {\n trailingSlash: [\"strict\", \"never\", \"always\", \"preserve\"] as const,\n queryParamsMode: [\"default\", \"strict\", \"loose\"] as const,\n urlParamsEncoding: [\"default\", \"uri\", \"uriComponent\", \"none\"] as const,\n} as const;\n\n/**\n * Valid keys and values for queryParams option.\n */\nconst VALID_QUERY_PARAMS = {\n arrayFormat: [\"none\", \"brackets\", \"index\", \"comma\"] as const,\n booleanFormat: [\"none\", \"string\", \"empty-true\"] as const,\n nullFormat: [\"default\", \"hidden\"] as const,\n} as const;\n\nconst optionNotFoundError = (method: string, name: keyof Options) =>\n new ReferenceError(`[router.${method}]: option \"${name}\" not found`);\n\n/**\n * Validates that value is a plain object without getters.\n */\nfunction validatePlainObject(\n value: unknown,\n optionName: string,\n methodName: string,\n): asserts value is Record<string, unknown> {\n if (!value || typeof value !== \"object\" || value.constructor !== Object) {\n throw new TypeError(\n `[router.${methodName}] Invalid type for \"${optionName}\": ` +\n `expected plain object, got ${getTypeDescription(value)}`,\n );\n }\n\n // Getters can throw, return different values, or have side effects\n for (const key in value) {\n if (Object.getOwnPropertyDescriptor(value, key)?.get) {\n throw new TypeError(\n `[router.${methodName}] Getters not allowed in \"${optionName}\": \"${key}\"`,\n );\n }\n }\n}\n\n/**\n * Validates queryParams keys and values against allowed enums.\n */\nfunction validateQueryParams(\n value: Record<string, unknown>,\n methodName: string,\n): void {\n for (const key in value) {\n if (!isObjKey(key, VALID_QUERY_PARAMS)) {\n const validKeys = Object.keys(VALID_QUERY_PARAMS)\n .map((k) => `\"${k}\"`)\n .join(\", \");\n\n throw new TypeError(\n `[router.${methodName}] Unknown queryParams key: \"${key}\". ` +\n `Valid keys: ${validKeys}`,\n );\n }\n\n const paramValue = value[key];\n const validValues = VALID_QUERY_PARAMS[key];\n const isValid = (validValues as readonly string[]).includes(\n paramValue as string,\n );\n\n if (!isValid) {\n const allowedValues = validValues.map((v) => `\"${v}\"`).join(\", \");\n\n throw new TypeError(\n `[router.${methodName}] Invalid value for queryParams.${key}: ` +\n `expected one of ${allowedValues}, got \"${String(paramValue)}\"`,\n );\n }\n }\n}\n\n/**\n * Validates string enum options against allowed values.\n */\nfunction validateEnumOption(\n optionName: keyof typeof VALID_OPTION_VALUES,\n value: unknown,\n methodName: string,\n): void {\n const validValues = VALID_OPTION_VALUES[optionName];\n const isValid = (validValues as readonly string[]).includes(value as string);\n\n if (!isValid) {\n const allowedValues = validValues.map((v) => `\"${v}\"`).join(\", \");\n\n throw new TypeError(\n `[router.${methodName}] Invalid value for \"${optionName}\": ` +\n `expected one of ${allowedValues}, got \"${String(value)}\"`,\n );\n }\n}\n\nfunction validateOptionValue<K extends keyof Options>(\n optionName: K,\n value: unknown,\n expectedValue: Options[K],\n methodName: string,\n): void {\n // For object options - ensure plain objects only (not null, arrays, Date, etc)\n if (expectedValue && typeof expectedValue === \"object\") {\n validatePlainObject(value, optionName, methodName);\n\n if (optionName === \"queryParams\") {\n validateQueryParams(value, methodName);\n }\n\n return;\n }\n\n // For primitives - typeof check first\n if (typeof value !== typeof expectedValue) {\n throw new TypeError(\n `[router.${methodName}] Invalid type for \"${optionName}\": ` +\n `expected ${typeof expectedValue}, got ${typeof value}`,\n );\n }\n\n // For string enum options - validate against allowed values\n if (optionName in VALID_OPTION_VALUES) {\n validateEnumOption(\n optionName as keyof typeof VALID_OPTION_VALUES,\n value,\n methodName,\n );\n }\n}\n\n// =============================================================================\n// Deep Freeze Helper\n// =============================================================================\n// Options contains nested objects (queryParams, defaultParams) that need\n// to be frozen recursively to prevent mutation via nested access:\n// router.getOptions().queryParams.arrayFormat = \"brackets\" // Should throw!\n// =============================================================================\n\n/**\n * Recursively freezes an object and all nested objects.\n * Only freezes plain objects, not primitives or special objects.\n */\nfunction deepFreeze<T extends object>(obj: T): Readonly<T> {\n // Freeze the object itself\n Object.freeze(obj);\n\n // Recursively freeze nested plain objects\n for (const key of Object.keys(obj)) {\n const value = (obj as Record<string, unknown>)[key];\n\n // Only freeze plain objects (not null, arrays, Date, etc.)\n if (value && typeof value === \"object\" && value.constructor === Object) {\n deepFreeze(value);\n }\n }\n\n return obj;\n}\n\nexport function withOptions<Dependencies extends DefaultDependencies>(\n options: Partial<Options>,\n): (router: Router<Dependencies>) => Router<Dependencies> {\n return (router: Router<Dependencies>): Router<Dependencies> => {\n // Validate options on initialization\n for (const [key, value] of Object.entries(options)) {\n if (!isObjKey(key, defaultOptions)) {\n throw new TypeError(`[router.options] Unknown option: \"${key}\"`);\n }\n\n // Skip undefined values for conditional configuration\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (value === undefined) {\n continue;\n }\n\n validateOptionValue(key, value, defaultOptions[key], \"withOptions\");\n }\n\n // ==========================================================================\n // Performance Optimization: Frozen Options\n // ==========================================================================\n // Instead of creating a copy on every getOptions() call, we freeze the\n // options object once and return the same reference.\n //\n // Trade-off:\n // - getOptions(): O(n) copy → O(1) reference return\n // - setOption(): O(1) mutation → O(n) object recreation\n //\n // This is beneficial because getOptions() is called frequently (every\n // start(), navigate()), while setOption() is called rarely (initialization).\n // ==========================================================================\n\n let frozenOptions: Readonly<Options> = deepFreeze({\n ...defaultOptions,\n ...options,\n });\n\n // Return frozen reference directly - no copy needed!\n // Mutations will throw TypeError in strict mode\n router.getOptions = () => frozenOptions;\n\n router.setOption = <K extends keyof Options>(\n optionName: K,\n value: Options[K],\n ): Router<Dependencies> => {\n // Validate optionName is a string (TypeScript can be bypassed at runtime)\n if (!isString(optionName)) {\n throw new TypeError(\n `[router.setOption]: option name must be a string, got ${typeof optionName}`,\n );\n }\n\n // Options cannot be changed after router starts, except defaultRoute/defaultParams\n if (\n router.isStarted() &&\n optionName !== \"defaultRoute\" &&\n optionName !== \"defaultParams\"\n ) {\n throw new Error(\n `[router.setOption] Options cannot be changed after router.start(). ` +\n `Only defaultRoute/defaultParams can be changed after start.`,\n );\n }\n\n // Use Object.hasOwn to reject prototype keys like __proto__\n if (!Object.hasOwn(frozenOptions, optionName)) {\n throw optionNotFoundError(\"setOption\", optionName);\n }\n\n validateOptionValue(\n optionName,\n value,\n defaultOptions[optionName],\n \"setOption\",\n );\n\n // Recreate frozen options with new value\n // For nested objects (defaultParams), create a shallow copy to avoid\n // sharing mutable references\n const newValue =\n value && typeof value === \"object\" && value.constructor === Object\n ? { ...value }\n : value;\n\n frozenOptions = deepFreeze({\n ...frozenOptions,\n [optionName]: newValue,\n });\n\n return router;\n };\n\n return router;\n };\n}\n","// packages/real-router/modules/core/plugins.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { isObjKey } from \"type-guards\";\n\nimport { events as EVENTS_CONST, plugins as PLUGINS_CONST } from \"../constants\";\nimport { getTypeDescription } from \"../helpers\";\n\nimport type {\n EventName,\n Unsubscribe,\n Router,\n Plugin,\n PluginFactory,\n DefaultDependencies,\n} from \"core-types\";\n\ntype EventMappingType = Record<\n (typeof PLUGINS_CONST)[keyof typeof PLUGINS_CONST],\n EventName\n>;\n\nconst LOGGER_CONTEXT_FOR_PLUGINS = \"router.usePlugin\";\n\nconst eventsMap = {\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_ERROR]: EVENTS_CONST.TRANSITION_ERROR,\n [PLUGINS_CONST.TRANSITION_CANCEL]: EVENTS_CONST.TRANSITION_CANCEL,\n} as const satisfies EventMappingType;\n\nconst EVENT_METHOD_NAMES = Object.keys(eventsMap).filter(\n (eventName): eventName is keyof typeof eventsMap =>\n isObjKey<typeof eventsMap>(eventName, eventsMap),\n);\n\nconst PLUGIN_LIMITS = {\n WARN: 10,\n ERROR: 25,\n HARD_LIMIT: 50,\n};\n\nconst validatePluginsSize = (\n newPluginsSize: number,\n registeredPluginsSize: number,\n) => {\n // Check total size BEFORE initialization to fail fast\n const newSize = newPluginsSize + registeredPluginsSize;\n\n // Hard limit: more than 50 plugins indicates architectural problem\n if (newSize > PLUGIN_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.usePlugin] Plugin limit exceeded (${PLUGIN_LIMITS.HARD_LIMIT})`,\n );\n }\n\n // Graduated warnings for early problem detection\n if (newSize >= PLUGIN_LIMITS.ERROR) {\n logger.error(LOGGER_CONTEXT_FOR_PLUGINS, `${newSize} plugins registered!`);\n } else if (newSize >= PLUGIN_LIMITS.WARN) {\n logger.warn(LOGGER_CONTEXT_FOR_PLUGINS, `${newSize} plugins registered`);\n }\n};\n\nconst validateAppliedPlugin = (plugin: Plugin) => {\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 ${getTypeDescription(\n plugin,\n )}`,\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 for (const key in plugin) {\n if (!(key === \"teardown\" || isObjKey<typeof eventsMap>(key, eventsMap))) {\n throw new TypeError(\n `[router.usePlugin] Unknown property '${key}'. ` +\n `Plugin must only contain event handlers and optional teardown.`,\n );\n }\n }\n};\n\n/**\n * Validates plugin batch and returns deduplicated set.\n * Throws if any plugin is invalid or already registered.\n */\nfunction validatePluginBatch<Dependencies extends DefaultDependencies>(\n plugins: PluginFactory<Dependencies>[],\n registeredPlugins: Set<PluginFactory<Dependencies>>,\n): Set<PluginFactory<Dependencies>> {\n const seenInBatch = new Set<PluginFactory<Dependencies>>();\n\n for (const plugin of plugins) {\n if (typeof plugin !== \"function\") {\n throw new TypeError(\n `[router.usePlugin] Expected plugin factory function, got ${typeof plugin}`,\n );\n }\n\n if (registeredPlugins.has(plugin)) {\n throw new Error(\n `[router.usePlugin] Plugin factory already registered. ` +\n `To re-register, first unsubscribe the existing plugin.`,\n );\n }\n\n if (seenInBatch.has(plugin)) {\n logger.warn(\n LOGGER_CONTEXT_FOR_PLUGINS,\n \"Duplicate factory in batch, will be registered once\",\n );\n } else {\n seenInBatch.add(plugin);\n }\n }\n\n return seenInBatch;\n}\n\nexport function withPlugins<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): Router<Dependencies> {\n const routerPlugins = new Set<PluginFactory<Dependencies>>();\n\n /**\n * Returns registered plugin factories\n *\n * @internal Used by router.clone(). Will be removed from public API.\n * @deprecated Use behavior testing instead of checking internal state\n */\n router.getPlugins = (): PluginFactory<Dependencies>[] => [...routerPlugins];\n\n /**\n * Registers one or more plugins in the router\n * Plugins can subscribe to router lifecycle events\n *\n * @returns Unsubscribe function that removes all added plugins\n */\n router.usePlugin = (\n ...plugins: PluginFactory<Dependencies>[]\n ): Unsubscribe => {\n // Prevent exceeding plugin limit (50 max)\n validatePluginsSize(plugins.length, routerPlugins.size);\n\n // Validate ALL plugins before any state changes (atomicity)\n const seenInBatch = validatePluginBatch(plugins, routerPlugins);\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 = 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 logger.error(\n LOGGER_CONTEXT_FOR_PLUGINS,\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 routerPlugins.add(factory);\n }\n\n // Return unsubscribe function - each call manages only its own plugins\n let unsubscribed = false;\n\n return () => {\n if (unsubscribed) {\n return;\n }\n\n unsubscribed = true;\n\n // Remove only plugins added in THIS call\n for (const { factory } of initializedPlugins) {\n routerPlugins.delete(factory);\n }\n\n // Cleanup all plugins from this call\n for (const { cleanup } of initializedPlugins) {\n try {\n cleanup();\n } catch (error) {\n logger.error(\n LOGGER_CONTEXT_FOR_PLUGINS,\n \"Error during cleanup:\",\n error,\n );\n }\n }\n };\n };\n\n /**\n * Initializes a single plugin and subscribes it to router events\n *\n * @param pluginFactory - Factory function to create plugin\n * @returns Composite cleanup function that unsubscribes from all events\n */\n function startPlugin(\n pluginFactory: PluginFactory<Dependencies>,\n ): Unsubscribe {\n // Create plugin instance with router context\n const appliedPlugin = pluginFactory(router, router.getDependency);\n\n validateAppliedPlugin(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 router.addEventListener(\n eventsMap[methodName],\n appliedPlugin[methodName],\n ),\n );\n\n if (methodName === PLUGINS_CONST.ROUTER_START && router.isStarted()) {\n logger.warn(\n LOGGER_CONTEXT_FOR_PLUGINS,\n \"Router already started, onStart will not be called\",\n );\n }\n } else {\n logger.warn(\n LOGGER_CONTEXT_FOR_PLUGINS,\n `Property '${methodName}' is not a function, skipping`,\n );\n }\n }\n }\n\n // Return composite cleanup function\n return () => {\n // Unsubscribe from all events\n removeEventListeners.forEach((removeListener) => {\n removeListener();\n });\n\n // Call plugin's custom teardown if exists\n if (typeof appliedPlugin.teardown === \"function\") {\n appliedPlugin.teardown();\n }\n };\n }\n\n return router;\n}\n","// packages/real-router/modules/core/routeLifecycle.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { isBoolean, validateRouteName } from \"type-guards\";\n\nimport { getTypeDescription } from \"../helpers\";\n\nimport type {\n ActivationFn,\n ActivationFnFactory,\n DefaultDependencies,\n Router,\n} from \"core-types\";\n\n/**\n * Lifecycle handler registry limits to prevent memory leaks.\n * Higher limits than middleware since routes can be numerous.\n */\nconst LIFECYCLE_LIMITS = {\n WARN: 50, // Log warning - review route structure\n ERROR: 100, // Log error - too many routes with handlers\n HARD_LIMIT: 200, // Throw error - critical architectural issue\n} as const;\n\n/**\n * Validates that a handler is either a boolean or a factory function.\n *\n * @param handler - Value to validate\n * @param methodName - Calling method for error context\n * @throws {TypeError} If handler is not valid\n */\nfunction validateHandler<Dependencies extends DefaultDependencies>(\n handler: unknown,\n methodName: string,\n): asserts handler is ActivationFnFactory<Dependencies> | boolean {\n if (!isBoolean(handler) && typeof handler !== \"function\") {\n throw new TypeError(\n `[router.${methodName}] Handler must be a boolean or factory function, ` +\n `got ${getTypeDescription(handler)}`,\n );\n }\n}\n\n/**\n * Checks the total handler count and emits warnings based on thresholds.\n * Prevents memory leaks from excessive route handlers.\n *\n * @param currentSize - Current number of registered handlers\n * @param methodName - Calling method for error context\n * @throws {Error} If limit is exceeded\n */\nfunction checkHandlerCount(currentSize: number, methodName: string): void {\n if (currentSize >= LIFECYCLE_LIMITS.HARD_LIMIT) {\n throw new Error(\n `[router.${methodName}] Lifecycle handler limit exceeded (${LIFECYCLE_LIMITS.HARD_LIMIT}). ` +\n `This indicates too many routes with individual handlers. ` +\n `Consider using middleware for cross-cutting concerns.`,\n );\n }\n\n if (currentSize >= LIFECYCLE_LIMITS.ERROR) {\n logger.error(\n `router.${methodName}`,\n `${currentSize} lifecycle handlers registered! ` +\n `This is excessive. Hard limit at ${LIFECYCLE_LIMITS.HARD_LIMIT}.`,\n );\n } else if (currentSize >= LIFECYCLE_LIMITS.WARN) {\n logger.warn(\n `router.${methodName}`,\n `${currentSize} lifecycle handlers registered. ` +\n `Consider consolidating logic.`,\n );\n }\n}\n\n/**\n * Converts a boolean value to an activation function factory.\n * Used for the shorthand syntax where true/false is passed instead of a function.\n *\n * Design note: Creates a factory that returns a function returning the boolean.\n * This maintains consistency with the factory pattern used throughout.\n *\n * @param value - Boolean value to convert\n * @returns Factory function that produces an activation function\n */\nfunction booleanToFactory<Dependencies extends DefaultDependencies>(\n value: boolean,\n): ActivationFnFactory<Dependencies> {\n // Cache the activation function to avoid recreating it\n const activationFn: ActivationFn = () => value;\n\n return () => activationFn;\n}\n\n/**\n * Adds route lifecycle capabilities to a router instance.\n * Allows registration of canActivate and canDeactivate guards for routes.\n *\n * Design decisions:\n * - Uses Map for O(1) operations and better memory management\n * - Separate Maps for factories and compiled functions\n * - Supports both boolean shortcuts and factory functions\n * - Warns on overwrites to prevent silent failures\n * - Enforces limits to prevent architectural degradation\n *\n * @param router - Router instance to enhance\n * @returns Enhanced router with lifecycle methods\n */\nexport function withRouteLifecycle<\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(router: Router<Dependencies>): Router<Dependencies> {\n // Use Map for efficient O(1) operations\n // Separate storage for factories (source) and functions (compiled)\n const canDeactivateFactories = new Map<\n string,\n ActivationFnFactory<Dependencies>\n >();\n const canActivateFactories = new Map<\n string,\n ActivationFnFactory<Dependencies>\n >();\n const canDeactivateFunctions = new Map<string, ActivationFn>();\n const canActivateFunctions = new Map<string, ActivationFn>();\n\n // Track routes currently being registered to prevent self-modification\n // This prevents desynchronization between factories and functions Maps\n const registering = new Set<string>();\n\n /**\n * Internal helper to register a lifecycle handler.\n * Centralizes the logic for both canActivate and canDeactivate.\n *\n * @param type - Type of handler ('activate' or 'deactivate')\n * @param name - Route name\n * @param handler - Handler function or boolean\n * @param factories - Map to store factories\n * @param functions - Map to store compiled functions\n * @param methodName - Method name for error messages\n */\n function registerHandler(\n type: \"activate\" | \"deactivate\",\n name: string,\n handler: ActivationFnFactory<Dependencies> | boolean,\n factories: Map<string, ActivationFnFactory<Dependencies>>,\n functions: Map<string, ActivationFn>,\n methodName: string,\n ): void {\n // Prevent self-modification during factory compilation\n // This ensures factories and functions Maps stay synchronized\n if (registering.has(name)) {\n throw new Error(\n `[router.${methodName}] Cannot modify route \"${name}\" during its own registration`,\n );\n }\n\n const isOverwrite = factories.has(name);\n\n if (isOverwrite) {\n // Warn about overwrites for debugging\n logger.warn(\n `router.${methodName}`,\n `Overwriting existing ${type} handler for route \"${name}\"`,\n );\n } else {\n // Check limit only for new handlers\n checkHandlerCount(factories.size + 1, methodName);\n }\n\n // Convert boolean to factory if needed\n const factory = isBoolean(handler)\n ? booleanToFactory<Dependencies>(handler)\n : handler;\n\n // Store factory\n factories.set(name, factory);\n\n // Mark route as being registered before calling user factory\n registering.add(name);\n\n // Compile and cache the function immediately\n // This validates the factory early and improves runtime performance\n try {\n const fn = factory(router, router.getDependency);\n\n if (typeof fn !== \"function\") {\n throw new TypeError(\n `[router.${methodName}] Factory must return a function, got ${getTypeDescription(fn)}`,\n );\n }\n\n functions.set(name, fn);\n } catch (error) {\n // Rollback on failure to maintain consistency\n factories.delete(name);\n\n throw error;\n } finally {\n // Always remove from registering set\n registering.delete(name);\n }\n }\n\n /**\n * Returns lifecycle factories for cloning.\n *\n * @internal Used by router.clone(). Not part of public API.\n * @returns Tuple of [canDeactivateFactories, canActivateFactories]\n */\n router.getLifecycleFactories = (): [\n Record<string, ActivationFnFactory<Dependencies>>,\n Record<string, ActivationFnFactory<Dependencies>>,\n ] => {\n // Convert Maps to Records for backward compatibility\n // Note: This creates a snapshot, not a live reference\n const deactivateRecord: Record<\n string,\n ActivationFnFactory<Dependencies>\n > = {};\n const activateRecord: Record<\n string,\n ActivationFnFactory<Dependencies>\n > = {};\n\n for (const [name, factory] of canDeactivateFactories) {\n deactivateRecord[name] = factory;\n }\n\n for (const [name, factory] of canActivateFactories) {\n activateRecord[name] = factory;\n }\n\n return [deactivateRecord, activateRecord];\n };\n\n /**\n * Returns compiled lifecycle functions for transition execution.\n * Returns Maps directly for O(1) operations without Object.fromEntries overhead.\n *\n * @internal Used by transition system. Not part of public API.\n * @returns Tuple of [canDeactivateFunctions, canActivateFunctions] as Maps\n */\n router.getLifecycleFunctions = () => [\n canDeactivateFunctions,\n canActivateFunctions,\n ];\n\n /**\n * Registers a canActivate guard for a route.\n * The guard is called before activating the route.\n *\n * @param name - Route name to guard\n * @param canActivateHandler - Guard function or boolean\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string or handler is invalid\n * @throws {Error} If handler limit is exceeded\n *\n * @example\n * // Boolean shorthand\n * router.canActivate('admin', false); // Always deny\n *\n * @example\n * // Factory function\n * router.canActivate('profile', (router) => {\n * return (toState, fromState, done) => {\n * const isAuthenticated = router.getDependency('auth').isLoggedIn();\n * done(isAuthenticated ? undefined : new Error('Not authenticated'));\n * };\n * });\n */\n router.canActivate = (\n name: string,\n canActivateHandler: ActivationFnFactory<Dependencies> | boolean,\n ): Router<Dependencies> => {\n validateRouteName(name, \"canActivate\");\n validateHandler<Dependencies>(canActivateHandler, \"canActivate\");\n\n registerHandler(\n \"activate\",\n name,\n canActivateHandler,\n canActivateFactories,\n canActivateFunctions,\n \"canActivate\",\n );\n\n return router;\n };\n\n /**\n * Registers a canDeactivate guard for a route.\n * The guard is called before leaving the route.\n *\n * @param name - Route name to guard\n * @param canDeactivateHandler - Guard function or boolean\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string or handler is invalid\n * @throws {Error} If handler limit is exceeded\n *\n * @example\n * // Prevent leaving with unsaved changes\n * router.canDeactivate('editor', (router) => {\n * return (toState, fromState, done) => {\n * if (hasUnsavedChanges()) {\n * const confirmed = confirm('Discard unsaved changes?');\n * done(confirmed ? undefined : new Error('User cancelled'));\n * } else {\n * done();\n * }\n * };\n * });\n */\n router.canDeactivate = (\n name: string,\n canDeactivateHandler: ActivationFnFactory<Dependencies> | boolean,\n ): Router<Dependencies> => {\n validateRouteName(name, \"canDeactivate\");\n validateHandler<Dependencies>(canDeactivateHandler, \"canDeactivate\");\n\n registerHandler(\n \"deactivate\",\n name,\n canDeactivateHandler,\n canDeactivateFactories,\n canDeactivateFunctions,\n \"canDeactivate\",\n );\n\n return router;\n };\n\n /**\n * Removes a canDeactivate guard for a route.\n * Used to clean up guards that are no longer needed.\n *\n * @param name - Route name to clear guard for\n * @param silent - If true, suppresses warning when no handler exists\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string\n *\n * @example\n * router.clearCanDeactivate('editor');\n */\n router.clearCanDeactivate = (\n name: string,\n silent = false,\n ): Router<Dependencies> => {\n validateRouteName(name, \"clearCanDeactivate\");\n\n // Prevent clearing a route during its own registration\n if (registering.has(name)) {\n throw new Error(\n `[router.clearCanDeactivate] Cannot modify route \"${name}\" during its own registration`,\n );\n }\n\n const factoryDeleted = canDeactivateFactories.delete(name);\n const functionDeleted = canDeactivateFunctions.delete(name);\n\n if (!silent && !factoryDeleted && !functionDeleted) {\n logger.warn(\n \"router.clearCanDeactivate\",\n `No canDeactivate handler found for route \"${name}\"`,\n );\n }\n\n return router;\n };\n\n /**\n * Removes a canActivate guard for a route.\n * Used to clean up guards that are no longer needed.\n *\n * @param name - Route name to clear guard for\n * @param silent - If true, suppresses warning when no handler exists\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a string\n *\n * @example\n * router.clearCanActivate('admin');\n */\n router.clearCanActivate = (\n name: string,\n silent = false,\n ): Router<Dependencies> => {\n validateRouteName(name, \"clearCanActivate\");\n\n // Prevent clearing a route during its own registration\n if (registering.has(name)) {\n throw new Error(\n `[router.clearCanActivate] Cannot modify route \"${name}\" during its own registration`,\n );\n }\n\n const factoryDeleted = canActivateFactories.delete(name);\n const functionDeleted = canActivateFunctions.delete(name);\n\n if (!silent && !factoryDeleted && !functionDeleted) {\n logger.warn(\n \"router.clearCanActivate\",\n `No canActivate handler found for route \"${name}\"`,\n );\n }\n\n return router;\n };\n\n return router;\n}\n","// packages/route-node/modules/search-params/decode.ts\n\n/**\n * Decoding functions for search-params.\n *\n * Extracted from encode.ts for better separation of concerns.\n *\n * @module search-params/decode\n */\n\nimport type { ResolvedStrategies } from \"./strategies\";\nimport type { DecodeResult } from \"./types\";\n\n// =============================================================================\n// Value Decoding\n// =============================================================================\n\n/**\n * Decodes a URL-encoded value, handling + as space.\n * Optimized: only replaces + if present, skips decodeURIComponent if not needed.\n *\n * Uses indexOf for checking presence - more mutation-resistant than includes\n * because indexOf(\"x\") returns -1 when not found, while includes(\"\") always returns true.\n */\nexport const decodeValue = (value: string): string => {\n const percentIdx = value.indexOf(\"%\");\n const plusIdx = value.indexOf(\"+\");\n\n // Fast path: no encoding needed (common case - most values are simple)\n if (percentIdx === -1 && plusIdx === -1) {\n return value;\n }\n\n // Only replace + if present (avoid regex overhead)\n const withSpaces = plusIdx === -1 ? value : value.split(\"+\").join(\" \");\n\n // Only decode if % is present\n return percentIdx === -1 ? withSpaces : decodeURIComponent(withSpaces);\n};\n\n// =============================================================================\n// Main Decode\n// =============================================================================\n\n/**\n * Decodes a query parameter value using resolved strategies.\n *\n * @param value - Raw value from query string (undefined for key-only params)\n * @param strategies - Pre-resolved format strategies\n * @returns Decoded value (string, boolean, or null)\n */\nexport const decode = (\n value: string | undefined,\n strategies: ResolvedStrategies,\n): DecodeResult => {\n // Handle undefined (key-only params like ?flag)\n if (value === undefined) {\n return strategies.boolean.decodeUndefined();\n }\n\n // Check raw value for boolean formats (e.g., \"true\"/\"false\")\n const rawResult = strategies.boolean.decodeRaw(value);\n\n if (rawResult !== null) {\n return rawResult;\n }\n\n // Decode URI and check decoded value for boolean formats (e.g., ✓/✗)\n const decoded = decodeValue(value);\n\n return strategies.boolean.decodeValue(decoded);\n};\n","// packages/route-node/modules/search-params/strategies/array.ts\n\n/**\n * Array encoding strategies.\n *\n * @module search-params/strategies/array\n */\n\nimport type { ArrayFormat } from \"../types\";\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for encoding array values.\n */\nexport interface ArrayStrategy {\n /**\n * Encodes an array as a query string segment.\n *\n * @param name - URL-encoded parameter name\n * @param values - Array values to encode\n * @returns Query string segment (e.g., \"items=a&items=b\" or \"items=a,b\")\n */\n encodeArray: (name: string, values: unknown[]) => string;\n}\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\nconst encodeValue = (value: unknown): string =>\n encodeURIComponent(value as string | number | boolean);\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * Repeated keys without brackets.\n * Example: items=a&items=b\n */\nexport const noneArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values) =>\n values.map((val) => `${name}=${encodeValue(val)}`).join(\"&\"),\n};\n\n/**\n * Bracket notation without index.\n * Example: items[]=a&items[]=b\n */\nexport const bracketsArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values) =>\n values.map((val) => `${name}[]=${encodeValue(val)}`).join(\"&\"),\n};\n\n/**\n * Indexed bracket notation.\n * Example: items[0]=a&items[1]=b\n */\nexport const indexArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values) =>\n values.map((val, i) => `${name}[${i}]=${encodeValue(val)}`).join(\"&\"),\n};\n\n/**\n * Comma-separated values.\n * Example: items=a,b,c\n */\nexport const commaArrayStrategy: ArrayStrategy = {\n encodeArray: (name, values) =>\n `${name}=${values.map((val) => encodeValue(val)).join(\",\")}`,\n};\n\n/**\n * Map of array format to strategy implementation.\n */\nexport const arrayStrategies: Record<ArrayFormat, ArrayStrategy> = {\n none: noneArrayStrategy,\n brackets: bracketsArrayStrategy,\n index: indexArrayStrategy,\n comma: commaArrayStrategy,\n};\n","// packages/route-node/modules/search-params/strategies/boolean.ts\n\n/**\n * Boolean encoding/decoding strategies.\n *\n * @module search-params/strategies/boolean\n */\n\nimport type { DecodeResult, BooleanFormat } from \"../types\";\n\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for encoding/decoding boolean values.\n */\nexport interface BooleanStrategy {\n /**\n * Encodes a boolean value as a query string segment.\n *\n * @param name - URL-encoded parameter name\n * @param value - Boolean value to encode\n * @returns Query string segment (e.g., \"flag=true\" or just \"flag\")\n */\n encode: (name: string, value: boolean) => string;\n\n /**\n * Handles undefined value (key-only params like ?flag).\n *\n * @returns Decoded value for undefined\n */\n decodeUndefined: () => DecodeResult;\n\n /**\n * Decodes a raw (not URI-decoded) value before decodeValue() is called.\n * Used for formats that check raw values (e.g., \"string\" checks \"true\"/\"false\").\n *\n * @param rawValue - Raw value before URI decoding\n * @returns boolean if matched, null to continue with URI decoding\n */\n decodeRaw: (rawValue: string) => boolean | null;\n\n /**\n * Decodes a URI-decoded value.\n *\n * @param decodedValue - Value after URI decoding\n * @returns Decoded value (boolean or the same string)\n */\n decodeValue: (decodedValue: string) => DecodeResult;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * No special boolean handling - values are treated as strings.\n */\nexport const noneBooleanStrategy: BooleanStrategy = {\n encode: (name, value) => `${name}=${value}`,\n decodeUndefined: () => null,\n decodeRaw: () => null, // No raw value matching\n decodeValue: (decoded) => decoded, // Return as-is\n};\n\n/**\n * Parse \"true\"/\"false\" strings as boolean values.\n * Checks raw value before URI decoding.\n */\nexport const stringBooleanStrategy: BooleanStrategy = {\n encode: (name, value) => `${name}=${value}`,\n decodeUndefined: () => null,\n decodeRaw: (raw) => {\n if (raw === \"true\") {\n return true;\n }\n if (raw === \"false\") {\n return false;\n }\n\n return null; // Continue with URI decoding\n },\n decodeValue: (decoded) => decoded, // Return decoded string\n};\n\n/**\n * True values are key-only (no =value), false values are omitted.\n * Example: ?flag instead of ?flag=true\n */\nexport const emptyTrueBooleanStrategy: BooleanStrategy = {\n encode: (name, value) => (value ? name : `${name}=false`),\n decodeUndefined: () => true, // Key-only means true\n decodeRaw: () => null, // No raw value matching\n decodeValue: (decoded) => decoded, // Return as-is\n};\n\n/**\n * Map of boolean format to strategy implementation.\n */\nexport const booleanStrategies: Record<BooleanFormat, BooleanStrategy> = {\n none: noneBooleanStrategy,\n string: stringBooleanStrategy,\n \"empty-true\": emptyTrueBooleanStrategy,\n};\n","// packages/route-node/modules/search-params/strategies/null.ts\n\n/**\n * Null encoding/decoding strategies.\n *\n * @module search-params/strategies/null\n */\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for encoding/decoding null values.\n */\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\nimport type { NullFormat } from \"../types\";\n\nexport interface NullStrategy {\n /**\n * Encodes a null value as a query string segment.\n *\n * @param name - URL-encoded parameter name\n * @returns Query string segment (e.g., \"key\" or \"\")\n */\n encode: (name: string) => string;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * Default null format - key only without value.\n * Example: ?key (no equals sign)\n */\nexport const defaultNullStrategy: NullStrategy = {\n encode: (name) => name,\n};\n\n/**\n * Null values are hidden (omitted from query string).\n * Example: (nothing)\n */\nexport const hiddenNullStrategy: NullStrategy = {\n encode: () => \"\",\n};\n\n/**\n * Map of null format to strategy implementation.\n */\nexport const nullStrategies: Record<NullFormat, NullStrategy> = {\n default: defaultNullStrategy,\n hidden: hiddenNullStrategy,\n};\n","// packages/route-node/modules/search-params/strategies/index.ts\n\n/**\n * Search Params Strategies - Factory and Types.\n *\n * Provides a unified interface for format-specific encoding/decoding strategies.\n * Strategies are resolved once when options are created, avoiding repeated\n * format checks during encode/decode operations.\n *\n * @module search-params/strategies\n */\n\nimport { arrayStrategies, type ArrayStrategy } from \"./array\";\nimport { booleanStrategies, type BooleanStrategy } from \"./boolean\";\nimport { nullStrategies, type NullStrategy } from \"./null\";\n\nimport type { FinalOptions } from \"../types\";\n\n// =============================================================================\n// Exports\n// =============================================================================\n\nexport type { ArrayStrategy } from \"./array\";\n\nexport type { BooleanStrategy } from \"./boolean\";\n\nexport type { NullStrategy } from \"./null\";\n\n// =============================================================================\n// Resolved Strategies\n// =============================================================================\n\n/**\n * Pre-resolved strategies based on options.\n * Created once when makeOptions() is called, avoiding repeated lookups.\n */\nexport interface ResolvedStrategies {\n readonly boolean: BooleanStrategy;\n readonly null: NullStrategy;\n readonly array: ArrayStrategy;\n}\n\n/**\n * Resolves strategies based on format options.\n *\n * @param arrayFormat - Array format\n * @param booleanFormat - Boolean format\n * @param nullFormat - Null format\n * @returns Resolved strategy implementations\n */\nexport const resolveStrategies = (\n arrayFormat: FinalOptions[\"arrayFormat\"],\n booleanFormat: FinalOptions[\"booleanFormat\"],\n nullFormat: FinalOptions[\"nullFormat\"],\n): ResolvedStrategies => ({\n boolean: booleanStrategies[booleanFormat],\n null: nullStrategies[nullFormat],\n array: arrayStrategies[arrayFormat],\n});\n\n// =============================================================================\n// Default Strategies\n// =============================================================================\n\n/**\n * Default strategies matching DEFAULT_OPTIONS.\n * Used when no custom options are provided.\n */\nexport const DEFAULT_STRATEGIES: ResolvedStrategies = {\n boolean: booleanStrategies.none,\n null: nullStrategies.default,\n array: arrayStrategies.none,\n};\n","// packages/route-node/modules/search-params/encode.ts\n\n/**\n * Encoding functions for search-params.\n *\n * Uses Strategy pattern for format-specific encoding.\n * Strategies are resolved once when options are created.\n *\n * @module search-params/encode\n */\n\nimport {\n DEFAULT_STRATEGIES,\n resolveStrategies,\n type ResolvedStrategies,\n} from \"./strategies\";\n\nimport type { FinalOptions, Options } from \"./types\";\n\n// =============================================================================\n// Options with Strategies\n// =============================================================================\n\n/**\n * Extended options with pre-resolved strategies.\n */\nexport interface OptionsWithStrategies extends FinalOptions {\n readonly strategies: ResolvedStrategies;\n}\n\n/**\n * Cached default options with strategies - avoids allocation when no options passed.\n */\nconst DEFAULT_OPTIONS: OptionsWithStrategies = {\n arrayFormat: \"none\",\n booleanFormat: \"none\",\n nullFormat: \"default\",\n strategies: DEFAULT_STRATEGIES,\n};\n\n/**\n * Creates options with defaults and pre-resolved strategies.\n * Returns cached DEFAULT_OPTIONS when no custom options are specified.\n */\nexport const makeOptions = (opts?: Options): OptionsWithStrategies => {\n if (\n !opts ||\n (opts.arrayFormat === undefined &&\n opts.booleanFormat === undefined &&\n opts.nullFormat === undefined)\n ) {\n return DEFAULT_OPTIONS;\n }\n\n // Avoid object spread - direct property assignment is faster\n const arrayFormat = opts.arrayFormat ?? \"none\";\n const booleanFormat = opts.booleanFormat ?? \"none\";\n const nullFormat = opts.nullFormat ?? \"default\";\n\n return {\n arrayFormat,\n booleanFormat,\n nullFormat,\n strategies: resolveStrategies(arrayFormat, booleanFormat, nullFormat),\n };\n};\n\n// =============================================================================\n// Value Encoding\n// =============================================================================\n\n/**\n * Encodes a value for use in a URL query string.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-argument\nexport const encodeValue = (value: any): string => encodeURIComponent(value);\n\n// =============================================================================\n// Main Encode\n// =============================================================================\n\n/**\n * Encodes a parameter name and value as a query string segment.\n *\n * Uses pre-resolved strategies for format-specific encoding.\n * Strategies handle all formats uniformly - no inline optimizations\n * to avoid equivalent mutants in mutation testing.\n *\n * @param name - Parameter name\n * @param value - Parameter value\n * @param opts - Options with pre-resolved strategies\n * @returns Query string segment (e.g., \"key=value\")\n */\nexport const encode = (\n name: string,\n value: unknown,\n opts: OptionsWithStrategies,\n): string => {\n const encodedName = encodeValue(name);\n\n // Handle each type using strategies\n switch (typeof value) {\n case \"string\":\n case \"number\": {\n return `${encodedName}=${encodeValue(value)}`;\n }\n case \"boolean\": {\n return opts.strategies.boolean.encode(encodedName, value);\n }\n case \"object\": {\n // Null check\n if (value === null) {\n return opts.strategies.null.encode(encodedName);\n }\n // Array check\n if (Array.isArray(value)) {\n return opts.strategies.array.encodeArray(encodedName, value);\n }\n\n // Fallback for other objects - treat as string\n return `${encodedName}=${encodeValue(value)}`;\n }\n default: {\n // Fallback for other types (undefined handled by caller)\n return `${encodedName}=${encodeValue(value)}`;\n }\n }\n};\n","// packages/route-node/modules/search-params/utils.ts\n\n/**\n * Utility functions for search-params.\n *\n * Internalized from https://github.com/troch/search-params\n *\n * @module search-params/utils\n */\n\n// =============================================================================\n// Query String Extraction\n// =============================================================================\n\n/**\n * Extracts the query string portion from a path.\n * Returns everything after \"?\" or the entire string if no \"?\" exists.\n */\nexport const getSearch = (path: string): string => {\n const pos = path.indexOf(\"?\");\n\n if (pos === -1) {\n return path;\n }\n\n return path.slice(pos + 1);\n};\n","// packages/route-node/modules/search-params/searchParams.ts\n\n/**\n * Search Params - Query String Parsing and Building.\n *\n * Internalized from https://github.com/troch/search-params (MIT License)\n * for better code control and optimization.\n *\n * @module search-params/searchParams\n */\n\nimport { decode, decodeValue } from \"./decode\";\nimport { encode, makeOptions } from \"./encode\";\nimport { getSearch } from \"./utils\";\n\nimport type { ResolvedStrategies } from \"./strategies\";\nimport type { KeepResponse, OmitResponse, Options } from \"./types\";\n\n// =============================================================================\n// Internal Helpers\n// =============================================================================\n\n/**\n * Extracts parameter name from raw name (removes bracket suffix).\n *\n * @internal\n */\nfunction extractParamName(rawName: string): {\n name: string;\n hasBrackets: boolean;\n} {\n const bracketPos = rawName.indexOf(\"[\");\n\n return bracketPos === -1\n ? { name: rawName, hasBrackets: false }\n : { name: rawName.slice(0, bracketPos), hasBrackets: true };\n}\n\n/**\n * Adds a decoded value to params object, handling array accumulation.\n *\n * @internal\n */\nfunction addToParams(\n params: Record<string, unknown>,\n decodedName: string,\n decodedValue: unknown,\n hasBrackets: boolean,\n): void {\n const currentValue = params[decodedName];\n\n if (currentValue === undefined) {\n params[decodedName] = hasBrackets ? [decodedValue] : decodedValue;\n } else if (Array.isArray(currentValue)) {\n currentValue.push(decodedValue);\n } else {\n params[decodedName] = [currentValue, decodedValue];\n }\n}\n\n/**\n * Decodes a parameter value based on whether strategies are provided.\n *\n * @internal\n */\nfunction decodeParamValue(\n searchPart: string,\n eqPos: number,\n end: number,\n hasValue: boolean,\n strategies: ResolvedStrategies | undefined,\n): unknown {\n if (strategies) {\n const rawValue = hasValue ? searchPart.slice(eqPos + 1, end) : undefined;\n\n return decode(rawValue, strategies);\n }\n\n return hasValue ? decodeValue(searchPart.slice(eqPos + 1, end)) : null;\n}\n\n/**\n * Processes a single query parameter chunk and adds to params.\n *\n * @internal\n */\nfunction processParamChunk(\n searchPart: string,\n start: number,\n end: number,\n params: Record<string, unknown>,\n strategies?: ResolvedStrategies,\n): void {\n const eqPos = searchPart.indexOf(\"=\", start);\n const hasValue = eqPos !== -1 && eqPos < end;\n\n const rawName = hasValue\n ? searchPart.slice(start, eqPos)\n : searchPart.slice(start, end);\n\n const { name, hasBrackets } = extractParamName(rawName);\n const decodedName = decodeValue(name);\n const decodedValue = decodeParamValue(\n searchPart,\n eqPos,\n end,\n hasValue,\n strategies,\n );\n\n addToParams(params, decodedName, decodedValue, hasBrackets);\n}\n\n/**\n * Iterates over query string parameters, calling handler for each chunk.\n *\n * @internal\n */\nfunction forEachParam(\n searchPart: string,\n handler: (chunk: string, start: number, end: number) => void,\n): void {\n let start = 0;\n const len = searchPart.length;\n\n while (start < len) {\n let end = searchPart.indexOf(\"&\", start);\n\n if (end === -1) {\n end = len;\n }\n\n handler(searchPart.slice(start, end), start, end);\n start = end + 1;\n }\n}\n\n// =============================================================================\n// Parse\n// =============================================================================\n\n/**\n * Parse a querystring and return an object of parameters.\n *\n * @example\n * ```typescript\n * parse(\"page=1&sort=name\");\n * // => { page: \"1\", sort: \"name\" }\n *\n * parse(\"items[]=a&items[]=b\", { arrayFormat: \"brackets\" });\n * // => { items: [\"a\", \"b\"] }\n * ```\n */\nexport const parse = (\n path: string,\n opts?: Options,\n): Record<string, unknown> => {\n const searchPart = getSearch(path);\n\n // Fast path: empty query string\n if (searchPart === \"\" || searchPart === \"?\") {\n return {};\n }\n\n // Fast path: no options - use simplified parser (skip strategy resolution)\n if (!opts) {\n return parseSimple(searchPart);\n }\n\n const options = makeOptions(opts);\n const params: Record<string, unknown> = {};\n\n // Process each parameter\n let start = 0;\n const len = searchPart.length;\n\n while (start < len) {\n let end = searchPart.indexOf(\"&\", start);\n\n if (end === -1) {\n end = len;\n }\n\n processParamChunk(searchPart, start, end, params, options.strategies);\n start = end + 1;\n }\n\n return params;\n};\n\n/**\n * Simplified parse without strategy resolution.\n * Used when no options are provided (most common case).\n * Returns string values only (no boolean/null conversion).\n *\n * @internal\n */\nfunction parseSimple(searchPart: string): Record<string, unknown> {\n const params: Record<string, unknown> = {};\n\n parseIntoInternal(searchPart, params);\n\n return params;\n}\n\n/**\n * Parse query string directly into a target object.\n * Avoids creating intermediate object and Object.assign.\n * Optimized for loose mode query params handling.\n *\n * @param queryString - Query string without leading \"?\"\n * @param target - Object to add params to\n */\nexport function parseInto(\n queryString: string,\n target: Record<string, unknown>,\n): void {\n if (queryString === \"\") {\n return;\n }\n\n parseIntoInternal(queryString, target);\n}\n\n/**\n * Internal function to parse query string into target object.\n * Shared by parseSimple and parseInto.\n *\n * @internal\n */\nfunction parseIntoInternal(\n searchPart: string,\n params: Record<string, unknown>,\n): void {\n let start = 0;\n const len = searchPart.length;\n\n while (start < len) {\n let end = searchPart.indexOf(\"&\", start);\n\n if (end === -1) {\n end = len;\n }\n\n // No strategies = simple decoding\n processParamChunk(searchPart, start, end, params);\n start = end + 1;\n }\n}\n\n// =============================================================================\n// Build\n// =============================================================================\n\n/**\n * Build a querystring from an object of parameters.\n *\n * @example\n * ```typescript\n * build({ page: 1, sort: \"name\" });\n * // => \"page=1&sort=name\"\n *\n * build({ items: [\"a\", \"b\"] }, { arrayFormat: \"brackets\" });\n * // => \"items[]=a&items[]=b\"\n * ```\n */\nexport const build = (\n params: Record<string, unknown>,\n opts?: Options,\n): string => {\n // Fast path for empty params (common case)\n const keys = Object.keys(params);\n\n if (keys.length === 0) {\n return \"\";\n }\n\n const options = makeOptions(opts);\n\n // Optimized: single loop instead of filter().map().filter().join()\n // Avoids creating 3 intermediate arrays\n const parts: string[] = [];\n\n for (const key of keys) {\n const value = params[key];\n\n // Skip undefined values (not serialisable)\n if (value === undefined) {\n continue;\n }\n\n const encoded = encode(key, value, options);\n\n // Skip empty strings (e.g., from nullFormat: \"hidden\")\n if (encoded) {\n parts.push(encoded);\n }\n }\n\n return parts.join(\"&\");\n};\n\n// =============================================================================\n// Omit\n// =============================================================================\n\n/**\n * Remove a list of parameters from a querystring.\n *\n * @example\n * ```typescript\n * omit(\"page=1&sort=name&limit=10\", [\"sort\", \"limit\"]);\n * // => { querystring: \"page=1\", removedParams: { sort: \"name\", limit: \"10\" } }\n * ```\n */\nexport const omit = (\n path: string,\n paramsToOmit: string[],\n opts?: Options,\n): OmitResponse => {\n const searchPart = getSearch(path);\n\n if (searchPart === \"\") {\n return { querystring: \"\", removedParams: {} };\n }\n\n // Fast path: no params to omit - keep entire querystring\n if (paramsToOmit.length === 0) {\n const hasPrefix = path.startsWith(\"?\");\n\n return {\n querystring: hasPrefix ? path : searchPart,\n removedParams: {},\n };\n }\n\n const options = makeOptions(opts);\n const hasPrefix = path.startsWith(\"?\");\n const omitSet = new Set(paramsToOmit);\n const kept: string[] = [];\n const removed: string[] = [];\n\n forEachParam(searchPart, (chunk) => {\n const eqPos = chunk.indexOf(\"=\");\n const rawName = eqPos === -1 ? chunk : chunk.slice(0, eqPos);\n const { name } = extractParamName(rawName);\n\n if (omitSet.has(name)) {\n removed.push(chunk);\n } else {\n kept.push(chunk);\n }\n });\n\n const querystring = kept.join(\"&\");\n\n return {\n querystring: hasPrefix && querystring ? `?${querystring}` : querystring,\n removedParams: parse(removed.join(\"&\"), options),\n };\n};\n\n// =============================================================================\n// Keep\n// =============================================================================\n\n/**\n * Keep only specified parameters from a querystring.\n *\n * @example\n * ```typescript\n * keep(\"page=1&sort=name&limit=10\", [\"page\"]);\n * // => { querystring: \"page=1\", keptParams: { page: \"1\" } }\n * ```\n */\nexport const keep = (\n path: string,\n paramsToKeep: string[],\n opts?: Options,\n): KeepResponse => {\n const searchPart = getSearch(path);\n\n if (searchPart === \"\") {\n return { keptParams: {}, querystring: \"\" };\n }\n\n // Fast path: no params to keep\n if (paramsToKeep.length === 0) {\n return { keptParams: {}, querystring: \"\" };\n }\n\n const options = makeOptions(opts);\n const keepSet = new Set(paramsToKeep);\n const kept: string[] = [];\n\n forEachParam(searchPart, (chunk) => {\n const eqPos = chunk.indexOf(\"=\");\n const rawName = eqPos === -1 ? chunk : chunk.slice(0, eqPos);\n const { name } = extractParamName(rawName);\n\n if (keepSet.has(name)) {\n kept.push(chunk);\n }\n });\n\n const querystring = kept.join(\"&\");\n\n return { keptParams: parse(querystring, options), querystring };\n};\n","// packages/route-tree/modules/parser/path-parser/buildPathFromPattern.ts\n\n/**\n * Standalone Path Building from Pattern.\n *\n * Pre-compiles route patterns for fast path building without regex at runtime.\n * R4 optimization used by Path.buildBasePath().\n *\n * NOTE: This module is designed for rou3 migration.\n * buildFromPattern() can be used as standalone buildPath without Path class.\n *\n * @example\n * ```typescript\n * // Compile once at initialization\n * const compiled = compilePathPattern(\"/users/:id/posts/:postId\");\n *\n * // Build many times (fast, no regex)\n * buildFromPattern(compiled, { id: \"123\", postId: \"456\" });\n * // → \"/users/123/posts/456\"\n * ```\n *\n * @module parser/path-parser/buildPathFromPattern\n */\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Pre-compiled path pattern for fast building.\n * Created once per route, reused for every buildPath call.\n */\nexport interface CompiledPathPattern {\n /** Static parts interleaved with params: [static0, static1, ..., staticN] */\n readonly staticParts: readonly string[];\n /** Parameter names in order: [param0, param1, ..., paramN-1] */\n readonly paramNames: readonly string[];\n /** Original pattern string (for debugging) */\n readonly pattern: string;\n}\n\n// =============================================================================\n// Pattern Parsing\n// =============================================================================\n\n/**\n * Pre-compiles a route pattern for fast path building.\n *\n * Supports:\n * - URL parameters: `/users/:id`\n * - Optional parameters: `/users/:id?`\n * - Wildcards: `/files/*` or `/files/*path`\n * - Matrix parameters: `/users;id=123`\n *\n * @param pattern - Route pattern string (e.g., \"/users/:id/posts/:postId\")\n * @returns Compiled pattern ready for buildFromPattern()\n *\n * @example\n * ```typescript\n * compilePathPattern(\"/users/:id\")\n * // → { staticParts: [\"/users/\", \"\"], paramNames: [\"id\"], pattern: \"/users/:id\" }\n *\n * compilePathPattern(\"/api/:version/:resource/:id\")\n * // → { staticParts: [\"/api/\", \"/\", \"/\", \"\"], paramNames: [\"version\", \"resource\", \"id\"], ... }\n * ```\n */\nexport function compilePathPattern(pattern: string): CompiledPathPattern {\n const staticParts: string[] = [];\n const paramNames: string[] = [];\n\n let lastIndex = 0;\n let currentStatic = \"\";\n\n // Combined regex for params and matrix\n // Group 1: URL param/wildcard (:param or *wildcard)\n // Group 2: Matrix param (;param=)\n const combinedRegex = /[*:](\\w*)\\??|;(\\w+)=?/g;\n let match: RegExpExecArray | null;\n\n while ((match = combinedRegex.exec(pattern)) !== null) {\n // Add static content before this match\n currentStatic += pattern.slice(lastIndex, match.index);\n\n // Check which group matched\n const urlParamName = match[1];\n const matrixParamName = match[2];\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- regex alternation: only one group matches\n if (matrixParamName === undefined) {\n // URL parameter or wildcard (:param or *wildcard)\n // urlParamName is defined here (may be empty string for bare *)\n const paramName = urlParamName || \"splat\";\n\n staticParts.push(currentStatic);\n currentStatic = \"\";\n paramNames.push(paramName);\n } else {\n // Matrix parameter (;param=)\n currentStatic += `;${matrixParamName}=`;\n staticParts.push(currentStatic);\n currentStatic = \"\";\n paramNames.push(matrixParamName);\n }\n\n lastIndex = combinedRegex.lastIndex;\n }\n\n // Add remaining static content\n currentStatic += pattern.slice(lastIndex);\n staticParts.push(currentStatic);\n\n return {\n staticParts,\n paramNames,\n pattern,\n };\n}\n\n// =============================================================================\n// Path Building\n// =============================================================================\n\n/**\n * Builds a URL path from a pre-compiled pattern and parameters.\n *\n * This is the hot path - optimized for speed:\n * - No regex at runtime\n * - O(n) string concatenation where n = number of params\n * - No object allocation\n *\n * @param compiled - Pre-compiled pattern from compilePathPattern()\n * @param params - Parameter values to inject (converted to string via String())\n * @returns Built URL path\n *\n * @example\n * ```typescript\n * const compiled = compilePathPattern(\"/users/:id/posts/:postId\");\n *\n * buildFromPattern(compiled, { id: \"123\", postId: \"456\" });\n * // → \"/users/123/posts/456\"\n *\n * buildFromPattern(compiled, { id: \"abc\", postId: \"def\" });\n * // → \"/users/abc/posts/def\"\n * ```\n */\nexport function buildFromPattern(\n compiled: CompiledPathPattern,\n params: Readonly<Record<string, unknown>>,\n): string {\n const { staticParts, paramNames } = compiled;\n\n // Fast path: no parameters\n if (paramNames.length === 0) {\n return staticParts[0];\n }\n\n // Build path using interleaved parts\n let path = staticParts[0];\n\n for (const [i, paramName] of paramNames.entries()) {\n path += String(params[paramName]) + staticParts[i + 1];\n }\n\n return path;\n}\n\n// =============================================================================\n// Convenience Functions\n// =============================================================================\n\n/**\n * One-shot path building (compiles and builds in one call).\n *\n * Use this only when pattern is used once.\n * For repeated builds, use compilePathPattern() + buildFromPattern().\n *\n * @param pattern - Route pattern string\n * @param params - Parameter values to inject\n * @returns Built URL path\n *\n * @example\n * ```typescript\n * buildPath(\"/users/:id\", { id: \"123\" });\n * // → \"/users/123\"\n * ```\n */\nexport function buildPathOnce(\n pattern: string,\n params: Readonly<Record<string, unknown>>,\n): string {\n return buildFromPattern(compilePathPattern(pattern), params);\n}\n","// packages/route-node/modules/parser/path-parser/constants.ts\n\n/**\n * Path Parser Constants.\n *\n * Consolidated constants for the path-parser module.\n *\n * @module parser/path-parser/constants\n */\n\nimport type { InternalPathOptions, Rule, URLParamsEncodingType } from \"./types\";\n\n// =============================================================================\n// Encoding Constants\n// =============================================================================\n\n/**\n * Optimized regex: only matches characters that ACTUALLY need encoding.\n * Excludes:\n * - A-Za-z0-9: alphanumeric (unreserved per RFC 3986)\n * - -._~: unreserved characters per RFC 3986\n * - !$'()*+,:;|: sub-delimiters we want to preserve\n *\n * Performance: This regex skips alphanumeric characters entirely,\n * avoiding unnecessary encodeURIComponent calls that return the same value.\n *\n * IMPORTANT: The 'u' (Unicode) flag is required to handle emoji and other\n * characters outside the Basic Multilingual Plane (BMP). Without it, the regex\n * matches individual UTF-16 code units (surrogates), and encodeURIComponent\n * fails on lone surrogates with \"URI malformed\" error.\n */\nconst NEEDS_ENCODING_REGEX = /[^\\w!$'()*+,.:;|~-]/gu;\n\n/**\n * Fast check regex (without global flag) to test if encoding is needed at all.\n * Used for pre-check optimization: if string contains only safe chars, skip encoding.\n *\n * IMPORTANT: The 'u' flag ensures proper handling of emoji/surrogate pairs.\n */\nconst NEEDS_ENCODING_TEST = /[^\\w!$'()*+,.:;|~-]/u;\n\n// =============================================================================\n// Encoding/Decoding Method Maps\n// =============================================================================\n\n/**\n * Encode a segment while preserving sub-delimiters.\n * Uses pre-check optimization: fast path for strings without special chars.\n *\n * Performance improvement over naive approach:\n * - Alphanumeric strings: 29-57x faster\n * - Strings with special chars: 2-3x faster\n */\nexport const encodeURIComponentExcludingSubDelims = (\n segment: string,\n): string => {\n // Fast path: if no special chars, return as-is\n if (!NEEDS_ENCODING_TEST.test(segment)) {\n return segment;\n }\n\n return segment.replaceAll(NEEDS_ENCODING_REGEX, (match) =>\n encodeURIComponent(match),\n );\n};\n\n/**\n * Encoding functions for each encoding type.\n */\nexport const ENCODING_METHODS: Record<\n URLParamsEncodingType,\n (param: string) => string\n> = {\n default: encodeURIComponentExcludingSubDelims,\n uri: encodeURI,\n uriComponent: encodeURIComponent,\n none: (val) => val,\n legacy: encodeURI,\n};\n\n/**\n * Decoding functions for each encoding type.\n */\nexport const DECODING_METHODS: Record<\n URLParamsEncodingType,\n (param: string) => string\n> = {\n default: decodeURIComponent,\n uri: decodeURI,\n uriComponent: decodeURIComponent,\n none: (val) => val,\n legacy: decodeURIComponent,\n};\n\n// =============================================================================\n// Path Defaults\n// =============================================================================\n\n/**\n * Default options for Path instances.\n */\nexport const DEFAULT_PATH_OPTIONS: InternalPathOptions = {\n urlParamsEncoding: \"default\",\n};\n\n// =============================================================================\n// Test Pattern Constants\n// =============================================================================\n\n/**\n * Regex patterns for Path.test() method.\n * Controls how URL matching handles query strings and end-of-path.\n */\nexport const TEST_PATTERNS = {\n /** Pattern for URL ending with optional query string: matches \"?\" followed by anything, or end of string */\n withQueryParams: String.raw`(\\?.*$|$)`,\n /** Pattern for URL ending: matches end of string only */\n withoutQueryParams: \"$\",\n} as const;\n\n/**\n * Regex patterns for Path.partialTest() method.\n * Controls delimiter matching for partial URL matching.\n */\nexport const PARTIAL_TEST_PATTERNS = {\n /** Delimiter pattern: matches /, ?, ., ;, or end of string */\n delimiter: String.raw`([/?.;]|$)`,\n} as const;\n\n// =============================================================================\n// Tokenizer Rules\n// =============================================================================\n\n/**\n * Default regex pattern for URL parameters without constraints.\n */\nexport const DEFAULT_PARAM_PATTERN = String.raw`[a-zA-Z0-9_.~%':|=+*@$-]+`;\n\n/**\n * Returns the constraint pattern or the default parameter pattern.\n * Wraps the pattern in a capturing group.\n *\n * @param match - The constraint pattern (e.g., \"<\\\\d+>\") or empty string\n * @returns Regex pattern string wrapped in parentheses\n *\n * @example\n * ```typescript\n * defaultOrConstrained('<\\\\d+>');\n * // => '(\\\\d+)'\n *\n * defaultOrConstrained('');\n * // => '([a-zA-Z0-9-_.~%\\':|=+\\\\*@$]+)'\n * ```\n */\nexport const defaultOrConstrained = (match: string): string => {\n const pattern = match\n ? match.replaceAll(/(^<|>$)/g, \"\")\n : DEFAULT_PARAM_PATTERN;\n\n return `(${pattern})`;\n};\n\n/**\n * Tokenization rules for parsing path patterns.\n *\n * Order matters: more specific rules should come first.\n * Each rule defines a pattern to match in the path string and\n * optionally a regex to use for URL matching.\n *\n * @example Path pattern examples:\n * - `/users/:id` - URL parameter\n * - `/users/:id<\\\\d+>` - Constrained URL parameter\n * - `/files/*path` - Splat parameter (matches rest of path)\n * - `/users/;section` - Matrix parameter\n * - `/users?page&limit` - Query parameters\n */\nexport const RULES: Rule[] = [\n /**\n * URL Parameter: `:paramName` or `:paramName<constraint>`\n * Matches: :id, :userId, :id<\\\\d+>\n */\n {\n name: \"url-parameter\",\n pattern: /^:([\\w-]*[\\dA-Za-z])(<(.+?)>)?/,\n regex: (match: RegExpMatchArray) =>\n new RegExp(defaultOrConstrained(match[2])),\n },\n /**\n * Splat Parameter: `*paramName`\n * Matches everything up to query string.\n * Example: *path in /files/*path matches \"docs/readme.md\"\n */\n {\n name: \"url-parameter-splat\",\n pattern: /^\\*([\\w-]*[\\dA-Za-z])/,\n regex: /([^?]*)/,\n },\n /**\n * Matrix Parameter: `;paramName` or `;paramName<constraint>`\n * RFC 3986 matrix URI syntax.\n * Example: ;section in /users/;section matches \";section=profile\"\n */\n {\n name: \"url-parameter-matrix\",\n pattern: /^;([\\w-]*[\\dA-Za-z])(<(.+?)>)?/,\n regex: (match: RegExpMatchArray) =>\n new RegExp(`;${match[1]}=${defaultOrConstrained(match[2])}`),\n },\n /**\n * Query Parameter: `?paramName` or `&paramName`\n * Defines expected query string parameters.\n * No regex - query params handled by search-params library.\n */\n {\n name: \"query-parameter\",\n pattern: /^[&?]:?([\\w-]*[\\dA-Za-z])/,\n },\n /**\n * Delimiter: `/` or `?`\n * Path segment separators.\n */\n {\n name: \"delimiter\",\n pattern: /^([/?])/,\n regex: (match: RegExpMatchArray) => new RegExp(`\\\\${match[0]}`),\n },\n /**\n * Sub-delimiter: `!`, `&`, `.`, `;`, `_`, `-`\n * RFC 3986 sub-delimiters used in paths.\n */\n {\n name: \"sub-delimiter\",\n pattern: /^([!&.;_-])/,\n regex: (match: RegExpMatchArray) => new RegExp(match[0]),\n },\n /**\n * Fragment: alphanumeric text\n * Static path segments like \"users\", \"posts\", \"api\".\n */\n {\n name: \"fragment\",\n pattern: /^([\\dA-Za-z]+)/,\n regex: (match: RegExpMatchArray) => new RegExp(match[0]),\n },\n];\n","// packages/route-node/modules/parser/path-parser/encoding.ts\n\n/**\n * Performance-critical code: string concatenation is 2x faster than template\n * literals/String.raw in V8 hot paths. See benchmarks for details.\n */\n/* eslint-disable prefer-template */\n\n/**\n * URL Parameter Encoding/Decoding.\n *\n * We encode using encodeURIComponent but we want to\n * preserve certain characters which are commonly used\n * (sub delimiters and ':')\n *\n * https://www.ietf.org/rfc/rfc3986.txt\n *\n * reserved = gen-delims / sub-delims\n * gen-delims = \":\" / \"/\" / \"?\" / \"#\" / \"[\" / \"]\" / \"@\"\n * sub-delims = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n * / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n *\n * @module parser/path-parser/encoding\n */\n\nimport { DECODING_METHODS, ENCODING_METHODS } from \"./constants\";\n\nimport type { URLParamsEncodingType } from \"./types\";\n\n/**\n * Encodes a URL parameter value using the specified encoding strategy.\n *\n * For splat parameters (*path), encodes each path segment separately\n * while preserving \"/\" characters.\n *\n * @param param - The parameter value to encode\n * @param encoding - The encoding strategy to use\n * @param isSpatParam - Whether this is a splat parameter\n * @returns The encoded parameter string\n *\n * @example\n * ```typescript\n * encodeParam('hello world', 'default', false);\n * // => 'hello%20world'\n *\n * encodeParam('docs/readme.md', 'default', true);\n * // => 'docs/readme.md' (splat preserves slashes)\n * ```\n */\nexport const encodeParam = (\n param: string | number | boolean,\n encoding: URLParamsEncodingType,\n isSpatParam: boolean,\n): string => {\n const encoder = ENCODING_METHODS[encoding];\n const str = String(param);\n\n if (!isSpatParam) {\n return encoder(str);\n }\n\n // Splat params: encode each segment separately, preserving \"/\"\n // H6 optimization: string concatenation is 2x faster than template literals\n const segments = str.split(\"/\");\n let result = encoder(segments[0]);\n\n for (let i = 1; i < segments.length; i++) {\n result += \"/\" + encoder(segments[i]);\n }\n\n return result;\n};\n\n/**\n * Decodes a URL parameter value using the specified encoding strategy.\n *\n * @param param - The encoded parameter string to decode\n * @param encoding - The encoding strategy to use for decoding\n * @returns The decoded parameter string\n *\n * @example\n * ```typescript\n * decodeParam('hello%20world', 'default');\n * // => 'hello world'\n * ```\n */\nexport const decodeParam = (\n param: string,\n encoding: URLParamsEncodingType,\n): string => DECODING_METHODS[encoding](param);\n","// packages/route-node/modules/parser/path-parser/tokeniser.ts\n\n/**\n * Path Pattern Tokenizer.\n *\n * Parses path patterns into tokens for matching and building URLs.\n *\n * @module parser/path-parser/tokeniser\n */\n\nimport { RULES } from \"./constants\";\n\nimport type { Token } from \"./types\";\n\n/**\n * Tokenizes a path pattern string into an array of tokens.\n *\n * Recursively parses the path using tokenization rules defined in constants.\n * Each token represents a segment of the path (static fragment, parameter, etc.).\n *\n * @param str - The path pattern string to tokenize\n * @param tokens - Accumulator array for tokens (used in recursion)\n * @returns Array of parsed tokens\n * @throws Error if path contains unparseable segments\n *\n * @example\n * ```typescript\n * tokenise('/users/:id');\n * // => [\n * // { type: 'delimiter', match: '/', ... },\n * // { type: 'fragment', match: 'users', ... },\n * // { type: 'delimiter', match: '/', ... },\n * // { type: 'url-parameter', match: ':id', val: ['id'], ... }\n * // ]\n *\n * tokenise('/files/*path');\n * // => [\n * // { type: 'delimiter', match: '/', ... },\n * // { type: 'fragment', match: 'files', ... },\n * // { type: 'delimiter', match: '/', ... },\n * // { type: 'url-parameter-splat', match: '*path', val: ['path'], ... }\n * // ]\n * ```\n */\nexport const tokenise = (str: string, tokens: Token[] = []): Token[] => {\n // Look for a matching rule\n const matched = RULES.some((rule) => {\n const match = rule.pattern.exec(str);\n\n if (!match) {\n return false;\n }\n\n tokens.push({\n type: rule.name,\n match: match[0],\n val: match.slice(1, 2),\n otherVal: match.slice(2),\n regex: typeof rule.regex === \"function\" ? rule.regex(match) : rule.regex,\n });\n\n if (match[0].length < str.length) {\n tokenise(str.slice(match[0].length), tokens);\n }\n\n return true;\n });\n\n // If no rules matched, throw an error (possible malformed path)\n if (!matched) {\n throw new Error(`Could not parse path '${str}'`);\n }\n\n return tokens;\n};\n","// packages/route-node/modules/parser/path-parser/Path.ts\n\n/**\n * Performance-critical code: string concatenation is 2x faster than template\n * literals/String.raw in V8 hot paths. See benchmarks for details.\n */\n/* eslint-disable prefer-template */\n/* eslint-disable unicorn/prefer-string-raw */\n\n/**\n * Path Class for URL Routing.\n *\n * Parses, matches, and builds URLs with support for parameters and query strings.\n *\n * @module parser/path-parser/Path\n */\n\nimport {\n build as buildQueryParams,\n parse as parseQueryParams,\n} from \"search-params\";\n\nimport { buildFromPattern } from \"./buildPathFromPattern\";\nimport {\n DEFAULT_PATH_OPTIONS,\n defaultOrConstrained,\n PARTIAL_TEST_PATTERNS,\n TEST_PATTERNS,\n} from \"./constants\";\nimport { decodeParam, encodeParam } from \"./encoding\";\nimport { tokenise } from \"./tokeniser\";\n\nimport type { CompiledPathPattern } from \"./buildPathFromPattern\";\nimport type {\n InternalPathOptions,\n ParamValue,\n PathBuildOptions,\n PathOptions,\n PathPartialTestOptions,\n PathTestOptions,\n TestMatch,\n Token,\n URLParamsEncodingType,\n} from \"./types\";\nimport type { Options } from \"search-params\";\n\n// =============================================================================\n// Types for Regex Cache\n// =============================================================================\n\n/**\n * Cached RegExp variations for case-sensitive and case-insensitive matching.\n */\ninterface RegexVariation {\n /** Case-sensitive regex */\n sensitive: RegExp;\n /** Case-insensitive regex */\n insensitive: RegExp;\n}\n\n/**\n * All precompiled regex variations for test() and partialTest().\n * Eliminates RegExp creation on every call (major performance win).\n */\ninterface RegexCache {\n /** For test() with strictTrailingSlash: false (default) */\n test: RegexVariation;\n /** For test() with strictTrailingSlash: true */\n testStrict: RegexVariation;\n /** For partialTest() with delimited: false */\n partial: RegexVariation;\n /** For partialTest() with delimited: true (default) */\n partialDelimited: RegexVariation;\n}\n\n// =============================================================================\n// Module-Private Helper Functions\n// =============================================================================\n\n/**\n * Checks if a value is defined (not null or undefined).\n */\nconst isDefined = (val: unknown): boolean => val !== undefined && val !== null;\n\n/**\n * Type guard to check if a value is a primitive parameter value.\n */\nconst isParamValue = (val: unknown): val is ParamValue =>\n typeof val === \"string\" ||\n typeof val === \"number\" ||\n typeof val === \"boolean\";\n\n/**\n * Type guard to check if a value is encodable (primitive or array of primitives).\n * Filters out null, undefined, and invalid types.\n */\nconst isEncodableParam = (val: unknown): val is ParamValue | ParamValue[] => {\n if (!isDefined(val)) {\n return false;\n }\n\n if (isParamValue(val)) {\n return true;\n }\n\n if (Array.isArray(val)) {\n return val.every((v) => isParamValue(v));\n }\n\n return false;\n};\n\n/**\n * Modifies regex source to make trailing slash optional.\n * Used in test() for flexible URL matching.\n *\n * @param source - Regex source string\n * @returns Modified regex source with optional trailing slash\n */\nconst optTrailingSlash = (source: string) => {\n if (source === \"\\\\/\") {\n return source;\n }\n\n return source.replace(/\\\\\\/$/, \"\") + \"(?:\\\\/)?\";\n};\n\n/**\n * Appends delimiter pattern for partial URL matching.\n * Ensures partial matches stop at path boundaries.\n *\n * @param source - Regex source string\n * @returns Modified regex source with delimiter boundary\n */\nconst upToDelimiter = (source: string) => {\n return /(\\/)$/.test(source)\n ? source\n : source + PARTIAL_TEST_PATTERNS.delimiter;\n};\n\n/**\n * Appends a query parameter value to the params object.\n * If param already exists (e.g., from URL param), combines into array.\n *\n * Note: The search-params library already combines duplicate query params,\n * so this is only called once per param key. The array accumulation handles\n * the case where URL param and query param share the same name.\n *\n * @param params - Target params object (mutated)\n * @param param - Parameter name\n * @param val - Parameter value to append\n * @returns The mutated params object\n */\nconst appendQueryParam = (\n params: Record<string, unknown>,\n param: string,\n val: unknown = \"\",\n): Record<string, unknown> => {\n const existingVal = params[param];\n\n // Existing value from URL param - combine with query param value\n params[param] = existingVal === undefined ? val : [existingVal, val];\n\n return params;\n};\n\n// =============================================================================\n// Path Class\n// =============================================================================\n\n/**\n * URL Path parser, matcher, and builder.\n *\n * Supports URL parameters (`:id`), splat parameters (`*path`),\n * matrix parameters (`;section`), query parameters (`?page`),\n * and parameter constraints (`:id<\\\\d+>`).\n *\n * @template T - Type of extracted/provided parameters object\n *\n * @example\n * ```typescript\n * const path = new Path('/users/:id/posts/:postId');\n *\n * // Match URL and extract params\n * path.test('/users/123/posts/456');\n * // => { id: '123', postId: '456' }\n *\n * // Build URL from params\n * path.build({ id: '123', postId: '456' });\n * // => '/users/123/posts/456'\n * ```\n */\nexport class Path<T extends Record<string, unknown> = Record<string, unknown>> {\n /** Original path pattern string */\n path: string;\n\n /** Parsed tokens from the path pattern */\n tokens: Token[];\n\n /** True if pattern contains any URL parameters (:param, *splat, ;matrix) */\n hasUrlParams: boolean;\n\n /** True if pattern contains a splat parameter (*path) */\n hasSpatParam: boolean;\n\n /** True if pattern contains matrix parameters (;param) */\n hasMatrixParams: boolean;\n\n /** True if pattern contains query parameters (?param) */\n hasQueryParams: boolean;\n\n /** Merged options with defaults */\n options: InternalPathOptions;\n\n /** Names of splat parameters in the pattern */\n spatParams: string[];\n\n /** Names of all URL parameters (including splat and matrix) */\n urlParams: string[];\n\n /** Names of query parameters in the pattern */\n queryParams: string[];\n\n /** Names of all parameters (URL + query) */\n params: string[];\n\n /** Compiled regex source for URL matching */\n source: string;\n\n /**\n * Precompiled regex cache for test() and partialTest().\n * Eliminates RegExp creation overhead in hot paths.\n */\n private readonly regexCache: RegexCache;\n\n /**\n * Precompiled constraint patterns for build() validation.\n * Maps parameter name to { pattern: RegExp, constraint: original constraint string }.\n */\n private readonly constraintPatterns: Map<\n string,\n { pattern: RegExp; constraint: string }\n >;\n\n /**\n * Cached options for build() when no overrides are provided.\n * Eliminates object creation overhead in hot paths.\n */\n private readonly buildOptionsCache: {\n readonly ignoreConstraints: false;\n readonly ignoreSearch: false;\n readonly queryParams: Options;\n readonly urlParamsEncoding: URLParamsEncodingType;\n };\n\n // ===========================================================================\n // R4 Optimization: Pre-compiled Build Pattern\n // ===========================================================================\n\n /**\n * Pre-compiled pattern for fast path building.\n * Used by buildFromPattern() for O(n) path construction without token iteration.\n */\n private readonly compiledBuildPattern: CompiledPathPattern;\n\n /**\n * Creates a new Path instance.\n *\n * @param path - Path pattern to parse (e.g., '/users/:id?page')\n * @param options - Optional configuration for encoding and query params\n * @throws Error if path is empty\n *\n * @example\n * ```typescript\n * // Simple path with URL param\n * new Path('/users/:id');\n *\n * // With constraint\n * new Path('/users/:id<\\\\d+>');\n *\n * // With query params\n * new Path('/users/:id?page&limit');\n *\n * // With encoding options\n * new Path('/users/:id', { urlParamsEncoding: 'uriComponent' });\n * ```\n */\n constructor(path: string, options?: PathOptions) {\n if (!path) {\n throw new Error(\"Missing path in Path constructor\");\n }\n\n this.path = path;\n this.options = {\n ...DEFAULT_PATH_OPTIONS,\n ...options,\n };\n this.tokens = tokenise(path);\n\n this.hasUrlParams = this.tokens.some((t) =>\n t.type.startsWith(\"url-parameter\"),\n );\n this.hasSpatParam = this.tokens.some((t) => t.type.endsWith(\"splat\"));\n this.hasMatrixParams = this.tokens.some((t) => t.type.endsWith(\"matrix\"));\n this.hasQueryParams = this.tokens.some((t) =>\n t.type.startsWith(\"query-parameter\"),\n );\n\n // Extract named parameters from tokens\n this.spatParams = this.getParams(\"url-parameter-splat\");\n this.urlParams = this.getParams(/^url-parameter/);\n // Query params\n this.queryParams = this.getParams(\"query-parameter\");\n // All params\n this.params = [...this.urlParams, ...this.queryParams];\n\n // Regular expressions for url part only (full and partial match)\n let source = \"\";\n\n for (const t of this.tokens) {\n if (t.regex !== undefined) {\n source += t.regex.source;\n }\n }\n\n this.source = source;\n\n // Precompile all regex variations\n // Eliminates RegExp creation on every test()/partialTest() call\n const testSource = optTrailingSlash(source);\n const testStrictSource = source;\n const partialSource = source;\n const partialDelimitedSource = upToDelimiter(source);\n\n const testSuffix = this.hasQueryParams\n ? TEST_PATTERNS.withQueryParams\n : TEST_PATTERNS.withoutQueryParams;\n\n this.regexCache = {\n test: {\n sensitive: new RegExp(\"^\" + testSource + testSuffix),\n insensitive: new RegExp(\"^\" + testSource + testSuffix, \"i\"),\n },\n testStrict: {\n sensitive: new RegExp(\"^\" + testStrictSource + testSuffix),\n insensitive: new RegExp(\"^\" + testStrictSource + testSuffix, \"i\"),\n },\n partial: {\n sensitive: new RegExp(\"^\" + partialSource),\n insensitive: new RegExp(\"^\" + partialSource, \"i\"),\n },\n partialDelimited: {\n sensitive: new RegExp(\"^\" + partialDelimitedSource),\n insensitive: new RegExp(\"^\" + partialDelimitedSource, \"i\"),\n },\n };\n\n // Precompile constraint patterns for build() validation\n this.constraintPatterns = new Map();\n const constrainedTokens = this.tokens.filter(\n (t) => t.type.startsWith(\"url-parameter\") && !t.type.endsWith(\"-splat\"),\n );\n\n for (const t of constrainedTokens) {\n const paramName = t.val[0];\n const constraintStr = t.otherVal[0]; // e.g., \"<\\\\d+>\" or \"\"\n const pattern = new RegExp(\n \"^\" + defaultOrConstrained(constraintStr) + \"$\",\n );\n\n this.constraintPatterns.set(paramName, {\n pattern,\n constraint: constraintStr,\n });\n }\n\n // Pre-compute build options cache to avoid object creation in build()\n this.buildOptionsCache = {\n ignoreConstraints: false,\n ignoreSearch: false,\n queryParams: this.options.queryParams ?? {},\n urlParamsEncoding: this.options.urlParamsEncoding,\n };\n\n // R4 Optimization: Pre-compile build pattern for fast path construction\n // Filter out query parameters at parse time\n const buildTokens = this.tokens.filter(\n (t) => !t.type.startsWith(\"query-parameter\"),\n );\n\n // Pre-compute static parts and param names for interleaved building\n const staticParts: string[] = [];\n const paramNames: string[] = [];\n let currentStatic = \"\";\n\n for (const t of buildTokens) {\n if (\n t.type.startsWith(\"url-parameter\") &&\n t.type !== \"url-parameter-matrix\"\n ) {\n // Save accumulated static, then add param\n staticParts.push(currentStatic);\n currentStatic = \"\";\n paramNames.push(t.val[0]);\n } else if (t.type === \"url-parameter-matrix\") {\n // Matrix params need special handling - accumulate prefix\n currentStatic += \";\" + t.val[0] + \"=\";\n staticParts.push(currentStatic);\n currentStatic = \"\";\n paramNames.push(t.val[0]);\n } else {\n // Static content (delimiter, fragment, sub-delimiter)\n currentStatic += t.match;\n }\n }\n\n // Add trailing static (may be empty)\n staticParts.push(currentStatic);\n\n this.compiledBuildPattern = {\n staticParts,\n paramNames,\n pattern: path,\n };\n }\n\n /**\n * Factory method to create a Path instance.\n * Alternative to using `new Path()` directly.\n *\n * @param path - Path pattern to parse\n * @param options - Optional configuration\n * @returns New Path instance\n */\n static createPath<\n T extends Record<string, unknown> = Record<string, unknown>,\n >(path: string, options?: PathOptions): Path<T> {\n return new Path<T>(path, options);\n }\n\n /**\n * Checks if a parameter name is a query parameter.\n *\n * @param name - Parameter name to check\n * @returns True if the parameter is defined in query string\n */\n isQueryParam(name: string): boolean {\n return this.queryParams.includes(name);\n }\n\n /**\n * Checks if a parameter name is a splat parameter.\n *\n * @param name - Parameter name to check\n * @returns True if the parameter is a splat (*path)\n */\n isSpatParam(name: string): boolean {\n return this.spatParams.includes(name);\n }\n\n /**\n * Tests if a URL exactly matches this path pattern.\n * Extracts parameter values from matching URLs.\n *\n * This is the HOT PATH for leaf node matching in route trees.\n *\n * @param path - URL to test against the pattern\n * @param opts - Test options (case sensitivity, trailing slash handling)\n * @returns Extracted parameters object, or null if no match\n *\n * @example\n * ```typescript\n * const pattern = new Path('/users/:id');\n *\n * pattern.test('/users/123');\n * // => { id: '123' }\n *\n * pattern.test('/users/123/posts');\n * // => null (not exact match)\n *\n * pattern.test('/USERS/123');\n * // => { id: '123' } (case insensitive by default)\n *\n * pattern.test('/USERS/123', { caseSensitive: true });\n * // => null\n * ```\n */\n test(path: string, opts?: PathTestOptions): TestMatch<T> {\n // Direct property access avoids object spread overhead\n const caseSensitive = opts?.caseSensitive ?? false;\n const strictTrailingSlash = opts?.strictTrailingSlash ?? false;\n\n // Use precompiled regex instead of creating on every call\n const regexVariation = strictTrailingSlash\n ? this.regexCache.testStrict\n : this.regexCache.test;\n const regex = caseSensitive\n ? regexVariation.sensitive\n : regexVariation.insensitive;\n\n const match = this.urlTestWithRegex(\n path,\n regex,\n opts?.urlParamsEncoding ?? this.options.urlParamsEncoding,\n );\n\n // If no match, or no query params, no need to go further\n if (!match || !this.hasQueryParams) {\n return match;\n }\n\n // Extract query params\n const queryParams = parseQueryParams(\n path,\n opts?.queryParams ?? this.options.queryParams,\n );\n\n // Single pass: check for unexpected params AND copy in one loop\n // Avoids Object.keys() allocation and double iteration\n let hasUnexpected = false;\n\n for (const p in queryParams) {\n if (this.isQueryParam(p)) {\n (match as Record<string, unknown>)[p] = queryParams[p];\n } else {\n hasUnexpected = true;\n }\n }\n\n return hasUnexpected ? null : match;\n }\n\n /**\n * Tests if a URL starts with this path pattern.\n * Used for matching branch nodes in route trees.\n *\n * This is the HOT PATH for branch node matching in route trees.\n *\n * @param path - URL to test against the pattern\n * @param opts - Test options (case sensitivity, delimiter handling)\n * @returns Extracted parameters object, or null if no match\n *\n * @example\n * ```typescript\n * const pattern = new Path('/users/:id');\n *\n * pattern.partialTest('/users/123/posts/456');\n * // => { id: '123' } (matches prefix)\n *\n * pattern.partialTest('/users/123');\n * // => { id: '123' }\n *\n * pattern.partialTest('/posts/123');\n * // => null\n * ```\n */\n partialTest(path: string, opts?: PathPartialTestOptions): TestMatch<T> {\n // Direct property access avoids object spread overhead\n const caseSensitive = opts?.caseSensitive ?? false;\n const delimited = opts?.delimited ?? true;\n\n // Use precompiled regex instead of creating on every call\n const regexVariation = delimited\n ? this.regexCache.partialDelimited\n : this.regexCache.partial;\n const regex = caseSensitive\n ? regexVariation.sensitive\n : regexVariation.insensitive;\n\n const match = this.urlTestWithRegex(\n path,\n regex,\n opts?.urlParamsEncoding ?? this.options.urlParamsEncoding,\n );\n\n if (!match) {\n return match;\n }\n\n if (!this.hasQueryParams) {\n return match;\n }\n\n const queryParams = parseQueryParams(\n path,\n opts?.queryParams ?? this.options.queryParams,\n );\n\n // for-in is faster than Object.keys() iteration\n for (const p in queryParams) {\n if (this.isQueryParam(p)) {\n appendQueryParam(match as Record<string, unknown>, p, queryParams[p]);\n }\n }\n\n return match;\n }\n\n /**\n * Builds a URL from parameter values.\n * Encodes parameters and validates constraints.\n *\n * @param params - Parameter values to substitute into the pattern\n * @param opts - Build options (constraint validation, query string handling)\n * @returns Constructed URL string\n * @throws Error if required parameters are missing\n * @throws Error if parameters violate constraints (unless ignoreConstraints)\n *\n * @example\n * ```typescript\n * const pattern = new Path('/users/:id/posts/:postId?page');\n *\n * pattern.build({ id: '123', postId: '456' });\n * // => '/users/123/posts/456'\n *\n * pattern.build({ id: '123', postId: '456', page: '1' });\n * // => '/users/123/posts/456?page=1'\n *\n * pattern.build({ id: '123' });\n * // => Error: requires missing parameters { postId }\n * ```\n */\n build(params: T = {} as T, opts?: PathBuildOptions): string {\n // Use cached options when no overrides, avoiding object creation\n const options = opts\n ? {\n ignoreConstraints: opts.ignoreConstraints ?? false,\n ignoreSearch: opts.ignoreSearch ?? false,\n queryParams: opts.queryParams ?? this.buildOptionsCache.queryParams,\n urlParamsEncoding:\n opts.urlParamsEncoding ?? this.buildOptionsCache.urlParamsEncoding,\n }\n : this.buildOptionsCache;\n\n const encodedUrlParams = this.encodeUrlParams(\n params,\n options.urlParamsEncoding,\n );\n\n this.validateRequiredParams(params);\n\n if (!options.ignoreConstraints) {\n this.validateConstraints(encodedUrlParams);\n }\n\n const base = this.buildBasePath(encodedUrlParams);\n\n if (options.ignoreSearch) {\n return base;\n }\n\n return this.buildWithSearch(base, params, options.queryParams);\n }\n\n // ===========================================================================\n // Private Methods - Encoding\n // ===========================================================================\n\n /**\n * Encodes all URL parameters from the input params object.\n * Skips query parameters (handled separately by search-params).\n *\n * @param params - Raw parameter values\n * @param encoding - Encoding strategy to use\n * @returns Object with encoded parameter values\n */\n private encodeUrlParams(\n params: T,\n encoding: URLParamsEncodingType,\n ): Record<string, unknown> {\n const encoded: Record<string, unknown> = {};\n\n for (const key of Object.keys(params)) {\n if (this.isQueryParam(key)) {\n continue;\n }\n\n const val = params[key];\n\n if (!isEncodableParam(val)) {\n continue;\n }\n\n encoded[key] = this.encodeParamValue(val, key, encoding);\n }\n\n return encoded;\n }\n\n /**\n * Encodes a single parameter value.\n * Handles booleans, arrays, and primitive values.\n *\n * @param val - Value to encode (already validated by isEncodableParam)\n * @param key - Parameter name (to check if splat)\n * @param encoding - Encoding strategy to use\n * @returns Encoded value (string, boolean, or array)\n */\n private encodeParamValue(\n val: ParamValue | ParamValue[],\n key: string,\n encoding: URLParamsEncodingType,\n ): unknown {\n if (typeof val === \"boolean\") {\n return val;\n }\n\n const isSpatParam = this.isSpatParam(key);\n\n if (Array.isArray(val)) {\n return val.map((v) => encodeParam(v, encoding, isSpatParam));\n }\n\n return encodeParam(val, encoding, isSpatParam);\n }\n\n // ===========================================================================\n // Private Methods - Validation\n // ===========================================================================\n\n /**\n * Validates that all required URL parameters are present.\n *\n * @param params - Parameters to validate\n * @throws Error listing missing required parameters\n */\n private validateRequiredParams(params: T): void {\n const missingParameters = this.urlParams.filter(\n (p) => !isDefined(params[p]),\n );\n\n if (missingParameters.length > 0) {\n throw new Error(\n \"Cannot build path: '\" +\n this.path +\n \"' requires missing parameters { \" +\n missingParameters.join(\", \") +\n \" }\",\n );\n }\n }\n\n /**\n * Validates that encoded parameter values match their constraints.\n * Uses precompiled constraint patterns.\n *\n * @param encodedUrlParams - Already encoded parameter values\n * @throws Error if any parameter violates its constraint\n */\n private validateConstraints(encodedUrlParams: Record<string, unknown>): void {\n // Use precompiled constraint patterns\n for (const [paramName, { pattern, constraint }] of this\n .constraintPatterns) {\n const value = String(encodedUrlParams[paramName]);\n\n if (!pattern.test(value)) {\n // Extract constraint pattern without angle brackets for cleaner message\n // If no explicit constraint, show the default pattern description\n const constraintPattern = constraint\n ? constraint.replaceAll(/(^<)|(>$)/g, \"\")\n : \"[^/]+\";\n\n throw new Error(\n `Parameter '${paramName}' of '${this.path}' has invalid format: ` +\n `got '${value}', expected to match '${constraintPattern}'`,\n );\n }\n }\n }\n\n // ===========================================================================\n // Private Methods - URL Building\n // ===========================================================================\n\n /**\n * Builds the base URL path (without query string).\n * Uses buildFromPattern with pre-compiled pattern for O(n) construction.\n * R4 Optimization: 3x faster than token iteration.\n *\n * @param encodedUrlParams - Encoded parameter values\n * @returns Built URL path string\n */\n private buildBasePath(encodedUrlParams: Record<string, unknown>): string {\n return buildFromPattern(this.compiledBuildPattern, encodedUrlParams);\n }\n\n /**\n * Appends query string to the base path.\n * Uses search-params library for query string formatting.\n *\n * @param base - Base URL path\n * @param params - All parameters (filters to query params only)\n * @param queryParamsOptions - Formatting options for search-params\n * @returns Complete URL with query string (if any)\n */\n private buildWithSearch(\n base: string,\n params: T,\n queryParamsOptions: Options | undefined,\n ): string {\n const searchParams: Record<string, unknown> = {};\n\n // 'in' operator is O(1) vs Object.keys().includes() which is O(n²)\n for (const paramName of this.queryParams) {\n if (paramName in params) {\n searchParams[paramName] = params[paramName];\n }\n }\n\n const searchPart = buildQueryParams(searchParams, queryParamsOptions);\n\n return searchPart ? base + \"?\" + searchPart : base;\n }\n\n // ===========================================================================\n // Private Methods - Utilities\n // ===========================================================================\n\n /**\n * Extracts parameter names from tokens by type.\n * Single pass instead of filter + map.\n *\n * @param type - Token type to filter (string for exact match, RegExp for pattern)\n * @returns Array of parameter names\n */\n private getParams(type: string | RegExp): string[] {\n const result: string[] = [];\n const isRegex = type instanceof RegExp;\n\n for (const t of this.tokens) {\n if (isRegex ? type.test(t.type) : t.type === type) {\n result.push(t.val[0]);\n }\n }\n\n return result;\n }\n\n /**\n * Core regex matching logic for test() and partialTest().\n * Uses precompiled regex and extracts parameter values.\n *\n * @param path - URL to test\n * @param regex - Precompiled RegExp to use for matching\n * @param urlParamsEncoding - Decoding strategy for extracted values\n * @returns Extracted parameters object, or null if no match\n */\n private urlTestWithRegex(\n path: string,\n regex: RegExp,\n urlParamsEncoding: URLParamsEncodingType,\n ): TestMatch<T> {\n const match = regex.exec(path);\n\n if (!match) {\n return null;\n }\n\n if (this.urlParams.length === 0) {\n return {} as T;\n }\n\n // Reduce named params to key-value pairs\n const result: Record<string, unknown> = {};\n\n for (let i = 0; i < this.urlParams.length; i++) {\n result[this.urlParams[i]] = decodeParam(match[i + 1], urlParamsEncoding);\n }\n\n return result as T;\n }\n}\n","// packages/route-node/modules/parser/defaultParserFactory.ts\n\n/**\n * Default path parser factory using path-parser library.\n *\n * @module defaultParserFactory\n */\n\nimport { Path } from \"./path-parser\";\n\nimport type { PathParser } from \"../types\";\n\n/**\n * Factory interface for creating PathParser instances.\n */\nexport interface PathParserFactory {\n create: (path: string) => PathParser;\n}\n\n/**\n * Creates a PathParser instance.\n *\n * The Path class directly implements the PathParser interface,\n * eliminating wrapper overhead for better performance.\n *\n * @param path - The path pattern to parse\n * @returns PathParser instance\n */\nfunction createPathParser(path: string): PathParser {\n return new Path(path);\n}\n\n/**\n * Default factory that creates PathParser instances.\n *\n * This factory wraps the path-parser library's Path class, providing\n * the standard implementation used by RouteNode.\n *\n * @example\n * ```typescript\n * import { defaultParserFactory } from \"route-tree\";\n *\n * const parser = defaultParserFactory.create(\"/users/:id\");\n * parser.test(\"/users/123\"); // { id: \"123\" }\n * ```\n */\nexport const defaultParserFactory: PathParserFactory = {\n create: createPathParser,\n};\n","// packages/route-node/modules/builder/buildTree.ts\n\n/**\n * Tree Building.\n *\n * Constructs the mutable tree structure from route definitions.\n *\n * @module builder/buildTree\n */\n\nimport { defaultParserFactory } from \"../parser/defaultParserFactory\";\n\nimport type { PathParser, RouteDefinition } from \"../types\";\n\n// =============================================================================\n// Mutable Node Type (internal)\n// =============================================================================\n\n/**\n * Mutable version of RouteTree used during building.\n * After building, this is converted to immutable RouteTree.\n */\nexport interface MutableRouteNode {\n name: string;\n path: string;\n absolute: boolean;\n parser: PathParser | null;\n children: MutableRouteNode[];\n parent: MutableRouteNode | null;\n\n // These are computed later by computeCaches\n nonAbsoluteChildren: MutableRouteNode[];\n absoluteDescendants: MutableRouteNode[];\n childrenByName: Map<string, MutableRouteNode>;\n parentSegments: MutableRouteNode[];\n fullName: string;\n staticChildrenByFirstSegment: Map<string, MutableRouteNode[]>;\n}\n\n// =============================================================================\n// Building Functions\n// =============================================================================\n\n/**\n * Creates a mutable node from a route definition.\n *\n * @param definition - Route definition object\n * @param definition.name - Route name\n * @param definition.path - Route path\n * @param definition.children - Optional child routes\n * @param parent - Parent node (null for root)\n * @returns Mutable node\n */\nfunction createNode(\n definition: {\n name: string;\n path: string;\n children?: RouteDefinition[] | undefined;\n },\n parent: MutableRouteNode | null,\n): MutableRouteNode {\n const path = definition.path;\n const absolute = path.startsWith(\"~\");\n const normalizedPath = absolute ? path.slice(1) : path;\n\n const node: MutableRouteNode = {\n name: definition.name,\n path: normalizedPath,\n absolute,\n parser: normalizedPath ? defaultParserFactory.create(normalizedPath) : null,\n children: [],\n parent,\n // These will be computed by computeCaches\n nonAbsoluteChildren: [],\n absoluteDescendants: [],\n childrenByName: new Map(),\n parentSegments: [],\n fullName: \"\",\n staticChildrenByFirstSegment: new Map(),\n };\n\n // Recursively add children\n if (definition.children) {\n for (const childDef of definition.children) {\n const childNode = createNode(childDef, node);\n\n node.children.push(childNode);\n }\n }\n\n return node;\n}\n\n/**\n * Resolves parent node for dot-notation names.\n *\n * For example, \"users.profile\" needs to find the \"users\" node first.\n *\n * @param root - Root node\n * @param name - Route name (possibly with dots)\n * @returns Parent node and final name segment\n */\nfunction resolveParent(\n root: MutableRouteNode,\n name: string,\n): { parent: MutableRouteNode; finalName: string } {\n const parts = name.split(\".\");\n\n if (parts.length === 1) {\n return { parent: root, finalName: name };\n }\n\n // Navigate to parent\n let current = root;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const partName = parts[i];\n\n // validateRoutes ensures parent exists before building\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n current = current.children.find((c) => c.name === partName)!;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return { parent: current, finalName: parts.at(-1)! };\n}\n\n/**\n * Builds the mutable tree structure from route definitions.\n *\n * Handles:\n * - Creating root node\n * - Processing flat and nested routes\n * - Dot-notation names (e.g., \"users.profile\")\n *\n * @param rootName - Root node name (typically \"\")\n * @param rootPath - Root node path (typically \"\")\n * @param routes - Route definitions\n * @returns Mutable root node\n */\nexport function buildTree(\n rootName: string,\n rootPath: string,\n routes: readonly RouteDefinition[],\n): MutableRouteNode {\n // Create root node\n const root = createNode({ name: rootName, path: rootPath }, null);\n\n // First pass: add routes with nested children\n const flatRoutes: RouteDefinition[] = [];\n\n for (const route of routes) {\n if (route.name.includes(\".\")) {\n // Dot-notation name - process later\n flatRoutes.push(route);\n } else if (route.children && route.children.length > 0) {\n // Has children - add directly\n const node = createNode(route, root);\n\n root.children.push(node);\n } else {\n // Simple route without children\n flatRoutes.push(route);\n }\n }\n\n // Second pass: add flat routes and dot-notation names\n for (const route of flatRoutes) {\n const { parent, finalName } = resolveParent(root, route.name);\n\n const node = createNode(\n { name: finalName, path: route.path, children: route.children },\n parent,\n );\n\n parent.children.push(node);\n }\n\n return root;\n}\n","// packages/route-node/modules/builder/computeCaches.ts\n\n/**\n * Cache Computation.\n *\n * Computes all pre-computed caches and freezes the tree.\n *\n * @module builder/computeCaches\n */\n\nimport type { MutableRouteNode } from \"./buildTree\";\nimport type { RouteTree } from \"../types\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/** Shared empty map for nodes with no static children (avoids allocation) */\nconst EMPTY_STATIC_INDEX: ReadonlyMap<string, readonly RouteTree[]> = new Map();\n\n// =============================================================================\n// Static Children Index\n// =============================================================================\n\n/**\n * Extracts the first static segment from a path pattern.\n *\n * Returns null for dynamic-only paths (starting with :param or *splat).\n *\n * @example\n * extractFirstStaticSegment(\"/users\") → \"users\"\n * extractFirstStaticSegment(\"/users/:id\") → \"users\"\n * extractFirstStaticSegment(\"/users?tab\") → \"users\"\n * extractFirstStaticSegment(\"/:id\") → null (dynamic)\n * extractFirstStaticSegment(\"*\") → null (splat)\n * extractFirstStaticSegment(\"/\") → null (root slash)\n *\n * @param path - Path pattern (without ~ prefix)\n * @returns First static segment or null if dynamic\n */\nfunction extractFirstStaticSegment(path: string): string | null {\n // Skip leading slash\n const start = path.startsWith(\"/\") ? 1 : 0;\n\n // Find end of first segment: next \"/\" or \"?\" (whichever comes first)\n let end = path.indexOf(\"/\", start);\n const queryPos = path.indexOf(\"?\", start);\n\n if (queryPos !== -1 && (end === -1 || queryPos < end)) {\n end = queryPos;\n }\n\n const segment = end === -1 ? path.slice(start) : path.slice(start, end);\n\n // Dynamic segments start with : or *, empty segment means root \"/\"\n if (\n segment === \"\" ||\n segment.startsWith(\":\") ||\n segment.startsWith(\"*\") ||\n segment.includes(\"(\") // optional segment like (locale)\n ) {\n return null;\n }\n\n // Normalize to lowercase for case-insensitive index lookup\n return segment.toLowerCase();\n}\n\n/**\n * Computes static children index for O(1) matching.\n *\n * Groups non-absolute children by their first static path segment.\n * Routes with dynamic first segments are not indexed (matched via linear search).\n *\n * @param children - Non-absolute children to index\n * @param freeze - Whether to freeze the result\n * @returns Map of first segment → routes\n */\nfunction computeStaticChildrenIndex(\n children: readonly RouteTree[],\n freeze: boolean,\n): ReadonlyMap<string, readonly RouteTree[]> {\n if (children.length === 0) {\n return EMPTY_STATIC_INDEX;\n }\n\n const index = new Map<string, RouteTree[]>();\n\n for (const child of children) {\n const segment = extractFirstStaticSegment(child.path);\n\n if (segment !== null) {\n const existing = index.get(segment);\n\n if (existing) {\n existing.push(child);\n } else {\n index.set(segment, [child]);\n }\n }\n }\n\n // No static children found\n if (index.size === 0) {\n return EMPTY_STATIC_INDEX;\n }\n\n // Freeze arrays for immutability\n // Cast needed: Object.freeze returns readonly[], but we return ReadonlyMap anyway\n if (freeze) {\n for (const [key, arr] of index) {\n index.set(key, Object.freeze(arr) as RouteTree[]);\n }\n }\n\n return index;\n}\n\n// =============================================================================\n// Cache Computation Functions\n// =============================================================================\n\n/**\n * Recursively collects all descendants with absolute paths.\n *\n * @param node - Node to collect from\n * @param result - Array to collect into\n */\nfunction collectAbsoluteDescendants(\n node: RouteTree,\n result: RouteTree[],\n): void {\n for (const child of node.children) {\n if (child.absolute) {\n result.push(child);\n }\n\n collectAbsoluteDescendants(child, result);\n }\n}\n\n/**\n * Computes all absolute descendants recursively.\n *\n * @param node - Node to start from\n * @returns Array of all absolute descendants\n */\nfunction computeAbsoluteDescendants(node: RouteTree): readonly RouteTree[] {\n const result: RouteTree[] = [];\n\n collectAbsoluteDescendants(node, result);\n\n return result;\n}\n\n/**\n * Computes parent segments from root to this node's parent.\n *\n * @param node - Node to compute for\n * @returns Array of parent segments\n */\nfunction computeParentSegments(node: RouteTree): readonly RouteTree[] {\n const segments: RouteTree[] = [];\n let current = node.parent;\n\n while (current?.parser) {\n segments.push(current);\n current = current.parent;\n }\n\n // Reverse to get root -> parent order\n segments.reverse();\n\n return segments;\n}\n\n/**\n * Computes the full dot-notation name for a node.\n * Parent fullName is always computed before children.\n *\n * @param node - Node to compute for\n * @returns Full name (e.g., \"users.profile\")\n */\nfunction computeFullName(node: RouteTree): string {\n if (!node.parent?.name) {\n return node.name;\n }\n\n // Parent fullName is always set before children are processed\n return `${node.parent.fullName}.${node.name}`;\n}\n\n/**\n * Computes static path for routes without parameters.\n *\n * Returns pre-built path string for fast buildPath lookup,\n * or null if the route has any dynamic parameters.\n *\n * @param node - Node to compute for\n * @returns Static path or null\n */\nfunction computeStaticPath(node: RouteTree): string | null {\n const parser = node.parser;\n\n if (!parser) {\n return null;\n }\n\n // If route has any parameters, we can't pre-compute\n if (parser.hasUrlParams || parser.hasQueryParams || parser.hasSpatParam) {\n return null;\n }\n\n // Build the full path from parent segments + this segment\n // Note: parentSegments only contains nodes with parsers (see computeParentSegments)\n let path = \"\";\n\n for (const segment of node.parentSegments) {\n // parentSegments only contains nodes with parsers (see computeParentSegments)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- by design\n const segmentParser = segment.parser!;\n\n // Parent segments with params invalidate static path\n if (\n segmentParser.hasUrlParams ||\n segmentParser.hasQueryParams ||\n segmentParser.hasSpatParam\n ) {\n return null;\n }\n\n path = segment.absolute ? segment.path : path + segment.path;\n }\n\n // Add this node's path\n path = node.absolute ? node.path : path + node.path;\n\n // Normalize double slashes - always apply regex (avoids equivalent mutants)\n return path.replaceAll(/\\/{2,}/g, \"/\");\n}\n\n// =============================================================================\n// Main Computation Function\n// =============================================================================\n\n/**\n * Recursively processes a mutable node into a RouteTree.\n *\n * This creates a new object with all caches computed.\n * Optionally freezes the result for immutability.\n *\n * @param mutable - Mutable node to process\n * @param parent - Already-processed parent node (null for root)\n * @param freeze - Whether to freeze the result\n * @returns RouteTree (frozen if freeze=true)\n */\nfunction processNode(\n mutable: MutableRouteNode,\n parent: RouteTree | null,\n freeze: boolean,\n): RouteTree {\n // Create node object with pre-allocated arrays\n const node = {\n name: mutable.name,\n path: mutable.path,\n absolute: mutable.absolute,\n parser: mutable.parser,\n parent,\n children: [] as RouteTree[],\n nonAbsoluteChildren: [] as RouteTree[],\n absoluteDescendants: [] as RouteTree[],\n childrenByName: new Map<string, RouteTree>(),\n parentSegments: [] as RouteTree[],\n fullName: \"\",\n staticPath: null as string | null,\n paramTypeMap: {} as Record<string, \"url\" | \"query\">,\n staticChildrenByFirstSegment: EMPTY_STATIC_INDEX,\n };\n\n // Compute paramTypeMap from parser (cached to avoid recomputing on every navigation)\n if (mutable.parser) {\n for (const p of mutable.parser.urlParams) {\n node.paramTypeMap[p] = \"url\";\n }\n\n for (const p of mutable.parser.queryParams) {\n node.paramTypeMap[p] = \"query\";\n }\n }\n\n // Compute fullName first (needs parent)\n node.fullName = computeFullName(node as RouteTree);\n\n // Process children and build childrenByName in single pass\n for (const childMutable of mutable.children) {\n const child = processNode(childMutable, node as RouteTree, freeze);\n\n node.children.push(child);\n node.childrenByName.set(child.name, child);\n\n // Build nonAbsoluteChildren inline\n if (!child.absolute) {\n node.nonAbsoluteChildren.push(child);\n }\n }\n\n // Compute absoluteDescendants (recursive collection)\n node.absoluteDescendants = computeAbsoluteDescendants(\n node as RouteTree,\n ) as RouteTree[];\n\n // Compute parentSegments\n node.parentSegments = computeParentSegments(node as RouteTree) as RouteTree[];\n\n // Compute staticPath for fast buildPath lookup\n node.staticPath = computeStaticPath(node as RouteTree);\n\n // Compute static children index for O(1) matching\n node.staticChildrenByFirstSegment = computeStaticChildrenIndex(\n node.nonAbsoluteChildren,\n freeze,\n );\n\n // Freeze only if requested\n if (freeze) {\n Object.freeze(node.children);\n Object.freeze(node.nonAbsoluteChildren);\n Object.freeze(node.absoluteDescendants);\n Object.freeze(node.parentSegments);\n Object.freeze(node.paramTypeMap);\n Object.freeze(node);\n }\n\n return node as RouteTree;\n}\n\n/**\n * Computes all caches and optionally freezes the tree.\n *\n * This is the final step in building a RouteTree.\n * When freeze=true (default), the tree is completely immutable.\n *\n * @param mutableRoot - Mutable root node\n * @param freeze - Whether to freeze the result (default: true)\n * @returns RouteTree (frozen if freeze=true)\n */\nexport function computeCaches(\n mutableRoot: MutableRouteNode,\n freeze = true,\n): RouteTree {\n return processNode(mutableRoot, null, freeze);\n}\n","// packages/route-node/modules/builder/sortTree.ts\n\n/**\n * Tree Sorting.\n *\n * Sorts route children by routing priority.\n *\n * @module builder/sortTree\n */\n\nimport type { MutableRouteNode } from \"./buildTree\";\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Removes trailing slash from path, preserving root \"/\".\n */\nfunction removeTrailingSlash(path: string): string {\n return path.endsWith(\"/\") && path.length > 1 ? path.slice(0, -1) : path;\n}\n\n/**\n * Normalizes path for comparison by removing query params and trailing slash.\n * Also removes route parameters (e.g., `<id>`) for comparison purposes.\n */\nfunction normalizePath(path: string): string {\n // Remove route parameters (e.g., <id>, <userId>)\n // Note: Angle bracket syntax is for internal path representation,\n // not typically used directly in route definitions\n let withoutParams = \"\";\n let depth = 0;\n\n for (const char of path) {\n if (char === \"<\") {\n depth++;\n } else if (char === \">\") {\n depth--;\n } else if (depth === 0) {\n withoutParams += char;\n }\n }\n\n const withoutQuery = withoutParams.split(\"?\")[0];\n\n return removeTrailingSlash(withoutQuery);\n}\n\n// =============================================================================\n// Sorting Implementation\n// =============================================================================\n\n/**\n * Pre-computed data for sorting comparison.\n */\ninterface PrecomputedSortData {\n readonly normalizedPath: string;\n readonly segmentCount: number;\n readonly lastSegmentLength: number;\n readonly originalIndex: number;\n}\n\n/**\n * Sorts children by routing priority.\n *\n * Priority (highest to lowest):\n * 1. Routes with more path segments\n * 2. Routes without splat parameters\n * 3. Routes with fewer URL parameters\n * 4. Routes with longer last segment\n * 5. Original definition order (stable sort)\n *\n * @param children - Array to sort (MUTATED in place)\n */\nfunction sortChildren(children: MutableRouteNode[]): void {\n if (children.length <= 1) {\n return;\n }\n\n // Pre-compute all derived data O(n)\n const precomputed = new Map<MutableRouteNode, PrecomputedSortData>();\n\n for (const [i, child] of children.entries()) {\n const normalizedPath = normalizePath(child.path);\n const segments = normalizedPath.split(\"/\");\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastSegment = segments.at(-1)!;\n\n precomputed.set(child, {\n normalizedPath,\n segmentCount: segments.length - 1,\n lastSegmentLength: lastSegment.length,\n originalIndex: i,\n });\n }\n\n // Sort using pre-computed data O(n log n)\n children.sort((left, right) => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const l = precomputed.get(left)!;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const r = precomputed.get(right)!;\n\n // \"/\" always sorts last\n if (l.normalizedPath === \"/\") {\n return 1;\n }\n if (r.normalizedPath === \"/\") {\n return -1;\n }\n\n // Splat params sort last\n // All children have parsers by design (only empty root lacks parser)\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n if (left.parser!.hasSpatParam) {\n return 1;\n }\n if (right.parser!.hasSpatParam) {\n return -1;\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n\n // More segments = higher priority\n if (l.segmentCount < r.segmentCount) {\n return 1;\n }\n if (l.segmentCount > r.segmentCount) {\n return -1;\n }\n\n // Same segments: fewer URL params = higher priority\n // All children have parsers by design (only empty root lacks parser)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const leftParamsCount = left.parser!.urlParams.length;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const rightParamsCount = right.parser!.urlParams.length;\n\n if (leftParamsCount < rightParamsCount) {\n return -1;\n }\n if (leftParamsCount > rightParamsCount) {\n return 1;\n }\n\n // Same params: longer last segment = higher priority\n if (l.lastSegmentLength < r.lastSegmentLength) {\n return 1;\n }\n if (l.lastSegmentLength > r.lastSegmentLength) {\n return -1;\n }\n\n // Preserve definition order (stable sort fallback)\n return l.originalIndex - r.originalIndex;\n });\n}\n\n/**\n * Recursively sorts all children in the tree.\n *\n * @param node - Root node of the tree\n */\nexport function sortTree(node: MutableRouteNode): void {\n // Sort this node's children\n sortChildren(node.children);\n\n // Recursively sort descendants\n for (const child of node.children) {\n sortTree(child);\n }\n}\n","// packages/route-node/modules/validation/errors.ts\n\n/**\n * Custom error types for route-node package.\n *\n * Provides structured error handling with specific error types\n * for different failure scenarios.\n *\n * @module errors\n */\n\n/**\n * Base error class for all route-node errors.\n *\n * All route-node specific errors inherit from this class,\n * allowing for unified error handling.\n *\n * @example\n * ```typescript\n * try {\n * node.add(invalidRoute);\n * } catch (error) {\n * if (error instanceof RouteNodeError) {\n * console.error(\"Route configuration error:\", error.message);\n * }\n * }\n * ```\n */\nexport class RouteNodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"RouteNodeError\";\n // Maintains proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Error thrown when attempting to add a route with a duplicate name or path.\n *\n * @example\n * ```typescript\n * // Throws DuplicateRouteError: Alias \"home\" is already defined in route node\n * node.add({ name: \"home\", path: \"/\" });\n * node.add({ name: \"home\", path: \"/home\" }); // Duplicate name!\n * ```\n */\nexport class DuplicateRouteError extends RouteNodeError {\n /** The duplicate name or path that caused the error */\n public readonly duplicateValue: string;\n /** Whether the duplicate is a name (\"name\") or path (\"path\") */\n public readonly duplicateType: \"name\" | \"path\";\n\n constructor(\n message: string,\n duplicateValue: string,\n duplicateType: \"name\" | \"path\",\n ) {\n super(message);\n this.name = \"DuplicateRouteError\";\n this.duplicateValue = duplicateValue;\n this.duplicateType = duplicateType;\n }\n}\n\n/**\n * Error thrown when a route definition is invalid.\n *\n * Common causes:\n * - Missing required name or path property\n * - Invalid route type (not an object or RouteNode)\n * - Absolute path with parameterized parents\n *\n * @example\n * ```typescript\n * // Throws InvalidRouteError: RouteNode.add() expects routes to have a name and a path defined.\n * node.add({ name: \"incomplete\" }); // Missing path!\n * ```\n */\nexport class InvalidRouteError extends RouteNodeError {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidRouteError\";\n }\n}\n\n/**\n * Error thrown when a referenced route cannot be found.\n *\n * @example\n * ```typescript\n * // Throws RouteNotFoundError: [route-node][buildPath] 'nonexistent' is not defined\n * node.buildPath(\"nonexistent\", {});\n * ```\n */\nexport class RouteNotFoundError extends RouteNodeError {\n /** The route name that was not found */\n public readonly routeName: string;\n\n constructor(message: string, routeName: string) {\n super(message);\n this.name = \"RouteNotFoundError\";\n this.routeName = routeName;\n }\n}\n\n/**\n * Error thrown when a parent route cannot be found for nested route addition.\n *\n * @example\n * ```typescript\n * // Throws ParentNotFoundError when parent \"users\" doesn't exist\n * node.add({ name: \"users.profile\", path: \"/profile\" });\n * ```\n */\nexport class ParentNotFoundError extends RouteNodeError {\n /** The route name whose parent was not found */\n public readonly routeName: string;\n\n constructor(message: string, routeName: string) {\n super(message);\n this.name = \"ParentNotFoundError\";\n this.routeName = routeName;\n }\n}\n","// packages/route-node/modules/builder/validateRoutes.ts\n\n/**\n * Route Validation.\n *\n * Validates route definitions before building the tree.\n *\n * @module builder/validateRoutes\n */\n\nimport { DuplicateRouteError, InvalidRouteError } from \"../validation/errors\";\n\nimport type { RouteDefinition } from \"../types\";\n\n// =============================================================================\n// Validation Functions\n// =============================================================================\n\n/**\n * Validates that a route definition has required properties.\n *\n * @param route - Route definition to validate\n * @throws {InvalidRouteError} If name or path is missing\n */\nfunction validateRouteDefinition(route: RouteDefinition): void {\n if (!route.name || typeof route.name !== \"string\") {\n throw new InvalidRouteError(\n \"Route definition must have a 'name' property of type string.\",\n );\n }\n\n if (typeof route.path !== \"string\") {\n throw new InvalidRouteError(\n `Route \"${route.name}\" must have a 'path' property of type string.`,\n );\n }\n}\n\n/**\n * Checks for duplicate route name and throws if found.\n */\nfunction checkDuplicateName(fullName: string, seenNames: Set<string>): void {\n if (seenNames.has(fullName)) {\n throw new DuplicateRouteError(\n `Duplicate route name \"${fullName}\" found.`,\n fullName,\n \"name\",\n );\n }\n\n seenNames.add(fullName);\n}\n\n/**\n * Checks for duplicate path at the same parent level.\n */\nfunction checkDuplicatePath(\n path: string,\n parentPrefix: string,\n seenPathsByParent: Map<string, Set<string>>,\n): void {\n const pathsAtLevel = seenPathsByParent.get(parentPrefix);\n\n if (pathsAtLevel?.has(path)) {\n throw new DuplicateRouteError(\n `Path \"${path}\" is already defined`,\n path,\n \"path\",\n );\n }\n\n if (pathsAtLevel) {\n pathsAtLevel.add(path);\n } else {\n seenPathsByParent.set(parentPrefix, new Set([path]));\n }\n}\n\n/**\n * Validates all route definitions in a single pass.\n *\n * Optimized version that flattens and validates in one traversal.\n *\n * Checks:\n * - Each route has name and path\n * - No duplicate names at the same level\n * - No duplicate paths at the same parent level (considering dot-notation)\n *\n * @param routes - Routes to validate\n * @throws {InvalidRouteError} If any route is invalid\n * @throws {DuplicateRouteError} If duplicate names or paths are found\n */\nexport function validateRoutes(routes: readonly RouteDefinition[]): void {\n const seenNames = new Set<string>();\n const seenPathsByParent = new Map<string, Set<string>>();\n\n // Use stack-based iteration instead of recursion (avoids call stack overhead)\n const stack: { routes: readonly RouteDefinition[]; parentPrefix: string }[] =\n [{ routes, parentPrefix: \"\" }];\n\n while (stack.length > 0) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { routes: currentRoutes, parentPrefix } = stack.pop()!;\n\n for (const route of currentRoutes) {\n validateRouteDefinition(route);\n\n // Compute full name for nested routes\n const fullName = parentPrefix\n ? `${parentPrefix}.${route.name}`\n : route.name;\n\n checkDuplicateName(fullName, seenNames);\n checkDuplicatePath(route.path, parentPrefix, seenPathsByParent);\n\n // Push children to stack (if any)\n if (route.children && route.children.length > 0) {\n stack.push({ routes: route.children, parentPrefix: fullName });\n }\n }\n }\n}\n","// packages/route-node/modules/builder/createRouteTree.ts\n\n/**\n * Route Tree Builder.\n *\n * Creates immutable RouteTree from route definitions.\n *\n * @module builder/createRouteTree\n */\n\nimport { buildTree } from \"./buildTree\";\nimport { computeCaches } from \"./computeCaches\";\nimport { sortTree } from \"./sortTree\";\nimport { validateRoutes } from \"./validateRoutes\";\n\nimport type {\n RouteDefinition,\n RouteTree,\n RouteTreeBuilder,\n TreeBuildOptions,\n} from \"../types\";\n\n// =============================================================================\n// Builder Implementation\n// =============================================================================\n\n/**\n * Creates a RouteTreeBuilder for constructing route trees.\n *\n * @param name - Root node name (typically empty string)\n * @param path - Root node path (typically empty string)\n * @returns RouteTreeBuilder instance\n *\n * @example\n * ```typescript\n * const tree = createRouteTreeBuilder(\"\", \"\")\n * .add({ name: \"users\", path: \"/users\" })\n * .add({ name: \"users.profile\", path: \"/:id\" })\n * .build();\n * ```\n */\nexport function createRouteTreeBuilder(\n name: string,\n path: string,\n): RouteTreeBuilder {\n const routes: RouteDefinition[] = [];\n\n return {\n add(route: RouteDefinition): RouteTreeBuilder {\n routes.push(route);\n\n return this;\n },\n\n addMany(newRoutes: readonly RouteDefinition[]): RouteTreeBuilder {\n routes.push(...newRoutes);\n\n return this;\n },\n\n build(options?: TreeBuildOptions): RouteTree {\n // Step 1: Validate all routes (unless skipped)\n if (!options?.skipValidation) {\n validateRoutes(routes);\n }\n\n // Step 2: Build mutable tree structure\n const mutableTree = buildTree(name, path, routes);\n\n // Step 3: Sort all children (unless skipped)\n if (!options?.skipSort) {\n sortTree(mutableTree);\n }\n\n // Step 4: Compute all caches and optionally freeze\n const freeze = !options?.skipFreeze;\n\n return computeCaches(mutableTree, freeze);\n },\n };\n}\n\n// =============================================================================\n// Convenience Function\n// =============================================================================\n\n/**\n * Creates a RouteTree directly from route definitions.\n *\n * Convenience wrapper around createRouteTreeBuilder().\n *\n * @param name - Root node name (typically empty string)\n * @param path - Root node path (typically empty string)\n * @param routes - Route definitions to add\n * @param options - Build options (e.g., skipValidation)\n * @returns Immutable RouteTree\n *\n * @example\n * ```typescript\n * const tree = createRouteTree(\"\", \"\", [\n * { name: \"users\", path: \"/users\" },\n * { name: \"users.profile\", path: \"/:id\" },\n * ]);\n *\n * // Skip validation (when routes are pre-validated)\n * const tree = createRouteTree(\"\", \"\", routes, { skipValidation: true });\n * ```\n */\nexport function createRouteTree(\n name: string,\n path: string,\n routes: readonly RouteDefinition[],\n options?: TreeBuildOptions,\n): RouteTree {\n return createRouteTreeBuilder(name, path).addMany(routes).build(options);\n}\n","// packages/route-node/modules/operations/match.ts\n\n/**\n * Path Matching Operations.\n *\n * Pure functions for matching URL paths against route trees.\n *\n * @module operations/match\n */\n\nimport { omit, parseInto } from \"search-params\";\n\nimport type {\n MatchOptions,\n MatchResult,\n PathParser,\n RouteParams,\n RouteTree,\n} from \"../types\";\nimport type { MatchConfig, MatchResponse } from \"./types\";\n\n// =============================================================================\n// Pre-compiled Patterns & Cached Objects\n// =============================================================================\n\nconst SLASH_CHILD_PATTERN = /^\\/(\\?|$)/;\nconst TRAILING_SLASH = /\\/$/;\nconst LEADING_SLASH_QUERY = /^\\/\\?/;\n\n/**\n * Extracts the first segment from a runtime URL path.\n *\n * @example\n * extractFirstPathSegment(\"/users/123\") → \"users\"\n * extractFirstPathSegment(\"users/123\") → \"users\"\n * extractFirstPathSegment(\"/users?tab=1\") → \"users\"\n * extractFirstPathSegment(\"/\") → \"\"\n *\n * @param path - Runtime path (e.g., \"/users/123\")\n * @returns First segment (without leading slash, query string stripped)\n */\nfunction extractFirstPathSegment(path: string): string {\n // Runtime paths always start with \"/\" (see calculateRemainingPath)\n // Find end of segment: next \"/\" or \"?\" (whichever comes first)\n let end = path.indexOf(\"/\", 1);\n const queryPos = path.indexOf(\"?\", 1);\n\n if (queryPos !== -1 && (end === -1 || queryPos < end)) {\n end = queryPos;\n }\n\n const segment = end === -1 ? path.slice(1) : path.slice(1, end);\n\n // Normalize to lowercase for case-insensitive index lookup\n return segment.toLowerCase();\n}\n\n/**\n * Checks if a route path has a dynamic first segment (starts with : or *).\n * Used to skip static routes during fallback matching.\n */\nfunction hasDynamicFirstSegment(path: string): boolean {\n const start = path.startsWith(\"/\") ? 1 : 0;\n const firstChar = path.charAt(start);\n\n return (\n firstChar === \":\" ||\n firstChar === \"*\" ||\n firstChar === \"\" ||\n path.charAt(start) === \"(\"\n );\n}\n\n// Pre-computed default options objects (avoid allocation on every match)\nconst DEFAULT_FULL_TEST_OPTIONS = {\n caseSensitive: false,\n strictTrailingSlash: false,\n};\nconst DEFAULT_FULL_TEST_OPTIONS_STRICT = {\n caseSensitive: false,\n strictTrailingSlash: true,\n};\nconst DEFAULT_FULL_TEST_OPTIONS_CASE_SENSITIVE = {\n caseSensitive: true,\n strictTrailingSlash: false,\n};\nconst DEFAULT_FULL_TEST_OPTIONS_CASE_SENSITIVE_STRICT = {\n caseSensitive: true,\n strictTrailingSlash: true,\n};\nconst DEFAULT_PARTIAL_TEST_OPTIONS = { caseSensitive: false, delimited: true };\nconst DEFAULT_PARTIAL_TEST_OPTIONS_CASE_SENSITIVE = {\n caseSensitive: true,\n delimited: true,\n};\nconst DEFAULT_PARTIAL_TEST_OPTIONS_WEAK = {\n caseSensitive: false,\n delimited: false,\n};\nconst DEFAULT_PARTIAL_TEST_OPTIONS_CASE_SENSITIVE_WEAK = {\n caseSensitive: true,\n delimited: false,\n};\nconst DEFAULT_BUILD_OPTIONS = { ignoreSearch: true };\n\n// Cached default config (used when no options provided)\nconst DEFAULT_CONFIG: MatchConfig = {\n queryParamsMode: \"default\",\n strictTrailingSlash: false,\n strongMatching: true,\n caseSensitive: false,\n queryParams: undefined,\n urlParamsEncoding: undefined,\n fullTestOptions: DEFAULT_FULL_TEST_OPTIONS,\n partialTestOptions: DEFAULT_PARTIAL_TEST_OPTIONS,\n buildOptions: DEFAULT_BUILD_OPTIONS,\n};\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Matches a URL path and returns raw segments.\n *\n * Returns raw segments and params without building the state name.\n * Use this when you need to build the state yourself (e.g., in real-router).\n *\n * @param tree - Route tree to match against\n * @param path - URL path to match\n * @param options - Matching options\n * @returns Match result with segments and params, or null if no match\n */\nexport function matchSegments(\n tree: RouteTree,\n path: string,\n options: MatchOptions = {},\n): MatchResult | null {\n let normalizedPath = path;\n\n if (normalizedPath === \"\" && !options.strictTrailingSlash) {\n normalizedPath = \"/\";\n }\n\n const match = getSegmentsMatchingPath(tree, normalizedPath, options);\n\n if (!match) {\n return null;\n }\n\n const matchedSegments = match.segments;\n\n if (matchedSegments[0]?.absolute) {\n const firstSegmentParents = matchedSegments[0].parentSegments;\n\n // Use for-loop instead of spread (faster for small arrays)\n\n for (let i = firstSegmentParents.length - 1; i >= 0; i--) {\n matchedSegments.unshift(firstSegmentParents[i]);\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const lastSegment = matchedSegments.at(-1)!;\n const lastSegmentSlashChild = findSlashChild(lastSegment);\n\n if (lastSegmentSlashChild) {\n matchedSegments.push(lastSegmentSlashChild);\n }\n\n return {\n segments: matchedSegments,\n params: match.params,\n };\n}\n\n// =============================================================================\n// Internal: Tree Traversal\n// =============================================================================\n\n/**\n * Finds a slash child node (route that matches \"/\").\n */\nfunction findSlashChild(node: RouteTree): RouteTree | undefined {\n return node.nonAbsoluteChildren.find(\n (child) => child.parser && SLASH_CHILD_PATTERN.test(child.parser.path),\n );\n}\n\n/**\n * Gets a cached or creates a match config for the given options.\n * Uses DEFAULT_CONFIG for empty options, otherwise creates new config.\n *\n * Note: Benchmarks show config creation overhead is <1.5% for deep paths,\n * so we prioritize code simplicity over complex caching logic.\n */\nfunction getMatchConfig(options: MatchOptions): MatchConfig {\n // Fast path: no options - use default config\n if (\n options.queryParamsMode === undefined &&\n options.strictTrailingSlash === undefined &&\n options.strongMatching === undefined &&\n options.caseSensitive === undefined &&\n options.queryParams === undefined &&\n options.urlParamsEncoding === undefined &&\n options.trailingSlashMode === undefined\n ) {\n return DEFAULT_CONFIG;\n }\n\n // trailingSlashMode doesn't affect matching, only buildPath\n // If it's the only option set, we can use DEFAULT_CONFIG\n if (\n options.trailingSlashMode !== undefined &&\n options.queryParamsMode === undefined &&\n options.strictTrailingSlash === undefined &&\n options.strongMatching === undefined &&\n options.caseSensitive === undefined &&\n options.queryParams === undefined &&\n options.urlParamsEncoding === undefined\n ) {\n return DEFAULT_CONFIG;\n }\n\n return createMatchConfig(options);\n}\n\n/**\n * Gets segments matching the given path.\n */\nfunction getSegmentsMatchingPath(\n tree: RouteTree,\n path: string,\n options: MatchOptions,\n): MatchResponse | null {\n // Determine starting nodes (optimized: avoid spread for single node)\n const startingNodes: RouteTree[] = [];\n\n /* eslint-disable @typescript-eslint/prefer-for-of */\n if (tree.parser) {\n // Tree has a parser - use it directly\n startingNodes.push(tree);\n\n // Use for-loop instead of spread (1.36x faster)\n for (let i = 0; i < tree.absoluteDescendants.length; i++) {\n startingNodes.push(tree.absoluteDescendants[i]);\n }\n } else {\n // Use children as starting nodes\n for (const topNode of tree.children) {\n startingNodes.push(topNode);\n\n // Use for-loop instead of spread (1.36x faster)\n for (let i = 0; i < topNode.absoluteDescendants.length; i++) {\n startingNodes.push(topNode.absoluteDescendants[i]);\n }\n }\n }\n /* eslint-enable @typescript-eslint/prefer-for-of */\n\n const currentMatch: MatchResponse = {\n segments: [],\n params: {},\n };\n\n // Use cached config when possible (most common case)\n const config = getMatchConfig(options);\n\n // matchChildren only processes route children, never returns root-only matches\n return matchChildren(startingNodes, path, currentMatch, config);\n}\n\n// =============================================================================\n// Internal: Path Matching\n// =============================================================================\n\n/**\n * Recursively matches a path segment against route tree nodes.\n * Used for top-level matching where no static index is available.\n */\nfunction matchChildren(\n nodes: readonly RouteTree[],\n pathSegment: string,\n currentMatch: MatchResponse,\n config: MatchConfig,\n consumedBefore?: string,\n): MatchResponse | null {\n const isRoot = nodes.length === 1 && nodes[0].name === \"\";\n\n for (const child of nodes) {\n const result = tryMatchChild(\n child,\n pathSegment,\n currentMatch,\n config,\n isRoot,\n consumedBefore,\n );\n\n if (result !== undefined) {\n return result;\n }\n }\n\n return null;\n}\n\n/**\n * Tries to match any child from the list against the path segment.\n *\n * @returns First successful match or null if no match found\n */\nfunction tryMatchAnyChild(\n children: readonly RouteTree[],\n pathSegment: string,\n currentMatch: MatchResponse,\n config: MatchConfig,\n consumedBefore: string | undefined,\n skipStatic: boolean,\n): MatchResponse | null {\n for (const child of children) {\n if (skipStatic && !hasDynamicFirstSegment(child.path)) {\n continue;\n }\n\n const result = tryMatchChild(\n child,\n pathSegment,\n currentMatch,\n config,\n false, // isRoot = false for indexed matching\n consumedBefore,\n );\n\n if (result !== undefined) {\n return result;\n }\n }\n\n return null;\n}\n\n/**\n * Matches path segment against a parent's children using static index.\n *\n * Uses O(1) lookup for routes with static first segments,\n * then falls back to linear search for dynamic-only routes.\n *\n * @param parent - Parent node whose children to match against\n * @param pathSegment - Remaining path to match\n * @param currentMatch - Accumulated match result\n * @param config - Match configuration\n * @param consumedBefore - Previously consumed path (for \"/\" handling)\n * @returns Match result or null\n */\nfunction matchChildrenIndexed(\n parent: RouteTree,\n pathSegment: string,\n currentMatch: MatchResponse,\n config: MatchConfig,\n consumedBefore?: string,\n): MatchResponse | null {\n const staticIndex = parent.staticChildrenByFirstSegment;\n const children = parent.nonAbsoluteChildren;\n\n // Fast path: no static index, use linear search\n if (staticIndex.size === 0) {\n return tryMatchAnyChild(\n children,\n pathSegment,\n currentMatch,\n config,\n consumedBefore,\n false,\n );\n }\n\n // 1. Try static index first (O(1) lookup)\n const firstSegment = extractFirstPathSegment(pathSegment);\n const candidates = staticIndex.get(firstSegment);\n\n if (candidates) {\n const result = tryMatchAnyChild(\n candidates,\n pathSegment,\n currentMatch,\n config,\n consumedBefore,\n false,\n );\n\n if (result !== null) {\n return result;\n }\n }\n\n // 2. Fall back to dynamic routes only (routes not in static index)\n return tryMatchAnyChild(\n children,\n pathSegment,\n currentMatch,\n config,\n consumedBefore,\n true, // skipStatic = true\n );\n}\n\n/**\n * Attempts to match a single child node against the path segment.\n *\n * @returns Match result, null for no match, or undefined to continue iteration\n */\nfunction tryMatchChild(\n child: RouteTree,\n pathSegment: string,\n currentMatch: MatchResponse,\n config: MatchConfig,\n isRoot: boolean,\n consumedBefore?: string,\n): MatchResponse | null | undefined {\n // All route children have parsers by design (only empty root lacks parser)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const parser = child.parser!;\n\n // Handle duplicate \"/\" case\n const segment = resolveSegment(pathSegment, child.path, consumedBefore);\n\n // Try to match\n const match = tryMatchNode(child, parser, segment, config);\n\n if (!match) {\n return undefined;\n }\n\n // Process successful match\n const isLeafNode = child.children.length === 0;\n const consumedPath = buildConsumedPath(parser, match, config, isLeafNode);\n const remainingPath = calculateRemainingPath(\n segment,\n consumedPath,\n config,\n isLeafNode,\n isRoot,\n parser,\n );\n\n // Update accumulated match\n currentMatch.segments.push(child);\n Object.assign(currentMatch.params, match as RouteParams);\n\n return resolveMatchResult(\n child,\n currentMatch,\n remainingPath,\n config,\n isRoot,\n consumedPath,\n );\n}\n\n/**\n * Resolves the segment to match, handling duplicate \"/\" case.\n */\nfunction resolveSegment(\n pathSegment: string,\n childPath: string,\n consumedBefore?: string,\n): string {\n return consumedBefore === \"/\" && childPath === \"/\"\n ? `/${pathSegment}`\n : pathSegment;\n}\n\n/**\n * Resolves the final match result after a successful node match.\n */\nfunction resolveMatchResult(\n child: RouteTree,\n currentMatch: MatchResponse,\n remainingPath: string,\n config: MatchConfig,\n isRoot: boolean,\n consumedPath: string,\n): MatchResponse | null {\n // Check if fully matched\n if (!isRoot && remainingPath.length === 0) {\n return currentMatch;\n }\n\n // Check for unmatched query params in non-strict mode\n if (hasOnlyQueryParamsRemaining(remainingPath, config, isRoot)) {\n return handleRemainingQueryParams(currentMatch, remainingPath);\n }\n\n // Continue matching on children using static index\n if (child.nonAbsoluteChildren.length === 0) {\n return null;\n }\n\n return matchChildrenIndexed(\n child,\n remainingPath,\n currentMatch,\n config,\n consumedPath,\n );\n}\n\n/**\n * Checks if only query params remain in the path.\n */\nfunction hasOnlyQueryParamsRemaining(\n remainingPath: string,\n config: MatchConfig,\n isRoot: boolean,\n): boolean {\n return (\n !isRoot &&\n config.queryParamsMode !== \"strict\" &&\n remainingPath.startsWith(\"?\")\n );\n}\n\n/**\n * Creates match config from options with defaults.\n * Optimized to reuse pre-computed option objects when possible.\n */\nfunction createMatchConfig(options: MatchOptions): MatchConfig {\n const queryParamsMode = options.queryParamsMode ?? \"default\";\n const strictTrailingSlash = options.strictTrailingSlash ?? false;\n const strongMatching = options.strongMatching ?? true;\n const caseSensitive = options.caseSensitive ?? false;\n const { queryParams, urlParamsEncoding } = options;\n\n // Determine if we can use pre-computed options (no custom queryParams or urlParamsEncoding)\n const canUseCachedOptions =\n queryParams === undefined && urlParamsEncoding === undefined;\n\n // Get fullTestOptions - use cached or create new\n const fullTestOptions = canUseCachedOptions\n ? getFullTestOptions(caseSensitive, strictTrailingSlash)\n : { caseSensitive, strictTrailingSlash, queryParams, urlParamsEncoding };\n\n // Get partialTestOptions - use cached or create new\n const partialTestOptions = canUseCachedOptions\n ? getPartialTestOptions(caseSensitive, strongMatching)\n : {\n caseSensitive,\n delimited: strongMatching,\n queryParams,\n urlParamsEncoding,\n };\n\n // Direct assignment eliminates conditional mutants\n // Parser handles undefined urlParamsEncoding the same as missing key\n const buildOptions: Record<string, unknown> = {\n ignoreSearch: true,\n urlParamsEncoding,\n };\n\n return {\n queryParamsMode,\n strictTrailingSlash,\n strongMatching,\n caseSensitive,\n queryParams,\n urlParamsEncoding,\n fullTestOptions,\n partialTestOptions,\n buildOptions,\n };\n}\n\n/**\n * Returns pre-computed fullTestOptions for given flags.\n */\nfunction getFullTestOptions(\n caseSensitive: boolean,\n strictTrailingSlash: boolean,\n): Record<string, unknown> {\n if (caseSensitive) {\n return strictTrailingSlash\n ? DEFAULT_FULL_TEST_OPTIONS_CASE_SENSITIVE_STRICT\n : DEFAULT_FULL_TEST_OPTIONS_CASE_SENSITIVE;\n }\n\n return strictTrailingSlash\n ? DEFAULT_FULL_TEST_OPTIONS_STRICT\n : DEFAULT_FULL_TEST_OPTIONS;\n}\n\n/**\n * Returns pre-computed partialTestOptions for given flags.\n */\nfunction getPartialTestOptions(\n caseSensitive: boolean,\n strongMatching: boolean,\n): Record<string, unknown> {\n if (caseSensitive) {\n return strongMatching\n ? DEFAULT_PARTIAL_TEST_OPTIONS_CASE_SENSITIVE\n : DEFAULT_PARTIAL_TEST_OPTIONS_CASE_SENSITIVE_WEAK;\n }\n\n return strongMatching\n ? DEFAULT_PARTIAL_TEST_OPTIONS\n : DEFAULT_PARTIAL_TEST_OPTIONS_WEAK;\n}\n\n/**\n * Attempts to match a node against a path segment.\n */\nfunction tryMatchNode(\n node: RouteTree,\n parser: PathParser,\n segment: string,\n config: MatchConfig,\n): Record<string, unknown> | null {\n // Try full match for leaf nodes\n if (node.children.length === 0) {\n const fullMatch = parser.test(segment, config.fullTestOptions);\n\n if (fullMatch) {\n return fullMatch;\n }\n }\n\n // Try partial match\n return parser.partialTest(segment, config.partialTestOptions);\n}\n\n/**\n * Calculates the path consumed by a match.\n */\nfunction buildConsumedPath(\n parser: PathParser,\n match: Record<string, unknown>,\n config: MatchConfig,\n isLeafNode: boolean,\n): string {\n let consumedPath = parser.build(match, config.buildOptions);\n\n if (!config.strictTrailingSlash && isLeafNode) {\n consumedPath = consumedPath.replace(TRAILING_SLASH, \"\");\n }\n\n return consumedPath;\n}\n\n/**\n * Calculates remaining path after consuming matched portion.\n */\nfunction calculateRemainingPath(\n segment: string,\n consumedPath: string,\n config: MatchConfig,\n isLeafNode: boolean,\n isRoot: boolean,\n parser: PathParser,\n): string {\n // After successful match, consumedPath is always a prefix of segment (case-insensitive)\n // because consumedPath is built from the same params extracted from segment\n let remainingPath = segment.slice(consumedPath.length);\n\n if (!config.strictTrailingSlash && isLeafNode) {\n remainingPath = remainingPath.replace(LEADING_SLASH_QUERY, \"?\");\n }\n\n const { querystring } = omit(\n getSearch(segment.slice(consumedPath.length)),\n parser.queryParams,\n config.queryParams,\n );\n\n remainingPath =\n getPath(remainingPath) + (querystring ? `?${querystring}` : \"\");\n\n if (\n !config.strictTrailingSlash &&\n !isRoot &&\n remainingPath === \"/\" &&\n !consumedPath.endsWith(\"/\")\n ) {\n remainingPath = \"\";\n }\n\n return remainingPath;\n}\n\n/**\n * Handles remaining query params in non-strict mode.\n * Optimized with fast path for empty query strings and direct assignment.\n */\nfunction handleRemainingQueryParams(\n currentMatch: MatchResponse,\n remainingPath: string,\n): MatchResponse {\n // Direct assignment: parse directly into params object\n // Avoids intermediate object creation and Object.assign overhead\n // Note: remainingPath always has format \"?key=value\" (length > 1)\n // because calculateRemainingPath only adds \"?\" when querystring is non-empty\n parseInto(remainingPath.slice(1), currentMatch.params);\n\n return currentMatch;\n}\n\n// =============================================================================\n// Utility Functions\n// =============================================================================\n\n/**\n * Extracts the path portion before query string.\n * Uses indexOf instead of split for better performance.\n */\nfunction getPath(path: string): string {\n const idx = path.indexOf(\"?\");\n\n return idx === -1 ? path : path.slice(0, idx);\n}\n\n/**\n * Extracts the query string portion from path.\n * Uses indexOf instead of split for better performance.\n */\nfunction getSearch(path: string): string {\n const idx = path.indexOf(\"?\");\n\n return idx === -1 ? \"\" : path.slice(idx + 1);\n}\n","// packages/route-node/modules/operations/query.ts\n\n/**\n * Route Query Operations.\n *\n * Pure functions for querying route information from the tree.\n *\n * @module operations/query\n */\n\nimport type { RouteTree } from \"../types\";\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Finds route nodes by dot-notation name.\n *\n * Returns an array of segments from root to the target node.\n * All returned segments have parsers (root included only if it has parser).\n * Uses childrenByName Map for O(1) lookup at each level.\n *\n * @param tree - Route tree to search in\n * @param routeName - Dot-notation route name (e.g., \"users.profile\")\n * @returns Array of route segments or null if not found\n *\n * @example\n * ```typescript\n * const segments = getSegmentsByName(tree, \"users.profile\");\n * // → [usersNode, profileNode]\n * ```\n */\nexport function getSegmentsByName(\n tree: RouteTree,\n routeName: string,\n): readonly RouteTree[] | null {\n const segments: RouteTree[] = [];\n\n // Optimize: avoid split() allocation for simple names without dots\n const names = routeName.includes(\".\") ? routeName.split(\".\") : [routeName];\n\n // Handle root with parser (include it as first segment)\n if (tree.parser) {\n segments.push(tree);\n }\n\n // Navigate through the tree using O(1) Map lookups\n let currentNode: RouteTree = tree;\n\n for (const name of names) {\n const segment = currentNode.childrenByName.get(name);\n\n if (!segment) {\n return null;\n }\n\n segments.push(segment);\n currentNode = segment;\n }\n\n return segments;\n}\n\n/**\n * Checks if a route exists in the tree by dot-notation name.\n * More efficient than getSegmentsByName when only existence check is needed.\n *\n * Avoids:\n * - Array allocation\n * - Array push operations\n *\n * @param tree - Route tree to search in\n * @param routeName - Dot-notation route name (e.g., \"users.profile\")\n * @returns true if route exists, false otherwise\n *\n * @example\n * ```typescript\n * const exists = hasSegmentsByName(tree, \"users.profile\");\n * // → true\n * ```\n */\nexport function hasSegmentsByName(tree: RouteTree, routeName: string): boolean {\n // Optimize: avoid split() allocation for simple names without dots\n const names = routeName.includes(\".\") ? routeName.split(\".\") : [routeName];\n\n // Navigate through the tree using O(1) Map lookups\n let currentNode: RouteTree = tree;\n\n for (const name of names) {\n const segment = currentNode.childrenByName.get(name);\n\n if (!segment) {\n return false;\n }\n\n currentNode = segment;\n }\n\n return true;\n}\n","// packages/route-node/modules/operations/build.ts\n\n/**\n * Path Building Operations.\n *\n * Pure functions for building URL paths from route names and parameters.\n *\n * @module operations/build\n */\n\nimport { build as buildQueryString } from \"search-params\";\n\nimport { getSegmentsByName } from \"./query\";\nimport { RouteNotFoundError } from \"../validation/errors\";\n\nimport type {\n BuildOptions,\n RouteParams,\n RouteTree,\n TrailingSlashMode,\n} from \"../types\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/**\n * Shared empty array for lazy allocation optimization.\n * Avoids creating new empty arrays for routes without params.\n */\nconst EMPTY_ARRAY: readonly string[] = Object.freeze([]);\n\n// =============================================================================\n// Helpers\n// =============================================================================\n\n/**\n * Checks if object has any own enumerable keys.\n * More efficient than Object.keys().length > 0 (avoids array allocation).\n */\nfunction hasOwnKeys(obj: object): boolean {\n for (const key in obj) {\n if (Object.hasOwn(obj, key)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Checks if BuildOptions contains any non-default values.\n * Used to determine if fast path can be taken.\n *\n * Default values that allow fast path:\n * - trailingSlashMode: \"default\" or undefined\n * - queryParamsMode: \"default\" or undefined\n * - queryParams: undefined\n * - urlParamsEncoding: \"default\" or undefined\n */\nfunction hasNonDefaultOptions(options: BuildOptions): boolean {\n return (\n (options.trailingSlashMode !== undefined &&\n options.trailingSlashMode !== \"default\") ||\n (options.queryParamsMode !== undefined &&\n options.queryParamsMode !== \"default\") ||\n options.queryParams !== undefined ||\n (options.urlParamsEncoding !== undefined &&\n options.urlParamsEncoding !== \"default\")\n );\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Collected parameters from route segments.\n */\ninterface CollectedParams {\n readonly searchParams: readonly string[];\n readonly nonSearchParams: readonly string[];\n}\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Tries fast path for simple route names without parameters.\n * Returns staticPath if available, null otherwise.\n */\nfunction tryStaticPathFast(tree: RouteTree, routeName: string): string | null {\n if (routeName.includes(\".\")) {\n const segments = getSegmentsByName(tree, routeName);\n const staticPath = segments?.at(-1)?.staticPath;\n\n return staticPath ?? null;\n }\n\n return tree.childrenByName.get(routeName)?.staticPath ?? null;\n}\n\n/**\n * Builds a URL path for the given route name and parameters.\n *\n * @param tree - Route tree to use\n * @param routeName - Dot-notation route name (e.g., \"users.profile\")\n * @param params - Route parameters\n * @param options - Build options\n * @param segments - Optional pre-computed segments (avoids getSegmentsByName call)\n * @returns Built URL path\n * @throws {RouteNotFoundError} If route not found\n *\n * @example\n * ```typescript\n * const url = buildPath(tree, \"users.profile\", { id: \"123\" });\n * // → \"/users/123\"\n *\n * // With pre-computed segments (avoids duplicate lookup)\n * const segments = getSegmentsByName(tree, \"users.profile\");\n * const url = buildPath(tree, \"users.profile\", { id: \"123\" }, {}, segments);\n * ```\n */\nexport function buildPath(\n tree: RouteTree,\n routeName: string,\n params: RouteParams = {},\n options: BuildOptions = {},\n segments?: readonly RouteTree[],\n): string {\n // If segments provided, skip lookup and fast path (caller already has segments)\n if (segments) {\n return buildPathFromSegments(segments, params, options);\n }\n\n // Fast path: no params, default options - try pre-computed staticPath\n // R6 optimization: use hasOwnKeys instead of Object.keys().length (avoids array allocation)\n // R7 optimization: check option VALUES not just keys (enables fast path for real-router)\n const hasParams = hasOwnKeys(params);\n const hasNonDefaults = hasNonDefaultOptions(options);\n\n if (!hasParams && !hasNonDefaults) {\n const staticPath = tryStaticPathFast(tree, routeName);\n\n if (staticPath !== null) {\n return staticPath;\n }\n }\n\n // Regular path: find segments and build\n const foundSegments = getSegmentsByName(tree, routeName);\n\n if (!foundSegments) {\n throw new RouteNotFoundError(\n `[route-node][buildPath] '${routeName}' is not defined`,\n routeName,\n );\n }\n\n return buildPathFromSegments(foundSegments, params, options);\n}\n\n// =============================================================================\n// Internal: Path Building\n// =============================================================================\n\n/**\n * Builds a URL path from route segments.\n *\n * Note: All segments from getSegmentsByName have parsers -\n * root is only included if it has a parser, and children always have parsers.\n */\nfunction buildPathFromSegments(\n segments: readonly RouteTree[],\n params: RouteParams,\n options: BuildOptions,\n): string {\n const { queryParamsMode = \"default\", trailingSlashMode = \"default\" } =\n options;\n\n const collected = collectParamsFromSegments(segments);\n const searchParams = resolveSearchParams(collected, params, queryParamsMode);\n const searchPart = buildSearchString(searchParams, params, options);\n const pathString = buildPathString(segments, params, options);\n const finalPath = applyTrailingSlashMode(pathString, trailingSlashMode);\n\n return finalPath + (searchPart ? `?${searchPart}` : \"\");\n}\n\n/**\n * Collects search and non-search parameters from segments.\n * Uses lazy allocation - arrays only created when params exist.\n */\nfunction collectParamsFromSegments(\n segments: readonly RouteTree[],\n): CollectedParams {\n let searchParams: string[] | null = null;\n let nonSearchParams: string[] | null = null;\n\n for (const segment of segments) {\n // All segments from getSegmentsByName have parsers by design\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const parser = segment.parser!;\n\n // Use for-loop instead of spread (1.49x faster)\n /* eslint-disable @typescript-eslint/prefer-for-of */\n if (parser.queryParams.length > 0) {\n searchParams ??= [];\n\n for (let i = 0; i < parser.queryParams.length; i++) {\n searchParams.push(parser.queryParams[i]);\n }\n }\n\n if (parser.urlParams.length > 0 || parser.spatParams.length > 0) {\n nonSearchParams ??= [];\n\n for (let i = 0; i < parser.urlParams.length; i++) {\n nonSearchParams.push(parser.urlParams[i]);\n }\n\n for (let i = 0; i < parser.spatParams.length; i++) {\n nonSearchParams.push(parser.spatParams[i]);\n }\n }\n /* eslint-enable @typescript-eslint/prefer-for-of */\n }\n\n return {\n searchParams: searchParams ?? EMPTY_ARRAY,\n nonSearchParams: nonSearchParams ?? EMPTY_ARRAY,\n };\n}\n\n/**\n * Resolves final search params, adding loose params if needed.\n */\nfunction resolveSearchParams(\n collected: CollectedParams,\n params: RouteParams,\n queryParamsMode: BuildOptions[\"queryParamsMode\"],\n): readonly string[] {\n if (queryParamsMode !== \"loose\") {\n return collected.searchParams;\n }\n\n // Use slice() instead of spread (1.15x faster)\n const searchParams = [...(collected.searchParams as string[])];\n const searchParamsSet = new Set(collected.searchParams);\n const nonSearchParamsSet = new Set(collected.nonSearchParams);\n\n // Object.hasOwn filters inherited properties (prototype pollution protection)\n for (const p in params) {\n if (\n Object.hasOwn(params, p) &&\n !searchParamsSet.has(p) &&\n !nonSearchParamsSet.has(p)\n ) {\n searchParams.push(p);\n }\n }\n\n return searchParams;\n}\n\n/**\n * Builds the query string from search params.\n */\nfunction buildSearchString(\n searchParams: readonly string[],\n params: RouteParams,\n options: BuildOptions,\n): string {\n const searchParamsObject: RouteParams = {};\n\n for (const paramName of searchParams) {\n if (paramName in params) {\n searchParamsObject[paramName] = params[paramName];\n }\n }\n\n return buildQueryString(searchParamsObject, options.queryParams);\n}\n\n/**\n * Builds the path string from segments.\n */\nfunction buildPathString(\n segments: readonly RouteTree[],\n params: RouteParams,\n options: BuildOptions,\n): string {\n // Direct assignment eliminates conditional mutants\n // Parser handles undefined values the same as missing keys\n const buildOptions: Record<string, unknown> = {\n ignoreSearch: true,\n queryParams: options.queryParams,\n urlParamsEncoding: options.urlParamsEncoding,\n };\n\n let path = \"\";\n\n for (const segment of segments) {\n // All segments from getSegmentsByName have parsers by design\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const segmentPath = segment.parser!.build(params, buildOptions);\n\n path = segment.absolute ? segmentPath : path + segmentPath;\n }\n\n // Always normalize - regex only matches actual \"//\" sequences\n // Removed conditional check as it created equivalent mutants\n return path.replaceAll(/\\/{2,}/g, \"/\");\n}\n\n/**\n * Applies trailing slash mode to the path.\n */\nfunction applyTrailingSlashMode(path: string, mode: TrailingSlashMode): string {\n if (mode === \"always\") {\n return path.endsWith(\"/\") ? path : `${path}/`;\n }\n\n if (mode === \"never\" && path !== \"/\") {\n return path.endsWith(\"/\") ? path.slice(0, -1) : path;\n }\n\n return path;\n}\n","// packages/route-node/modules/operations/meta.ts\n\n/**\n * Metadata Operations.\n *\n * Pure functions for building route parameter metadata.\n *\n * @module operations/meta\n */\n\nimport type {\n ParamTypeMap,\n PathParser,\n RouteTree,\n RouteTreeStateMeta,\n} from \"../types\";\n\n// =============================================================================\n// Public API\n// =============================================================================\n\n/**\n * Builds a map of parameter names to their source type (url or query).\n *\n * @param parser - Path parser to extract parameters from\n * @returns Map of parameter names to their source type\n */\nexport function buildParamTypeMap(parser: PathParser | null): ParamTypeMap {\n const params: ParamTypeMap = {};\n\n if (!parser) {\n return params;\n }\n\n for (const p of parser.urlParams) {\n params[p] = \"url\";\n }\n\n for (const p of parser.queryParams) {\n params[p] = \"query\";\n }\n\n return params;\n}\n\n/**\n * Builds parameter type metadata from route segments.\n *\n * @param segments - Array of route tree segments\n * @returns Metadata mapping segment names to their parameter types\n *\n * @example\n * ```typescript\n * const meta = getMetaFromSegments(matchResult.segments);\n * // → { users: {}, \"users.profile\": { id: \"url\" } }\n * ```\n */\nexport function getMetaFromSegments(\n segments: readonly RouteTree[],\n): RouteTreeStateMeta {\n const meta: RouteTreeStateMeta = {};\n\n for (const segment of segments) {\n // Use pre-computed fullName and paramTypeMap from RouteTree cache\n // This avoids string concatenation and buildParamTypeMap() call per segment\n meta[segment.fullName] = segment.paramTypeMap;\n }\n\n return meta;\n}\n","// packages/route-tree/modules/operations/routeTreeToDefinitions.ts\n\n/**\n * RouteTree to RouteDefinition Converter.\n *\n * Converts a RouteTree back to an array of RouteDefinition objects.\n * Used for serialization and router cloning.\n *\n * @module operations/routeTreeToDefinitions\n */\n\nimport type { RouteDefinition, RouteTree } from \"../types\";\n\n/**\n * Converts a single RouteTree node to a RouteDefinition.\n *\n * If the node has absolute=true, the path is prefixed with '~'\n * to reconstruct the original definition format.\n *\n * @param node - RouteTree node to convert\n * @returns RouteDefinition with name, path, and optional children\n */\nexport function nodeToDefinition(node: RouteTree): RouteDefinition {\n // Reconstruct absolute path marker if needed\n const path = node.absolute ? `~${node.path}` : node.path;\n\n const def: RouteDefinition = {\n name: node.name,\n path,\n };\n\n if (node.children.length > 0) {\n def.children = node.children.map((child) => nodeToDefinition(child));\n }\n\n return def;\n}\n\n/**\n * Converts a RouteTree back to an array of RouteDefinition objects.\n *\n * This is the inverse of createRouteTree - it extracts the minimal\n * definition data (name, path, children) from the computed tree.\n *\n * Note: Extra properties stored in RouteDefinition (like canActivate,\n * forwardTo, encodeParams, etc.) are NOT preserved in RouteTree,\n * so they won't be present in the output.\n *\n * @example\n * ```ts\n * const tree = createRouteTree(\"\", \"\", [\n * { name: \"users\", path: \"/users\", children: [\n * { name: \"profile\", path: \"/:id\" }\n * ]}\n * ]);\n *\n * const definitions = routeTreeToDefinitions(tree);\n * // [{ name: \"users\", path: \"/users\", children: [{ name: \"profile\", path: \"/:id\" }] }]\n * ```\n *\n * @param tree - RouteTree to convert\n * @returns Array of RouteDefinition objects (top-level routes only)\n */\nexport function routeTreeToDefinitions(tree: RouteTree): RouteDefinition[] {\n return tree.children.map((child) => nodeToDefinition(child));\n}\n","// packages/route-node/modules/validation/routes.ts\n\nimport type { RouteTree } from \"../types\";\n\n/**\n * Creates a TypeError with consistent router error message format.\n *\n * @param methodName - Name of the method that triggered the error\n * @param message - Error message\n * @returns TypeError with formatted message\n * @internal\n */\nfunction createRouterError(methodName: string, message: string): TypeError {\n return new TypeError(`[router.${methodName}] ${message}`);\n}\n\n/**\n * Validates route path format.\n * Throws a descriptive error if validation fails.\n *\n * Allows:\n * - Empty string (for grouping/root routes)\n * - Absolute paths: /path, ~path\n * - Query strings: ?query\n * - Relative segments: segment\n *\n * Prevents:\n * - Non-string values\n * - Double slashes (//)\n * - Absolute paths (~) under parameterized parent nodes\n *\n * @param path - Route path to validate\n * @param routeName - Name of route (for error messages)\n * @param methodName - Name of calling method for error messages\n * @param parentNode - Optional parent node for context validation\n * @throws {TypeError} If path is invalid\n *\n * @example\n * // Valid paths\n * validateRoutePath(\"\", \"home\", \"add\"); // ok (empty for grouping)\n * validateRoutePath(\"/users\", \"users\", \"add\"); // ok (absolute)\n * validateRoutePath(\"~dashboard\", \"dash\", \"add\"); // ok (absolute, if no parameterized parent)\n * validateRoutePath(\"?tab=1\", \"home\", \"add\"); // ok (query)\n * validateRoutePath(\"profile\", \"users.profile\", \"add\"); // ok (relative)\n *\n * @example\n * // Invalid paths (throws)\n * validateRoutePath(\"/users//list\", \"users.list\", \"add\"); // throws (double slash)\n * validateRoutePath(\"~dash\", \"dash\", \"add\", paramParent); // throws (~ under parameterized parent)\n */\nexport function validateRoutePath(\n path: unknown,\n routeName: string,\n methodName: string,\n parentNode?: RouteTree,\n): asserts path is string {\n // Type check\n if (typeof path !== \"string\") {\n // Get type description for error message\n let typeDesc: string;\n\n if (path === null) {\n typeDesc = \"null\";\n } else if (Array.isArray(path)) {\n typeDesc = \"array\";\n } else {\n typeDesc = typeof path;\n }\n\n throw createRouterError(\n methodName,\n `Route path must be a string, got ${typeDesc}`,\n );\n }\n\n // Empty path is valid (for grouping/root)\n if (path === \"\") {\n return;\n }\n\n // No whitespace characters (spaces, tabs, newlines)\n if (/\\s/.test(path)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": whitespace not allowed in \"${path}\"`,\n );\n }\n\n // Valid path pattern\n if (!/^([/?~]|[^/]+$)/.test(path)) {\n throw createRouterError(\n methodName,\n `Route \"${routeName}\" has invalid path format: \"${path}\". Path should start with '/', '~', '?' or be a relative segment.`,\n );\n }\n\n // No double slashes\n if (path.includes(\"//\")) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": double slashes not allowed in \"${path}\"`,\n );\n }\n\n // Absolute paths under parameterized parents\n // RouteTree has parser with urlParams array\n // Also support legacy hasUrlParams for backwards compatibility\n const hasUrlParams =\n parentNode?.parser &&\n ((\"urlParams\" in parentNode.parser &&\n parentNode.parser.urlParams.length > 0) ||\n (\"hasUrlParams\" in parentNode.parser &&\n (parentNode.parser as { hasUrlParams?: boolean }).hasUrlParams));\n\n if (path.startsWith(\"~\") && hasUrlParams) {\n throw new Error(\n `[router.${methodName}] Absolute path \"${path}\" cannot be used under parent route with URL parameters`,\n );\n }\n}\n","// packages/route-node/modules/validation/route-batch.ts\n\n/**\n * Batch route validation utilities.\n *\n * Provides validation for adding routes with cross-batch duplicate detection.\n * Used by router.addRoute() to ensure atomicity - all routes validated before any modification.\n */\n\nimport { validateRoutePath } from \"./routes\";\n\nimport type { RouteDefinition, RouteTree } from \"../types\";\n\n/**\n * Pattern for complete route validation (all segments at once).\n * Matches: single segment or multiple segments separated by dots.\n * Each segment must start with letter/underscore, followed by alphanumeric/hyphen/underscore.\n * Rejects: leading/trailing/consecutive dots, segments starting with numbers/hyphens.\n */\nconst FULL_ROUTE_PATTERN = /^[A-Z_a-z][\\w-]*(?:\\.[A-Z_a-z][\\w-]*)*$/;\n\n/**\n * Checks if string contains at least one non-whitespace character.\n */\nconst HAS_NON_WHITESPACE = /\\S/;\n\n/**\n * Maximum route name length to prevent DoS and performance issues.\n */\nconst MAX_ROUTE_NAME_LENGTH = 10_000;\n\n/**\n * Gets a human-readable description of a value's type.\n * Used for error messages to provide helpful debugging information.\n */\nfunction getTypeDescription(value: unknown): string {\n // Handle null explicitly (typeof null === \"object\")\n if (value === null) {\n return \"null\";\n }\n\n if (typeof value === \"object\") {\n // Return constructor name for class instances\n if (\"constructor\" in value && value.constructor.name !== \"Object\") {\n return value.constructor.name;\n }\n\n // Plain object\n return \"object\";\n }\n\n // Primitive types (string, number, boolean, undefined, etc.)\n return typeof value;\n}\n\n/**\n * Checks if an object has getters or setters.\n * Used to detect potentially malicious route objects that could mutate during processing.\n *\n * @param obj - Object to check\n * @returns true if object has getters or setters\n */\nfunction hasGettersOrSetters(obj: Record<string, unknown>): boolean {\n for (const key of Object.keys(obj)) {\n const descriptor = Object.getOwnPropertyDescriptor(obj, key);\n\n if (descriptor && (descriptor.get || descriptor.set)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Validates that route is a plain object without getters/setters.\n * Prevents malicious objects that could mutate during processing.\n *\n * @param route - Route to validate\n * @param methodName - Calling method for error context\n * @throws {TypeError} If route is not a plain object\n */\nfunction validateRouteType(\n route: unknown,\n methodName: string,\n): asserts route is Record<string, unknown> {\n if (!route || typeof route !== \"object\") {\n throw new TypeError(\n `[router.${methodName}] Route must be an object, got ${getTypeDescription(route)}`,\n );\n }\n\n // Check for plain object (prototype must be Object.prototype or null)\n const proto: object | null = Object.getPrototypeOf(route) as object | null;\n\n if (proto !== Object.prototype && proto !== null) {\n throw new TypeError(\n `[router.${methodName}] Route must be a plain object, got ${getTypeDescription(route)}`,\n );\n }\n\n // Check for getters/setters (could cause mutations during processing)\n if (hasGettersOrSetters(route as Record<string, unknown>)) {\n throw new TypeError(\n `[router.${methodName}] Route must not have getters or setters`,\n );\n }\n}\n\n/**\n * Validates that encodeParams is a function if provided.\n *\n * @param route - Route configuration\n * @param methodName - Calling method for error context\n * @throws {TypeError} If encodeParams is not a function\n */\nfunction validateEncodeParams(\n route: Record<string, unknown>,\n methodName: string,\n): void {\n if (\n route.encodeParams !== undefined &&\n typeof route.encodeParams !== \"function\"\n ) {\n throw new TypeError(\n `[router.${methodName}] Route \"${String(route.name)}\" encodeParams must be a function`,\n );\n }\n}\n\n/**\n * Validates that decodeParams is a function if provided.\n *\n * @param route - Route configuration\n * @param methodName - Calling method for error context\n * @throws {TypeError} If decodeParams is not a function\n */\nfunction validateDecodeParams(\n route: Record<string, unknown>,\n methodName: string,\n): void {\n if (\n route.decodeParams !== undefined &&\n typeof route.decodeParams !== \"function\"\n ) {\n throw new TypeError(\n `[router.${methodName}] Route \"${String(route.name)}\" decodeParams must be a function`,\n );\n }\n}\n\n/**\n * Validates that route name is a valid string matching the expected format.\n *\n * Route name rules:\n * - Must be a string\n * - Cannot be empty or whitespace-only\n * - Each segment must match [a-zA-Z_][a-zA-Z0-9_-]*\n * - Segments are separated by dots (e.g., \"users.profile\")\n * - No consecutive dots, no leading/trailing dots\n *\n * @param route - Route configuration\n * @param methodName - Calling method for error context\n * @throws {TypeError} If name is missing, not a string, or invalid format\n */\nfunction validateRouteName(\n route: Record<string, unknown>,\n methodName: string,\n): asserts route is Record<string, unknown> & { name: string } {\n if (typeof route.name !== \"string\") {\n throw new TypeError(\n `[router.${methodName}] Route name must be a string, got ${getTypeDescription(route.name)}`,\n );\n }\n\n const name = route.name;\n\n // Empty string is not allowed for addRoute (unlike root node in type-guards)\n if (name === \"\") {\n throw new TypeError(`[router.${methodName}] Route name cannot be empty`);\n }\n\n // Whitespace-only strings are invalid\n if (!HAS_NON_WHITESPACE.test(name)) {\n throw new TypeError(\n `[router.${methodName}] Route name cannot contain only whitespace`,\n );\n }\n\n // Length check for technical safety\n if (name.length > MAX_ROUTE_NAME_LENGTH) {\n throw new TypeError(\n `[router.${methodName}] Route name exceeds maximum length of ${MAX_ROUTE_NAME_LENGTH} characters`,\n );\n }\n\n // System routes bypass pattern validation (e.g., @@router/UNKNOWN_ROUTE)\n if (name.startsWith(\"@@\")) {\n return;\n }\n\n // Validate route pattern (ASCII only: letters, numbers, underscores, hyphens, dots)\n if (!FULL_ROUTE_PATTERN.test(name)) {\n throw new TypeError(\n `[router.${methodName}] Invalid route name \"${name}\". ` +\n `Each segment must start with a letter or underscore, ` +\n `followed by letters, numbers, underscores, or hyphens. ` +\n `Segments are separated by dots (e.g., \"users.profile\").`,\n );\n }\n}\n\n/**\n * Checks for duplicate route name in existing tree.\n *\n * @param rootNode - Root node to search in\n * @param fullName - Full route name (dot-notation)\n * @param methodName - Calling method for error context\n * @throws {Error} If route name already exists\n */\nfunction checkTreeNameDuplicate(\n rootNode: RouteTree,\n fullName: string,\n methodName: string,\n): void {\n // Use childrenByName Map for O(1) lookup\n const segments = fullName.split(\".\");\n let current: RouteTree | undefined = rootNode;\n\n for (const segment of segments) {\n current = current.childrenByName.get(segment);\n\n if (!current) {\n return; // Route doesn't exist\n }\n }\n\n throw new Error(`[router.${methodName}] Route \"${fullName}\" already exists`);\n}\n\n/**\n * Checks for duplicate route name in current batch.\n *\n * @param seenNames - Set of names already seen in batch\n * @param fullName - Full route name to check\n * @param methodName - Calling method for error context\n * @throws {Error} If duplicate name in batch\n */\nfunction checkBatchNameDuplicate(\n seenNames: Set<string>,\n fullName: string,\n methodName: string,\n): void {\n if (seenNames.has(fullName)) {\n throw new Error(\n `[router.${methodName}] Duplicate route \"${fullName}\" in batch`,\n );\n }\n\n seenNames.add(fullName);\n}\n\n/**\n * Checks for duplicate path in existing tree at same parent level.\n *\n * @param rootNode - Root node to search in\n * @param parentName - Parent route name (empty string for root level)\n * @param routePath - Path to check for duplicates\n * @throws {Error} If path already exists at this level\n */\nfunction checkTreePathDuplicate(\n rootNode: RouteTree,\n parentName: string,\n routePath: string,\n): void {\n // Find parent node using childrenByName\n let parentNode: RouteTree | undefined = rootNode;\n\n if (parentName !== \"\") {\n const segments = parentName.split(\".\");\n\n for (const segment of segments) {\n parentNode = parentNode.childrenByName.get(segment);\n\n if (!parentNode) {\n return; // Parent doesn't exist, so no duplicate\n }\n }\n }\n\n for (const child of parentNode.children) {\n if (child.path === routePath) {\n throw new Error(`Path \"${routePath}\" is already defined`);\n }\n }\n}\n\n/**\n * Checks that parent route exists for dot-notation names.\n *\n * For routes like \"users.profile\", verifies that \"users\" exists either:\n * - In the existing tree\n * - In the current batch (already added before this route)\n *\n * @param rootNode - Root node to search in\n * @param routeName - Route name (possibly with dots)\n * @param methodName - Calling method for error context\n * @param seenNames - Set of names already seen in batch\n * @throws {Error} If parent route does not exist\n */\nfunction checkParentExists(\n rootNode: RouteTree | undefined,\n routeName: string,\n methodName: string,\n seenNames?: Set<string>,\n): void {\n const parts = routeName.split(\".\");\n\n parts.pop(); // Remove last segment (actual route name)\n\n const parentName = parts.join(\".\");\n\n // Check if parent exists in current batch\n if (seenNames?.has(parentName)) {\n return; // Parent was added earlier in this batch\n }\n\n // Check if parent exists in tree\n if (rootNode) {\n const segments = parentName.split(\".\");\n let current: RouteTree | undefined = rootNode;\n\n for (const segment of segments) {\n current = current.childrenByName.get(segment);\n\n if (!current) {\n throw new Error(\n `[router.${methodName}] Parent route \"${parentName}\" does not exist for route \"${routeName}\"`,\n );\n }\n }\n\n return; // Parent exists in tree\n }\n\n // No tree and not in batch - parent doesn't exist\n throw new Error(\n `[router.${methodName}] Parent route \"${parentName}\" does not exist for route \"${routeName}\"`,\n );\n}\n\n/**\n * Checks for duplicate path in current batch at same parent level.\n *\n * @param seenPathsByParent - Map of paths by parent name\n * @param parentName - Parent route name (empty string for root level)\n * @param routePath - Path to check for duplicates\n * @throws {Error} If path already exists at this level in batch\n */\nfunction checkBatchPathDuplicate(\n seenPathsByParent: Map<string, Set<string>>,\n parentName: string,\n routePath: string,\n): void {\n const pathsAtLevel = seenPathsByParent.get(parentName);\n\n if (pathsAtLevel?.has(routePath)) {\n throw new Error(`Path \"${routePath}\" is already defined`);\n }\n\n if (pathsAtLevel) {\n pathsAtLevel.add(routePath);\n } else {\n seenPathsByParent.set(parentName, new Set([routePath]));\n }\n}\n\n/**\n * Validates route structure for add operations.\n *\n * Performs comprehensive validation including:\n * - Type check (must be object)\n * - Name validation\n * - Path validation\n * - Duplicate name detection (in tree and batch)\n * - Duplicate path detection (in tree and batch)\n * - Recursive children validation\n *\n * @param route - Route to validate\n * @param methodName - Calling method for error context\n * @param rootNode - Optional root node for duplicate checking\n * @param parentName - Parent route name for building full path (used in recursion)\n * @param seenNames - Set of names already seen in this batch\n * @param seenPathsByParent - Map of paths by parent for path duplicate detection\n * @throws {TypeError} If route structure is invalid\n * @throws {Error} If route already exists (duplicate)\n * @throws {Error} If path already defined (duplicate)\n *\n * @example\n * ```typescript\n * const seenNames = new Set<string>();\n * const seenPaths = new Map<string, Set<string>>();\n *\n * // Validate routes before adding\n * for (const route of routes) {\n * validateRoute(route, \"add\", rootNode, \"\", seenNames, seenPaths);\n * }\n * ```\n */\nexport function validateRoute(\n route: unknown,\n methodName: string,\n rootNode?: RouteTree,\n parentName = \"\",\n seenNames?: Set<string>,\n seenPathsByParent?: Map<string, Set<string>>,\n): asserts route is RouteDefinition {\n validateRouteType(route, methodName);\n\n const r = route;\n\n // Validate that name is a non-empty string\n validateRouteName(r, methodName);\n\n // Validate path structure\n validateRoutePath(r.path, r.name, methodName, rootNode);\n\n // Validate optional function properties\n validateEncodeParams(r, methodName);\n validateDecodeParams(r, methodName);\n\n const routeName = r.name;\n const fullName = parentName ? `${parentName}.${routeName}` : routeName;\n\n // Check that parent exists for dot-notation names (e.g., \"users.profile\" requires \"users\")\n // Only check for flat routes (no parentName) with dot-notation\n if (!parentName && fullName.includes(\".\")) {\n checkParentExists(rootNode, fullName, methodName, seenNames);\n }\n\n // Check for duplicate name in existing tree\n if (rootNode && fullName) {\n checkTreeNameDuplicate(rootNode, fullName, methodName);\n }\n\n // Check for duplicate name in current batch\n if (seenNames) {\n checkBatchNameDuplicate(seenNames, fullName, methodName);\n }\n\n const routePath = r.path;\n\n // For flat routes with dot-notation names (e.g., \"users.settings\"),\n // extract the parent from the name for path checking.\n // RouteNode will place such routes under their implied parent.\n let pathCheckParent = parentName;\n\n if (routeName.includes(\".\") && !parentName) {\n const parts = routeName.split(\".\");\n\n parts.pop(); // Remove last segment (actual route name)\n\n pathCheckParent = parts.join(\".\");\n }\n\n // Check for duplicate path in existing tree\n if (rootNode) {\n checkTreePathDuplicate(rootNode, pathCheckParent, routePath);\n }\n\n // Check for duplicate path in current batch\n if (seenPathsByParent) {\n checkBatchPathDuplicate(seenPathsByParent, pathCheckParent, routePath);\n }\n\n // Validate children recursively\n if (r.children !== undefined) {\n if (!Array.isArray(r.children)) {\n throw new TypeError(\n `[router.${methodName}] Route \"${routeName}\" children must be an array, got ${getTypeDescription(r.children)}`,\n );\n }\n\n for (const child of r.children) {\n validateRoute(\n child,\n methodName,\n rootNode,\n fullName,\n seenNames,\n seenPathsByParent,\n );\n }\n }\n}\n","// packages/real-router/modules/internals.ts\n\n/**\n * Typed accessors for internal router storage.\n *\n * Router uses Symbols to store internal state that shouldn't appear in Object.keys().\n * These accessors provide type-safe access without scattered type casts.\n *\n * @internal\n */\n\nimport {\n ROOT_TREE_SYMBOL,\n RESOLVED_FORWARD_MAP_SYMBOL,\n CONFIG_SYMBOL,\n} from \"./constants\";\n\nimport type { Router, DefaultDependencies, Config } from \"core-types\";\nimport type { RouteTree } from \"route-tree\";\n\n/**\n * Internal storage shape for router.\n * These properties are stored using Symbols for encapsulation.\n */\ninterface RouterInternals {\n [ROOT_TREE_SYMBOL]: RouteTree;\n [RESOLVED_FORWARD_MAP_SYMBOL]: Record<string, string>;\n [CONFIG_SYMBOL]: Config;\n}\n\n/**\n * Type for router with internal storage exposed.\n */\ntype RouterWithInternals<Dependencies extends DefaultDependencies> =\n Router<Dependencies> & RouterInternals;\n\n// =============================================================================\n// Route Tree Accessors\n// =============================================================================\n\n/**\n * Gets the route tree from router internal storage.\n * Tree is always initialized in createRouter, so this never returns undefined.\n *\n * @param router - Router instance\n * @returns Route tree\n */\nexport function getRouteTree<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): RouteTree {\n return (router as RouterWithInternals<Dependencies>)[ROOT_TREE_SYMBOL];\n}\n\n/**\n * Sets the route tree in router internal storage.\n *\n * @param router - Router instance\n * @param tree - New route tree\n */\nexport function setRouteTree<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n tree: RouteTree,\n): void {\n (router as RouterWithInternals<Dependencies>)[ROOT_TREE_SYMBOL] = tree;\n}\n\n// =============================================================================\n// Resolved Forward Map Accessors\n// =============================================================================\n\n/**\n * Gets the resolved forward map from router internal storage.\n * Map is always initialized in createRouter, so this never returns undefined.\n *\n * @param router - Router instance\n * @returns Resolved forward map (route name → final destination)\n */\nexport function getResolvedForwardMap<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Record<string, string> {\n return (router as RouterWithInternals<Dependencies>)[\n RESOLVED_FORWARD_MAP_SYMBOL\n ];\n}\n\n/**\n * Sets the resolved forward map in router internal storage.\n *\n * @param router - Router instance\n * @param map - New resolved forward map\n */\nexport function setResolvedForwardMap<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n map: Record<string, string>,\n): void {\n (router as RouterWithInternals<Dependencies>)[RESOLVED_FORWARD_MAP_SYMBOL] =\n map;\n}\n\n// =============================================================================\n// Config Accessors\n// =============================================================================\n\n/**\n * Gets the router configuration from internal storage.\n * Config is always initialized in createRouter, so this never returns undefined.\n *\n * @param router - Router instance\n * @returns Router configuration (decoders, encoders, defaultParams, forwardMap)\n */\nexport function getConfig<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Config {\n return (router as RouterWithInternals<Dependencies>)[CONFIG_SYMBOL];\n}\n\n/**\n * Sets the router configuration in internal storage.\n *\n * @param router - Router instance\n * @param config - New configuration\n */\nexport function setConfig<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n config: Config,\n): void {\n (router as RouterWithInternals<Dependencies>)[CONFIG_SYMBOL] = config;\n}\n","// packages/real-router/modules/core/stateBuilder.ts\n\n/**\n * State Builder Utilities.\n *\n * Functions for building RouteTreeState from raw route segments.\n * This module handles the conversion from low-level route-node data\n * to the higher-level state representation used by real-router.\n *\n * @module core/stateBuilder\n */\n\nimport { getMetaFromSegments } from \"route-tree\";\n\nimport type {\n MatchResult,\n RouteParams,\n RouteTree,\n RouteTreeState,\n} from \"route-tree\";\n\n/**\n * Builds a dot-separated route name from segments.\n *\n * @param segments - Array of route segments with names\n * @returns Dot-separated route name (e.g., \"users.profile\")\n *\n * @example\n * ```typescript\n * const segments = [{ name: \"users\" }, { name: \"profile\" }];\n * buildNameFromSegments(segments); // \"users.profile\"\n * ```\n */\nexport function buildNameFromSegments(segments: readonly RouteTree[]): string {\n let name = \"\";\n\n for (const segment of segments) {\n if (segment.name) {\n if (name) {\n name += \".\";\n }\n\n name += segment.name;\n }\n }\n\n return name;\n}\n\n/**\n * Creates a RouteTreeState from a MatchResult.\n *\n * This function is the primary way to build a RouteTreeState when\n * you have a MatchResult from matchPathSegments() or other low-level APIs.\n *\n * @param matchResult - Result from matchPathSegments() containing segments and params\n * @param name - Optional explicit name (if not provided, built from segments)\n * @returns RouteTreeState with name, params, and meta\n *\n * @example\n * ```typescript\n * const matchResult = routeNode.matchPathSegments(\"/users/123\");\n * if (matchResult) {\n * const state = createRouteState(matchResult);\n * // { name: \"users.profile\", params: { id: \"123\" }, meta: {...} }\n * }\n * ```\n */\nexport function createRouteState<P extends RouteParams = RouteParams>(\n matchResult: MatchResult<P>,\n name?: string,\n): RouteTreeState<P> {\n const resolvedName = name ?? buildNameFromSegments(matchResult.segments);\n\n return {\n name: resolvedName,\n params: matchResult.params,\n meta: getMetaFromSegments(matchResult.segments),\n };\n}\n","// packages/real-router/modules/core/routes/routePath.ts\n\nimport {\n createRouteTree,\n matchSegments,\n buildPath as routeNodeBuildPath,\n} from \"route-tree\";\nimport { isString } from \"type-guards\";\n\nimport { constants } from \"@real-router/core\";\n\nimport { ROUTE_DEFINITIONS_SYMBOL, ROOT_PATH_SYMBOL } from \"../../constants\";\nimport { createBuildOptions } from \"../../helpers\";\nimport { getConfig, getRouteTree, setRouteTree } from \"../../internals\";\nimport { createRouteState } from \"../stateBuilder\";\n\nimport type {\n Params,\n State,\n Router,\n DefaultDependencies,\n Options,\n} from \"core-types\";\nimport type {\n BuildOptions,\n MatchOptions,\n RouteDefinition,\n RouteTree,\n} from \"route-tree\";\n\n// =============================================================================\n// BuildOptions Cache (local to routePath)\n// =============================================================================\n\n/**\n * Internal Symbol for caching buildOptions.\n * Local to this module — only used by buildPath functionality.\n *\n * @internal\n * @todo RFC-1: Replace with direct #options field access from internal contour.\n */\nconst BUILD_OPTIONS_CACHE_SYMBOL = Symbol(\"real-router.buildOptionsCache\");\n\n/**\n * Type for router with cached buildOptions.\n */\ntype RouterWithCache = Record<symbol, BuildOptions | undefined>;\n\n/**\n * Initializes buildOptions cache for a router.\n * Called from routerLifecycle.ts at router.start().\n *\n * @param router - Router instance\n * @param options - Router options\n *\n * @internal\n */\nexport function initBuildOptionsCache<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n options: Options,\n): void {\n // Invalidate previous cache (support for stop/start cycles)\n delete (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL];\n // Create new cache with current options\n (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL] =\n createBuildOptions(options);\n}\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst DEFAULT_ROUTE_NAME = \"\";\n\n/**\n * Creates RouteNode match options from real-router options.\n */\nfunction createMatchOptions(options: Options): MatchOptions {\n return {\n ...createBuildOptions(options),\n caseSensitive: options.caseSensitive,\n strictTrailingSlash: options.trailingSlash === \"strict\",\n strongMatching: false,\n };\n}\n\n/**\n * Adds path building and matching capabilities to a router instance.\n * Handles URL path construction, path-to-route matching, and root path management.\n *\n * @returns Function to enhance router with path capabilities\n */\nexport function withRoutePath<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n /**\n * Builds a URL path for a route with parameters.\n *\n * @param route - Route name (dot-notation for nested routes, e.g., 'users.profile')\n * @param params - Route parameters to encode into the path\n * @returns Built URL path\n * @throws {TypeError} If route is not a non-empty string\n * @throws {Error} If route does not exist in the router\n * @throws {Error} If required parameters are missing\n * @throws {Error} If parameter value doesn't match its constraint pattern\n *\n * @remarks\n * **Parameter Type Coercion:**\n * - Numeric values (including `NaN`, `Infinity`, `-Infinity`) are converted to strings\n * via `String()`. This may produce unexpected URLs like `/user/NaN` or `/user/Infinity`.\n * Validate numeric parameters before passing them to buildPath if semantic correctness\n * is required.\n * - Boolean values are converted to `\"true\"` or `\"false\"` strings.\n * - Empty strings throw an error as they don't match the default parameter pattern.\n * - Arrays are converted via `String()` (e.g., `[\"a\",\"b\"]` → `\"a,b\"`), which may fail\n * validation unless a custom constraint like `<.*>` is used.\n *\n * @example\n * // Basic usage\n * router.buildPath('users.view', { id: '123' });\n * // Returns: '/users/123'\n *\n * @example\n * // With query parameters\n * router.buildPath('search', { q: 'hello', page: '1' });\n * // Returns: '/search?q=hello&page=1'\n *\n * @example\n * // Numeric values are stringified (use with caution)\n * router.buildPath('user', { id: 42 }); // → '/user/42'\n * router.buildPath('user', { id: NaN }); // → '/user/NaN' ⚠️\n * router.buildPath('user', { id: Infinity }); // → '/user/Infinity' ⚠️\n */\n router.buildPath = (route: string, params?: Params): string => {\n // Early validation for better DX (fail-fast with clear message)\n if (!isString(route) || route === \"\") {\n throw new TypeError(\n `[real-router] buildPath: route must be a non-empty string, got ${typeof route === \"string\" ? '\"\"' : typeof route}`,\n );\n }\n\n if (route === constants.UNKNOWN_ROUTE) {\n return isString(params?.path) ? params.path : \"\";\n }\n\n const config = getConfig(router);\n\n // R2 optimization: avoid spread when no defaultParams\n const paramsWithDefault = Object.hasOwn(config.defaultParams, route)\n ? { ...config.defaultParams[route], ...params }\n : (params ?? {});\n\n // Apply custom encoder if defined (copy protects original params)\n const encodedParams =\n typeof config.encoders[route] === \"function\"\n ? config.encoders[route]({ ...paramsWithDefault })\n : paramsWithDefault;\n\n // R5 optimization: read cached buildOptions (created at router.start())\n // Fallback for cold calls before start() — creates buildOptions on the fly\n const buildOptions =\n (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL] ??\n createBuildOptions(router.getOptions());\n\n return routeNodeBuildPath(\n getRouteTree(router),\n route,\n encodedParams,\n buildOptions,\n );\n };\n\n /**\n * Internal path builder that accepts pre-computed segments.\n * Avoids duplicate getSegmentsByName call when segments are already available.\n *\n * @internal\n */\n router.buildPathWithSegments = (\n route: string,\n params: Params,\n segments: readonly unknown[],\n ): string => {\n // Early validation for better DX (fail-fast with clear message)\n if (!isString(route) || route === \"\") {\n throw new TypeError(\n `[real-router] buildPathWithSegments: route must be a non-empty string, got ${typeof route === \"string\" ? '\"\"' : typeof route}`,\n );\n }\n\n if (route === constants.UNKNOWN_ROUTE) {\n return isString(params.path) ? params.path : \"\";\n }\n\n const config = getConfig(router);\n\n // R2 optimization: avoid spread when no defaultParams\n const paramsWithDefault = Object.hasOwn(config.defaultParams, route)\n ? { ...config.defaultParams[route], ...params }\n : params;\n\n // Apply custom encoder if defined (copy protects original params)\n const encodedParams =\n typeof config.encoders[route] === \"function\"\n ? config.encoders[route]({ ...paramsWithDefault })\n : paramsWithDefault;\n\n // R5 optimization: read cached buildOptions\n /* v8 ignore next 2 -- @preserve defensive: always called after router.start() */\n const buildOptions =\n (router as RouterWithCache)[BUILD_OPTIONS_CACHE_SYMBOL] ??\n createBuildOptions(router.getOptions());\n\n // Pass segments to avoid duplicate getSegmentsByName call in route-tree\n // Cast to RouteTree[] - segments come from getSegmentsByName which returns RouteTree[]\n return routeNodeBuildPath(\n getRouteTree(router),\n route,\n encodedParams,\n buildOptions,\n segments as readonly RouteTree[],\n );\n };\n\n /**\n * Matches a URL path to a route in the tree.\n * Uses caching for performance optimization.\n * Note: RouteNode automatically matches `/` child nodes when accessing parent.\n *\n * @param path - URL path to match\n * @param source - Optional source identifier for debugging\n * @returns Matched state or undefined if no match\n *\n * @example\n * const state = router.matchPath('/users/123');\n * // Returns: { name: 'users.view', params: { id: '123' }, ... }\n */\n router.matchPath = <P extends Params = Params, MP extends Params = Params>(\n path: string,\n source?: string,\n ): State<P, MP> | undefined => {\n // Early validation for better DX (fail-fast with clear message)\n if (!isString(path)) {\n throw new TypeError(\n `[real-router] matchPath: path must be a string, got ${typeof path}`,\n );\n }\n\n const options = router.getOptions();\n\n // Use full set of options supported by RouteNode\n const matchOptions = createMatchOptions(options);\n\n // Use low-level API: get segments and build state in real-router\n const matchResult = matchSegments(getRouteTree(router), path, matchOptions);\n\n if (matchResult) {\n // Build RouteTreeState from MatchResult\n const routeState = createRouteState(matchResult);\n const { name, params, meta } = routeState;\n\n const { decoders } = getConfig(router);\n const decodedParams =\n typeof decoders[name] === \"function\"\n ? decoders[name](params as Params)\n : params;\n const { name: routeName, params: routeParams } = router.forwardState<P>(\n name,\n decodedParams as P,\n );\n const builtPath = options.rewritePathOnMatch\n ? router.buildPath(routeName, routeParams)\n : path;\n\n // makeState() already returns frozen state - no need for redundant freeze\n return router.makeState<P, MP>(routeName, routeParams, builtPath, {\n params: meta as MP,\n options: {},\n source,\n redirected: false,\n });\n }\n\n return undefined;\n };\n\n /**\n * Sets the root path for the router.\n *\n * @param newRootPath - New root path\n */\n router.setRootPath = (newRootPath): void => {\n type RouterInternal = Record<symbol, RouteDefinition[] | string>;\n const routerInternal = router as RouterInternal;\n\n routerInternal[ROOT_PATH_SYMBOL] = newRootPath;\n\n // Rebuild tree with new root path\n const routeDefinitions = routerInternal[\n ROUTE_DEFINITIONS_SYMBOL\n ] as RouteDefinition[];\n\n setRouteTree(\n router,\n createRouteTree(DEFAULT_ROUTE_NAME, newRootPath, routeDefinitions, {\n skipValidation: true,\n }),\n );\n };\n\n router.getRootPath = (): string => {\n return (router as Record<symbol, string>)[ROOT_PATH_SYMBOL] || \"\";\n };\n\n return router;\n}\n","// packages/real-router/modules/core/routerLifecycle.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { isState } from \"type-guards\";\n\nimport { errorCodes, events, RouterError } from \"@real-router/core\";\n\nimport { initBuildOptionsCache } from \"./routes/routePath\";\n\nimport type {\n DoneFn,\n NavigationOptions,\n Params,\n State,\n DefaultDependencies,\n Router,\n RouterError as RouterErrorType,\n} from \"core-types\";\n\nconst noop = () => {};\n\n// =============================================================================\n// Cached Errors (Performance Optimization)\n// =============================================================================\n// Pre-create error instances to avoid object allocation on hot paths.\n// Error creation involves: new object, stack trace capture (~500ns-2μs).\n// Cached errors skip this overhead entirely.\n//\n// Trade-off: All error instances share the same stack trace (points here).\n// This is acceptable because:\n// 1. These errors indicate user misconfiguration, not internal bugs\n// 2. Error code and message are sufficient for debugging\n// 3. Performance gain (~80% for error paths) outweighs stack trace loss\n// =============================================================================\n\n/**\n * Cached error for start() called without path/state and no defaultRoute.\n *\n * @internal\n */\nconst CACHED_NO_START_PATH_ERROR = new RouterError(\n errorCodes.NO_START_PATH_OR_STATE,\n);\n\n/**\n * Cached error for start() called when router is already started/starting.\n *\n * @internal\n */\nconst CACHED_ALREADY_STARTED_ERROR = new RouterError(\n errorCodes.ROUTER_ALREADY_STARTED,\n);\n\ntype StartRouterArguments =\n | []\n | [done: DoneFn]\n | [startPathOrState: string | State]\n | [startPathOrState: string | State, done: DoneFn];\n\nconst getStartRouterArguments = (\n args: StartRouterArguments,\n): [startPathOrState: string | State | undefined, done: DoneFn] => {\n // Simple validation\n if (args.length > 2) {\n throw new Error(\"Invalid number of arguments\");\n }\n\n const [first, second] = args;\n\n if (!first) {\n return [undefined, noop];\n }\n if (typeof first === \"function\") {\n return [undefined, first];\n }\n\n return [first, second ?? noop];\n};\n\n// State resolution logic\nconst resolveStartState = <Dependencies extends DefaultDependencies>(\n pathOrState: string | State,\n router: Router<Dependencies>,\n): State | undefined => {\n if (typeof pathOrState === \"string\") {\n return router.matchPath(pathOrState);\n }\n\n // Validate state object structure using isState type guard\n // This validates: name (non-empty string), path (string), params (plain object)\n // Rejects: missing fields, wrong types, functions, symbols, class instances\n if (!isState(pathOrState)) {\n return undefined;\n }\n\n // Validate that the route exists\n // buildPath throws RouteNotFoundError for invalid routes, so we wrap in try-catch\n // to gracefully return undefined instead of propagating the error\n // See: https://github.com/greydragon888/real-router/issues/42\n try {\n router.buildPath(pathOrState.name, pathOrState.params);\n } catch {\n return undefined;\n }\n\n return pathOrState;\n};\n\n// Note: Guards cannot redirect - redirects are not supported from guards\n// See: https://github.com/greydragon888/real-router/issues/44\n// Transition errors are always reported to callback, no silent fallback to defaultRoute\n\nconst STARTED = Symbol(\"started\");\n// Issue #50: Track \"active\" state separately from \"started\"\n// Active = router is starting or started (allows transitions)\n// Started = router has completed initial start (allows navigation)\nconst ACTIVE = Symbol(\"active\");\n\nexport function withRouterLifecycle<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n router[STARTED] = false;\n router[ACTIVE] = false;\n\n const setIsStarted = () => {\n router[STARTED] = true;\n };\n\n const unsetIsStarted = () => {\n router[STARTED] = false;\n };\n\n const setIsActive = () => {\n router[ACTIVE] = true;\n };\n\n const unsetIsActive = () => {\n router[ACTIVE] = false;\n };\n\n router.isStarted = () => !!router[STARTED];\n\n // Issue #50: isActive() indicates router is starting or started\n // Used by transition to check if transitions should be cancelled\n router.isActive = () => !!router[ACTIVE];\n\n router.start = (...args: StartRouterArguments): Router<Dependencies> => {\n const options = router.getOptions();\n const [startPathOrState, done] = getStartRouterArguments(args);\n\n let callbackInvoked = false;\n\n // Early return if already started or starting (concurrent start() protection)\n // Issue #50: Check both isStarted() and isActive() to block concurrent start() calls\n // - isStarted(): Router has completed initial start\n // - isActive(): Router is in the process of starting (async transition in progress)\n // Performance: Uses cached error to avoid object allocation (~500ns-2μs saved)\n if (router.isStarted() || router.isActive()) {\n callbackInvoked = true;\n\n done(CACHED_ALREADY_STARTED_ERROR);\n\n return router;\n }\n\n // ==========================================================================\n // Early return for NO_START_PATH_OR_STATE (Performance Optimization)\n // ==========================================================================\n // Check BEFORE setIsActive() to avoid:\n // - setIsActive/unsetIsActive calls\n // - handleTransitionComplete overhead\n // - Event emission setup\n //\n // This is a common error case: start() called without path and no defaultRoute.\n // Optimizing this path saves ~80% of error handling overhead.\n // ==========================================================================\n if (!startPathOrState && !options.defaultRoute) {\n callbackInvoked = true;\n\n // Lazy emit: only invoke if listeners exist\n // hasListeners check (~5ns) vs invokeEventListeners validation (~100ns+)\n if (router.hasListeners(events.TRANSITION_ERROR)) {\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n undefined,\n CACHED_NO_START_PATH_ERROR,\n );\n }\n\n done(CACHED_NO_START_PATH_ERROR);\n\n return router;\n }\n\n // Issue #50: Mark router as active BEFORE attempting transition\n // This allows the transition to proceed (isCancelled() checks isActive())\n setIsActive();\n\n // Perform the actual transition\n // See: https://github.com/greydragon888/real-router/issues/44\n // On error, always report to handleTransitionComplete (no silent fallback)\n const performTransition = (\n toState: State,\n navOptions: NavigationOptions = {},\n ) => {\n // Use internal navigateToState without emitting TRANSITION_SUCCESS\n // handleTransitionComplete will emit it\n router.navigateToState(\n toState,\n undefined,\n navOptions,\n (err: RouterErrorType | undefined, resultState: State | undefined) => {\n handleTransitionComplete(err, resultState);\n },\n false, // emitSuccess = false - handleTransitionComplete will emit\n );\n };\n\n const protectedDone = (err?: RouterError, state?: State) => {\n if (callbackInvoked) {\n logger.warn(\"real-router\", \"Callback already invoked\");\n\n return;\n }\n\n callbackInvoked = true;\n // State is already frozen from makeState() in start flow\n done(err, state);\n };\n\n // Base options for all operations in start() method\n const startOptions: NavigationOptions = {\n replace: true, // start() always replace history\n };\n\n // Centralized callback for transition completion\n // See: https://github.com/greydragon888/real-router/issues/44\n // Transition errors are always reported (no silent fallback to defaultRoute)\n //\n // See: https://github.com/greydragon888/real-router/issues/50\n // Two-phase start: Only mark router as started AFTER successful transition\n // This prevents inconsistent state where isStarted()=true but getState()=undefined\n //\n // Note: emitErrorEvent controls whether TRANSITION_ERROR event is emitted:\n // - true: for errors NOT going through navigateToState (ROUTE_NOT_FOUND, NO_START_PATH_OR_STATE)\n // - false: for errors from performTransition (navigateToState already emits TRANSITION_ERROR)\n const handleTransitionComplete = (\n err?: RouterError,\n state?: State,\n emitErrorEvent = false,\n ) => {\n if (err) {\n // Issue #50: Unset active flag on failure (router is no longer starting)\n unsetIsActive();\n\n if (emitErrorEvent && router.hasListeners(events.TRANSITION_ERROR)) {\n // Emit TRANSITION_ERROR for errors not going through navigateToState\n // Performance: Skip emission if no listeners\n router.invokeEventListeners(\n events.TRANSITION_ERROR,\n undefined,\n undefined,\n err,\n );\n }\n } else {\n // Two-phase start: Only set started and emit ROUTER_START on success\n // See: https://github.com/greydragon888/real-router/issues/50\n setIsStarted();\n router.invokeEventListeners(events.ROUTER_START);\n\n router.invokeEventListeners(\n events.TRANSITION_SUCCESS,\n state,\n undefined,\n { replace: true },\n );\n }\n // For performTransition errors, TRANSITION_ERROR is already emitted by navigateToState\n\n protectedDone(err, state);\n };\n\n // Build state for default route and perform transition\n // Uses performTransition to properly handle two-phase start\n const navigateToDefault = (\n defaultRouteName: string,\n defaultParams: Params,\n navOptions: NavigationOptions,\n ) => {\n const defaultRoute = router.buildState(defaultRouteName, defaultParams);\n\n if (!defaultRoute) {\n handleTransitionComplete(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, {\n routeName: defaultRouteName,\n }),\n undefined,\n true,\n );\n\n return;\n }\n\n const toState = router.makeState(\n defaultRoute.name,\n defaultRoute.params,\n router.buildPath(defaultRoute.name, defaultRoute.params),\n {\n params: defaultRoute.meta,\n options: navOptions,\n redirected: false,\n },\n );\n\n performTransition(toState, navOptions);\n };\n\n // Resolve start path/state: use defaultRoute if no explicit path provided\n // Note: Early return for \"no path AND no defaultRoute\" is handled above\n const resolvedStartPathOrState = startPathOrState ?? options.defaultRoute;\n\n // Parse the start path or state\n const startState = resolveStartState(resolvedStartPathOrState, router);\n\n // Determine the target state and path\n const targetPath =\n typeof resolvedStartPathOrState === \"string\"\n ? resolvedStartPathOrState\n : \"\";\n\n // Check if we can attempt to start the router\n // See: https://github.com/greydragon888/real-router/issues/50\n // Two-phase start: We only initialize the cache here, but don't mark as started yet.\n // The router will be marked as started only after successful transition in handleTransitionComplete.\n //\n // Note: !startPathOrState checks ORIGINAL argument to distinguish:\n // - start() without path → can use defaultRoute\n // - start('/invalid') with explicit path → no silent fallback (Issue #44)\n const canAttemptStart =\n startState !== undefined ||\n options.allowNotFound ||\n (options.defaultRoute && !startPathOrState);\n\n if (canAttemptStart) {\n // Setup buildOptions cache for buildPath (needed for transition)\n initBuildOptionsCache(router, options);\n }\n\n // Perform transition based on conditions\n // All start() transitions should use replace: true\n // See: https://github.com/greydragon888/real-router/issues/43\n if (startState) {\n performTransition(startState, startOptions);\n } else if (options.defaultRoute && !startPathOrState) {\n // IMPORTANT: Check !startPathOrState (original argument), NOT !resolvedStartPathOrState\n // This distinguishes between:\n // - User called start() without path → use defaultRoute (this branch)\n // - User called start('/invalid') with explicit path → error, no silent fallback\n // See: https://github.com/greydragon888/real-router/issues/44\n\n const params = options.defaultParams;\n\n navigateToDefault(options.defaultRoute, params, startOptions);\n } else if (options.allowNotFound) {\n performTransition(\n router.makeNotFoundState(targetPath, startOptions),\n startOptions,\n );\n } else {\n handleTransitionComplete(\n new RouterError(errorCodes.ROUTE_NOT_FOUND, { path: targetPath }),\n undefined,\n true, // emitErrorEvent: doesn't go through navigateToState\n );\n }\n\n return router;\n };\n\n router.stop = (): Router<Dependencies> => {\n // Issue #50: Always unset active flag when stopping\n // This cancels any in-flight transitions via isCancelled() check\n unsetIsActive();\n\n if (router.isStarted()) {\n unsetIsStarted();\n\n router.setState(undefined);\n\n router.invokeEventListeners(events.ROUTER_STOP);\n }\n\n return router;\n };\n\n return router;\n}\n","// packages/real-router/modules/core/routes/routeConfig.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { getSegmentsByName } from \"route-tree\";\nimport { isParams, getTypeDescription } from \"type-guards\";\n\nimport { getConfig, setResolvedForwardMap } from \"../../internals\";\n\nimport type {\n ActivationFnFactory,\n Config,\n DefaultDependencies,\n Params,\n Route,\n Router,\n} from \"core-types\";\nimport type { RouteDefinition, RouteTree } from \"route-tree\";\n\n// ============================================================================\n// Validation Helpers\n// ============================================================================\n\n/**\n * Validates parameters object structure.\n *\n * @param params - Parameters to validate\n * @param methodName - Calling method for error context\n * @throws {TypeError} If params structure is invalid\n */\nexport function validateParams(\n params: unknown,\n methodName: string,\n): asserts params is Params {\n if (!isParams(params)) {\n throw new TypeError(\n `[router.${methodName}] Invalid params structure: ${getTypeDescription(params)}`,\n );\n }\n}\n\n/**\n * Validates route properties (canActivate, defaultParams) before registration.\n * This ensures type safety at configuration time, not runtime.\n *\n * @param route - Route to validate\n * @param fullName - Full route name (with parent prefix)\n * @throws {TypeError} If canActivate is not a function\n * @throws {TypeError} If defaultParams is not a plain object\n */\nexport function validateRouteProperties<\n Dependencies extends DefaultDependencies,\n>(route: Route<Dependencies>, fullName: string): void {\n // Validate canActivate is a function\n if (\n route.canActivate !== undefined &&\n typeof route.canActivate !== \"function\"\n ) {\n throw new TypeError(\n `[router.addRoute] canActivate must be a function for route \"${fullName}\", ` +\n `got ${getTypeDescription(route.canActivate)}`,\n );\n }\n\n // Validate defaultParams is a plain object\n // Runtime check for invalid types passed via `as any`\n if (route.defaultParams !== undefined) {\n const params: unknown = route.defaultParams;\n\n if (\n params === null ||\n typeof params !== \"object\" ||\n Array.isArray(params)\n ) {\n throw new TypeError(\n `[router.addRoute] defaultParams must be an object for route \"${fullName}\", ` +\n `got ${getTypeDescription(route.defaultParams)}`,\n );\n }\n }\n\n // Recursively validate children\n if (route.children) {\n for (const child of route.children) {\n const childFullName = `${fullName}.${child.name}`;\n\n validateRouteProperties(child, childFullName);\n }\n }\n}\n\n// ============================================================================\n// Parameter Extraction Helpers\n// ============================================================================\n\n/**\n * Extracts required path parameters from route segments.\n * Required params are urlParams and spatParams (not queryParams).\n *\n * Note: getSegmentsByName only returns segments with parsers,\n * so we can safely use non-null assertion here.\n *\n * @param segments - Route segments from getSegmentsByName\n * @returns Set of required parameter names\n */\nexport function getRequiredParams(segments: readonly RouteTree[]): Set<string> {\n const params = new Set<string>();\n\n for (const segment of segments) {\n // getSegmentsByName only includes segments with parsers\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const parser = segment.parser!;\n\n for (const param of parser.urlParams) {\n params.add(param);\n }\n\n for (const param of parser.spatParams) {\n params.add(param);\n }\n }\n\n return params;\n}\n\n/**\n * Extracts parameter names from a path string.\n * Matches :param and *splat patterns.\n *\n * @param path - Route path string\n * @returns Set of parameter names\n */\nfunction extractParamsFromPath(path: string): Set<string> {\n const params = new Set<string>();\n // Match :param and *splat patterns\n const paramRegex = /[*:]([A-Z_a-z]\\w*)/g;\n let match;\n\n while ((match = paramRegex.exec(path)) !== null) {\n params.add(match[1]);\n }\n\n return params;\n}\n\n/**\n * Collects all path segments for a route from batch definitions.\n * Traverses parent routes to include inherited path segments.\n *\n * @remarks Callers must guarantee routeName exists in routes.\n *\n * @param routes - Batch of routes to search\n * @param routeName - Full route name to find (must exist in routes)\n * @param parentName - Current parent name prefix\n * @param paths - Accumulated path segments\n * @returns Array of path strings\n */\nfunction collectPathsToRoute<Dependencies extends DefaultDependencies>(\n routes: readonly Route<Dependencies>[],\n routeName: string,\n parentName = \"\",\n paths: string[] = [],\n): string[] {\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n const currentPaths = [...paths, route.path];\n\n if (fullName === routeName) {\n return currentPaths;\n }\n\n if (route.children && routeName.startsWith(`${fullName}.`)) {\n return collectPathsToRoute(\n route.children,\n routeName,\n fullName,\n currentPaths,\n );\n }\n }\n\n /* v8 ignore next -- @preserve unreachable: callers guarantee routeName exists in routes */\n return undefined as never;\n}\n\n/**\n * Extracts all parameters from multiple path segments.\n *\n * @param paths - Array of path strings\n * @returns Set of all parameter names\n */\nfunction extractParamsFromPaths(paths: readonly string[]): Set<string> {\n const params = new Set<string>();\n\n for (const path of paths) {\n for (const param of extractParamsFromPath(path)) {\n params.add(param);\n }\n }\n\n return params;\n}\n\n/**\n * Collects all route names from a batch of routes (including children).\n *\n * @param routes - Routes to collect names from\n * @param parentName - Parent name prefix\n * @returns Set of all route names in the batch\n */\nfunction collectRouteNames<Dependencies extends DefaultDependencies>(\n routes: readonly Route<Dependencies>[],\n parentName = \"\",\n): Set<string> {\n const names = new Set<string>();\n\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n\n names.add(fullName);\n\n if (route.children) {\n for (const childName of collectRouteNames(route.children, fullName)) {\n names.add(childName);\n }\n }\n }\n\n return names;\n}\n\n/**\n * Collects all forwardTo mappings from a batch of routes (including children).\n *\n * @param routes - Routes to collect forwardTo from\n * @param parentName - Parent name prefix\n * @returns Map of source route name to target route name\n */\nfunction collectForwardMappings<Dependencies extends DefaultDependencies>(\n routes: readonly Route<Dependencies>[],\n parentName = \"\",\n): Map<string, string> {\n const mappings = new Map<string, string>();\n\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n\n if (route.forwardTo) {\n mappings.set(fullName, route.forwardTo);\n }\n\n if (route.children) {\n for (const [key, value] of collectForwardMappings(\n route.children,\n fullName,\n )) {\n mappings.set(key, value);\n }\n }\n }\n\n return mappings;\n}\n\n/**\n * Checks if a route exists in the tree by navigating through childrenByName.\n *\n * @param tree - Root node of the route tree\n * @param routeName - Full route name (e.g., \"users.profile\")\n * @returns true if route exists, false otherwise\n */\nfunction routeExistsInTree(tree: RouteTree, routeName: string): boolean {\n const segments = routeName.split(\".\");\n let current: RouteTree | undefined = tree;\n\n for (const segment of segments) {\n current = current.childrenByName.get(segment);\n\n if (!current) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Gets the target route parameters for validation.\n */\nfunction getTargetParams<Dependencies extends DefaultDependencies>(\n targetRoute: string,\n existsInTree: boolean,\n tree: RouteTree,\n routes: readonly Route<Dependencies>[],\n): Set<string> {\n if (existsInTree) {\n const toSegments = getSegmentsByName(tree, targetRoute);\n\n // toSegments won't be null since we checked existsInTree\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return getRequiredParams(toSegments!);\n }\n\n // Target is in batch\n return extractParamsFromPaths(collectPathsToRoute(routes, targetRoute));\n}\n\n/**\n * Validates a single forward mapping for target existence and param compatibility.\n *\n * @throws {Error} If target doesn't exist or params are incompatible\n */\nfunction validateSingleForward<Dependencies extends DefaultDependencies>(\n fromRoute: string,\n targetRoute: string,\n routes: readonly Route<Dependencies>[],\n batchNames: Set<string>,\n tree: RouteTree,\n): void {\n const existsInTree = routeExistsInTree(tree, targetRoute);\n const existsInBatch = batchNames.has(targetRoute);\n\n if (!existsInTree && !existsInBatch) {\n throw new Error(\n `[router.addRoute] forwardTo target \"${targetRoute}\" does not exist ` +\n `for route \"${fromRoute}\"`,\n );\n }\n\n // Get source params\n const fromParams = extractParamsFromPaths(\n collectPathsToRoute(routes, fromRoute),\n );\n\n // Get target params\n const toParams = getTargetParams(targetRoute, existsInTree, tree, routes);\n\n // Check for missing params\n const missingParams = [...toParams].filter((p) => !fromParams.has(p));\n\n if (missingParams.length > 0) {\n throw new Error(\n `[router.addRoute] forwardTo target \"${targetRoute}\" requires params ` +\n `[${missingParams.join(\", \")}] that are not available in source route \"${fromRoute}\"`,\n );\n }\n}\n\n/**\n * Validates forwardTo targets and cycles BEFORE any modifications.\n * This ensures atomicity - if validation fails, no routes are added.\n *\n * @param routes - Routes to validate\n * @param existingForwardMap - Current forwardMap from router.config\n * @param tree - Current route tree\n *\n * @throws {Error} If forwardTo target doesn't exist\n * @throws {Error} If circular forwardTo is detected\n */\nexport function validateForwardToTargets<\n Dependencies extends DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n existingForwardMap: Record<string, string>,\n tree: RouteTree,\n): void {\n const batchNames = collectRouteNames(routes);\n const batchForwards = collectForwardMappings(routes);\n\n // Merge with existing forwardMap for cycle detection\n const combinedForwardMap: Record<string, string> = { ...existingForwardMap };\n\n for (const [from, to] of batchForwards) {\n combinedForwardMap[from] = to;\n }\n\n // Validate each forwardTo target exists and params are compatible\n for (const [fromRoute, targetRoute] of batchForwards) {\n validateSingleForward(fromRoute, targetRoute, routes, batchNames, tree);\n }\n\n // Check for cycles in the combined forwardMap\n for (const fromRoute of Object.keys(combinedForwardMap)) {\n resolveForwardChain(fromRoute, combinedForwardMap);\n }\n}\n\n/**\n * Registers route handlers (canActivate).\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteHandlers<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n router: Router<Dependencies>,\n): void {\n if (route.canActivate) {\n router.canActivate(route.name, route.canActivate);\n }\n}\n\n/**\n * Resolves a forwardTo chain to its final destination.\n *\n * Follows the chain of forwardTo references until reaching a route\n * that doesn't forward, or until detecting a cycle or reaching max depth.\n *\n * @param startRoute - Starting route name\n * @param forwardMap - Map of route forwards\n * @param maxDepth - Maximum chain depth (default: 100)\n * @returns Final destination route name\n * @throws {Error} If circular forwardTo is detected or chain exceeds max depth\n *\n * @example\n * ```typescript\n * // Simple chain: A → B → C\n * resolveForwardChain(\"A\", { A: \"B\", B: \"C\" }) // → \"C\"\n *\n * // Cycle detected: A → B → A\n * resolveForwardChain(\"A\", { A: \"B\", B: \"A\" }) // throws Error\n * ```\n */\nexport function resolveForwardChain(\n startRoute: string,\n forwardMap: Record<string, string>,\n maxDepth = 100,\n): string {\n const visited = new Set<string>();\n const chain: string[] = [startRoute];\n let current = startRoute;\n\n while (forwardMap[current]) {\n const next = forwardMap[current];\n\n // Cycle detection: if we've seen this route before, it's a cycle\n if (visited.has(next)) {\n const cycleStart = chain.indexOf(next);\n const cycle = [...chain.slice(cycleStart), next];\n\n throw new Error(`Circular forwardTo: ${cycle.join(\" → \")}`);\n }\n\n visited.add(current);\n chain.push(next);\n current = next;\n\n // Depth limit protection\n if (chain.length > maxDepth) {\n throw new Error(\n `forwardTo chain exceeds maximum depth (${maxDepth}): ${chain.join(\" → \")}`,\n );\n }\n }\n\n return current;\n}\n\n/**\n * Validates and caches all forwardTo chains.\n *\n * This function:\n * 1. Validates that all forwardTo targets exist in the route tree\n * 2. Detects circular forwardTo references\n * 3. Resolves all chains to their final destinations\n * 4. Caches the resolved values for O(1) runtime lookup\n *\n * @param router - Router instance\n * @throws {Error} If a forwardTo target doesn't exist or a cycle is detected\n */\nexport function validateAndCacheForwardMap<\n Dependencies extends DefaultDependencies,\n>(router: Router<Dependencies>): void {\n const { forwardMap } = getConfig(router);\n const resolvedMap: Record<string, string> = {};\n\n for (const fromRoute of Object.keys(forwardMap)) {\n // Resolve the full chain to cache the final destination\n // Note: cycles are caught in Phase 1 (validateForwardToTargets)\n resolvedMap[fromRoute] = resolveForwardChain(fromRoute, forwardMap);\n }\n\n // TODO(RFC-8): Replace with CacheManager.getInstance().setResolvedForwardMap(router, resolvedMap)\n setResolvedForwardMap(router, resolvedMap);\n}\n\n/**\n * Registers route forward configuration.\n *\n * IMPORTANT: forwardTo creates a URL alias, not a transition chain.\n * Guards (canActivate) on routes with forwardTo are NOT executed.\n * Only guards on the final destination are executed.\n *\n * This matches Vue Router and Angular Router behavior where\n * redirect routes bypass guards on the source.\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteForward<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n router: Router<Dependencies>,\n): void {\n if (route.forwardTo) {\n // Warn if route has both forwardTo and canActivate\n // canActivate will be ignored because forwardTo is an alias, not a transition\n if (route.canActivate) {\n logger.warn(\n \"real-router\",\n `Route \"${route.name}\" has both forwardTo and canActivate. ` +\n `canActivate will be ignored because forwardTo creates a redirect (industry standard). ` +\n `Move canActivate to the target route \"${route.forwardTo}\".`,\n );\n }\n\n getConfig(router).forwardMap[route.name] = route.forwardTo;\n }\n}\n\n/**\n * Registers route parameter decoders and encoders.\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteTransformers<\n Dependencies extends DefaultDependencies,\n>(route: Route<Dependencies>, router: Router<Dependencies>): void {\n const config = getConfig(router);\n\n if (route.decodeParams) {\n config.decoders[route.name] = (params: Params): Params =>\n route.decodeParams?.(params) ?? params;\n }\n\n if (route.encodeParams) {\n config.encoders[route.name] = (params: Params): Params =>\n route.encodeParams?.(params) ?? params;\n }\n}\n\n/**\n * Registers route default parameters.\n *\n * @param route - Route configuration\n * @param router - Router instance\n */\nexport function registerRouteDefaults<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n router: Router<Dependencies>,\n): void {\n if (route.defaultParams) {\n getConfig(router).defaultParams[route.name] = route.defaultParams;\n }\n}\n\n/**\n * Recursively registers all route handlers from a route definition.\n */\nexport function registerAllRouteHandlers<\n Dependencies extends DefaultDependencies,\n>(\n routes: readonly Route<Dependencies>[],\n router: Router<Dependencies>,\n parentName = \"\",\n): void {\n for (const route of routes) {\n const fullName = parentName ? `${parentName}.${route.name}` : route.name;\n const routeWithFullName = { ...route, name: fullName };\n\n registerRouteHandlers(routeWithFullName, router);\n registerRouteForward(routeWithFullName, router);\n registerRouteTransformers(routeWithFullName, router);\n registerRouteDefaults(routeWithFullName, router);\n\n if (route.children) {\n registerAllRouteHandlers(route.children, router, fullName);\n }\n }\n}\n\n/**\n * Clears configuration entries that match the predicate.\n * Helper function for route removal operations.\n *\n * @param config - Configuration object to clean\n * @param matcher - Function to test if entry should be cleared\n */\nexport function clearConfigEntries<T>(\n config: Record<string, T>,\n matcher: (key: string) => boolean,\n): void {\n for (const key of Object.keys(config)) {\n if (matcher(key)) {\n delete config[key];\n }\n }\n}\n\n// ============================================================================\n// Route Tree Helpers\n// ============================================================================\n\n/**\n * Sanitizes a route by keeping only essential properties.\n * Custom properties (meta, permissions, etc.) are removed to optimize memory\n * and ensure a clean contract. Only name, path, and children are preserved.\n *\n * @param route - Route to sanitize\n * @returns Sanitized route definition\n */\nexport function sanitizeRoute<Dependencies extends DefaultDependencies>(\n route: Route<Dependencies>,\n): RouteDefinition {\n const sanitized: RouteDefinition = {\n name: route.name,\n path: route.path,\n };\n\n if (route.children) {\n sanitized.children = route.children.map((child) => sanitizeRoute(child));\n }\n\n return sanitized;\n}\n\n/**\n * Recursively removes a route from definitions array.\n * Handles both top-level and nested routes.\n *\n * @param definitions - Route definitions array to modify\n * @param routeName - Full route name to remove\n * @param parentPrefix - Parent route prefix for recursion\n * @returns true if route was removed, false otherwise\n */\nexport function removeFromDefinitions(\n definitions: RouteDefinition[],\n routeName: string,\n parentPrefix = \"\",\n): boolean {\n for (let i = 0; i < definitions.length; i++) {\n const route = definitions[i];\n const fullName = parentPrefix\n ? `${parentPrefix}.${route.name}`\n : route.name;\n\n if (fullName === routeName) {\n definitions.splice(i, 1);\n\n return true;\n }\n\n if (\n route.children &&\n routeName.startsWith(`${fullName}.`) &&\n removeFromDefinitions(route.children, routeName, fullName)\n ) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Updates or removes a config map entry.\n * - undefined: no change\n * - null: remove entry\n * - value: set entry\n *\n * @param map - Config map to modify\n * @param name - Route name key\n * @param value - Value to set, null to remove, undefined to skip\n */\nexport function updateConfigEntry<T>(\n map: Record<string, T>,\n name: string,\n value: T | null | undefined,\n): void {\n if (value === undefined) {\n return;\n }\n\n if (value === null) {\n delete map[name];\n } else {\n map[name] = value;\n }\n}\n\n// ============================================================================\n// Higher-Order Factory Functions\n// ============================================================================\n\n/**\n * Creates a function to clear all configurations associated with a route.\n * Includes config entries (decoders, encoders, defaults, forwards)\n * and lifecycle handlers (canActivate, canDeactivate).\n *\n * @param router - Router instance\n * @returns Function that clears configurations for a route name\n */\nexport function createClearRouteConfigurations<\n Dependencies extends DefaultDependencies,\n>(router: Router<Dependencies>): (routeName: string) => void {\n return (routeName: string): void => {\n const shouldClear = (n: string): boolean =>\n n === routeName || n.startsWith(`${routeName}.`);\n\n const config = getConfig(router);\n\n // Clear config entries\n clearConfigEntries(config.decoders, shouldClear);\n clearConfigEntries(config.encoders, shouldClear);\n clearConfigEntries(config.defaultParams, shouldClear);\n clearConfigEntries(config.forwardMap, shouldClear);\n\n // Clear forwardMap entries pointing TO deleted route\n clearConfigEntries(config.forwardMap, (key) =>\n shouldClear(config.forwardMap[key]),\n );\n\n // Clear lifecycle handlers (silently - they may not exist)\n const [canDeactivateFactories, canActivateFactories] =\n router.getLifecycleFactories();\n\n for (const n of Object.keys(canActivateFactories)) {\n if (shouldClear(n)) {\n router.clearCanActivate(n, true);\n }\n }\n\n for (const n of Object.keys(canDeactivateFactories)) {\n if (shouldClear(n)) {\n router.clearCanDeactivate(n, true);\n }\n }\n };\n}\n\n/**\n * Creates a function to validate and apply forwardTo updates.\n *\n * @param forwardMap - Forward map from router config\n * @returns Function that validates and applies forwardTo\n * @throws {Error} If target doesn't exist, creates cycle, or params mismatch\n */\nexport function createApplyForwardToUpdate(\n forwardMap: Record<string, string>,\n): (\n name: string,\n toRoute: string,\n segments: readonly RouteTree[],\n tree: RouteTree,\n) => void {\n return (\n name: string,\n toRoute: string,\n segments: readonly RouteTree[],\n tree: RouteTree,\n ): void => {\n const toSegments = getSegmentsByName(tree, toRoute);\n\n if (!toSegments) {\n throw new Error(\n `[real-router] updateRoute: forwardTo target \"${toRoute}\" does not exist`,\n );\n }\n\n // Note: Self-reference cycles (name === toRoute) are caught by\n // resolveForwardChain() which runs before this function in updateRoute()\n\n const fromParams = getRequiredParams(segments);\n const toParams = getRequiredParams(toSegments);\n const missingParams = [...toParams].filter((p) => !fromParams.has(p));\n\n if (missingParams.length > 0) {\n throw new Error(\n `[real-router] updateRoute: forwardTo target \"${toRoute}\" requires params ` +\n `[${missingParams.join(\", \")}] that are not available in source route \"${name}\"`,\n );\n }\n\n forwardMap[name] = toRoute;\n };\n}\n\n/**\n * Creates a function to enrich route definitions with config data.\n *\n * @param config - Router config containing forwardMap, decoders, encoders, defaultParams\n * @param canActivateFactories - Map of canActivate factories by route name\n * @returns Recursive function that enriches RouteDefinition to full Route\n */\nexport function createEnrichRoute<Dependencies extends DefaultDependencies>(\n config: Config,\n canActivateFactories: Record<string, ActivationFnFactory<Dependencies>>,\n): (routeDef: RouteDefinition, routeName: string) => Route<Dependencies> {\n const enrichRoute = (\n routeDef: RouteDefinition,\n routeName: string,\n ): Route<Dependencies> => {\n const route: Route<Dependencies> = {\n name: routeDef.name,\n path: routeDef.path,\n };\n\n // Add forwardTo if exists\n const forwardTo = config.forwardMap[routeName];\n\n if (forwardTo) {\n route.forwardTo = forwardTo;\n }\n\n // Add defaultParams if exists\n if (routeName in config.defaultParams) {\n route.defaultParams = config.defaultParams[routeName];\n }\n\n // Add decoder if exists\n if (routeName in config.decoders) {\n route.decodeParams = config.decoders[routeName];\n }\n\n // Add encoder if exists\n if (routeName in config.encoders) {\n route.encodeParams = config.encoders[routeName];\n }\n\n // Add canActivate if exists\n if (routeName in canActivateFactories) {\n route.canActivate = canActivateFactories[routeName];\n }\n\n // Recursively enrich children\n if (routeDef.children) {\n route.children = routeDef.children.map((child) =>\n enrichRoute(child, `${routeName}.${child.name}`),\n );\n }\n\n return route;\n };\n\n return enrichRoute;\n}\n","// packages/real-router/modules/core/routes/routeQuery.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { routeTreeToDefinitions } from \"route-tree\";\nimport { isString, validateRouteName } from \"type-guards\";\n\nimport { createRouter } from \"@real-router/core\";\n\nimport { validateParams } from \"./routeConfig\";\nimport {\n getConfig,\n getResolvedForwardMap,\n getRouteTree,\n setConfig,\n setResolvedForwardMap,\n} from \"../../internals\";\nimport { getTransitionPath } from \"../../transitionPath\";\n\nimport type {\n Params,\n State,\n Router,\n Route,\n DefaultDependencies,\n} from \"core-types\";\n\n// Constants\nconst DEFAULT_ROUTE_NAME = \"\";\n\n// Cache for validated route names to skip regex validation on repeated calls\n// Key insight: validateRouteName() regex takes ~40ns, but cache lookup is ~1ns\n// This cache is module-level (shared across all router instances) since route name\n// validity is independent of router instance\nconst validatedRouteNames = new Set<string>();\n\n/**\n * Checks if all params from source exist with same values in target.\n * Extracted for cognitive complexity reduction.\n * Small function body allows V8 inlining.\n */\nfunction paramsMatch(source: Params, target: Params): boolean {\n for (const key in source) {\n if (source[key] !== target[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Checks params match, skipping keys present in skipKeys.\n */\nfunction paramsMatchExcluding(\n source: Params,\n target: Params,\n skipKeys: Params,\n): boolean {\n for (const key in source) {\n if (key in skipKeys) {\n continue;\n }\n if (source[key] !== target[key]) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Adds route query and state inspection capabilities to a router instance.\n * Handles route activity checks, route relationships, node update predicates, and cloning.\n *\n * @returns Function to enhance router with query capabilities\n */\nexport function withRouteQuery<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n /**\n * Checks if a route is currently active.\n *\n * Optimized implementation that avoids creating State objects and\n * traversing the route tree when possible.\n *\n * @param name - Route name to check\n * @param params - Route parameters to match\n * @param strictEquality - Whether to require exact match (default: false)\n * @param ignoreQueryParams - Whether to ignore query parameters (default: true)\n * @returns True if route is active, false otherwise\n * @throws {TypeError} If name is not a valid route name or params are invalid\n *\n * @example\n * // Check if specific user view is active\n * router.isActiveRoute('users.view', { id: '123' });\n */\n router.isActiveRoute = (\n name: string,\n params: Params = {},\n strictEquality = false,\n ignoreQueryParams = true,\n ): boolean => {\n // Fast path: skip regex validation for already-validated route names\n // Saves ~40ns per call (regex validation cost)\n if (!validatedRouteNames.has(name)) {\n validateRouteName(name, \"isActiveRoute\");\n validatedRouteNames.add(name);\n }\n\n validateParams(params, \"isActiveRoute\");\n\n // Validate boolean parameters (prevent truthy/falsy coercion bugs)\n // These checks are for JavaScript users who may pass non-boolean values\n /* eslint-disable @typescript-eslint/no-unnecessary-condition -- JS runtime guards */\n if (strictEquality !== undefined && typeof strictEquality !== \"boolean\") {\n throw new TypeError(\n `[router.isActiveRoute] strictEquality must be a boolean, got ${typeof strictEquality}`,\n );\n }\n if (\n ignoreQueryParams !== undefined &&\n typeof ignoreQueryParams !== \"boolean\"\n ) {\n throw new TypeError(\n `[router.isActiveRoute] ignoreQueryParams must be a boolean, got ${typeof ignoreQueryParams}`,\n );\n }\n /* eslint-enable @typescript-eslint/no-unnecessary-condition */\n\n // Warn about empty string usage (likely a bug)\n // Root node (\"\") is not considered a parent of any named route\n if (name === \"\") {\n logger.warn(\n \"real-router\",\n 'isActiveRoute(\"\") called with empty string. ' +\n \"The root node is not considered active for any named route. \" +\n \"To check if router has active state, use: router.getState() !== undefined\",\n );\n\n return false;\n }\n\n const activeState = router.getState();\n\n // Early return if no active state\n if (!activeState) {\n return false;\n }\n\n const activeName = activeState.name;\n\n // Fast path: check if routes are related before any expensive operations\n // Routes are related if: equal, or one is ancestor of the other\n if (\n activeName !== name &&\n !activeName.startsWith(`${name}.`) &&\n !name.startsWith(`${activeName}.`)\n ) {\n return false;\n }\n\n // Get defaultParams once (may be undefined at runtime)\n // Cast needed because Record<string, Params> doesn't include undefined for missing keys\n const defaultParams = getConfig(router).defaultParams[name] as\n | Params\n | undefined;\n\n // Exact match case (strictEquality or same name)\n if (strictEquality || activeName === name) {\n // Optimize: only create merged object if defaultParams exist\n const effectiveParams = defaultParams\n ? { ...defaultParams, ...params }\n : params;\n\n // Use areStatesEqual for proper param comparison\n // Create minimal state object (without buildPath - the expensive part)\n const targetState: State = {\n name,\n params: effectiveParams,\n path: \"\", // Not used for comparison\n };\n\n return router.areStatesEqual(targetState, activeState, ignoreQueryParams);\n }\n\n // Hierarchical check: activeState is a descendant of target (name)\n // At this point we know: activeName.startsWith(`${name}.`)\n // Check that all target params are present in activeState\n const activeParams = activeState.params;\n\n if (!paramsMatch(params, activeParams)) {\n return false;\n }\n\n // Check defaultParams (skip keys already in params)\n return (\n !defaultParams ||\n paramsMatchExcluding(defaultParams, activeParams, params)\n );\n };\n\n /**\n * Creates a predicate function to check if a route node should be updated.\n * Used internally by the transition system and integrations.\n *\n * @param nodeName - Route node name to check\n * @returns Predicate function for update checking\n * @throws {TypeError} If nodeName is not a string\n */\n router.shouldUpdateNode = (nodeName: string) => {\n // Validate nodeName type (can come from user code via React props)\n if (!isString(nodeName)) {\n throw new TypeError(\n `[router.shouldUpdateNode] nodeName must be a string, got ${typeof nodeName}`,\n );\n }\n // No need to validate node existence. Non-existent nodes correctly return false as they won't be in intersection, toActivate, or toDeactivate arrays\n\n return (toState: State, fromState?: State): boolean => {\n // Validate toState is state like obj\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!(toState && typeof toState === \"object\" && \"name\" in toState)) {\n throw new TypeError(\n \"[router.shouldUpdateNode] toState must be valid State object\",\n );\n }\n\n // Force update all nodes when reload option is set\n if (toState.meta?.options.reload) {\n return true;\n }\n\n // Root node should always update on initial navigation\n if (nodeName === DEFAULT_ROUTE_NAME && !fromState) {\n return true;\n }\n\n const { intersection, toActivate, toDeactivate } = getTransitionPath(\n toState,\n fromState,\n );\n\n // Update node at the boundary where paths diverge\n if (nodeName === intersection) {\n return true;\n }\n\n // Check if node is being activated\n if (toActivate.includes(nodeName)) {\n return true;\n }\n\n // Check if node is being deactivated\n return toDeactivate.includes(nodeName);\n };\n };\n\n /**\n * Creates an independent clone of this router with the same configuration.\n *\n * The clone inherits routes, options, middleware, plugins, lifecycle handlers,\n * and config (decoders, encoders, defaultParams, forwardMap), but NOT:\n * - Current state (clone starts unstarted with no active state)\n * - Event listeners/subscribers\n * - Original dependencies (must be passed explicitly)\n *\n * @param dependencies - New dependencies for the cloned router (default: empty object).\n * Original router's dependencies are NOT copied automatically.\n * To copy them: `router.clone(router.getDependencies())`\n * @returns A new independent router instance\n *\n * @example\n * ```typescript\n * // SSR: isolated router per request\n * const requestRouter = baseRouter.clone();\n * requestRouter.start(req.url);\n *\n * // Testing: fresh router with mock dependencies\n * const testRouter = router.clone({ api: mockApi });\n *\n * // Chain cloning is supported\n * const clone2 = clone1.clone();\n * ```\n *\n * @remarks\n * **Limitations:**\n *\n * 1. **Symbol-keyed dependencies are not copied.**\n * The clone uses `for...in` iteration which skips Symbol keys.\n * ```typescript\n * const sym = Symbol('secret');\n * router.clone({ [sym]: value }); // sym will be ignored\n * ```\n *\n * 2. **Functions in `defaultParams` will throw.**\n * The `Params` type excludes functions, but if bypassed via `as any`,\n * `structuredClone` will throw `DataCloneError`.\n * ```typescript\n * // TypeScript prevents this (TS2322), but if bypassed:\n * router.config.defaultParams.x = { fn: () => {} } as any;\n * router.clone(); // throws DataCloneError\n * ```\n *\n * 3. **Middleware/plugin factories are shared references.**\n * State created inside `(router) => { ... }` is isolated per router.\n * State in outer closures is shared between original and clones.\n */\n router.clone = (dependencies = {} as Dependencies): Router<Dependencies> => {\n const tree = getRouteTree(router);\n\n // Convert tree back to definitions and build cloned router\n const clonedRouter = createRouter<Dependencies>(\n routeTreeToDefinitions(tree) as Route<Dependencies>[],\n router.getOptions(),\n dependencies,\n );\n\n // Copy middleware factories\n clonedRouter.useMiddleware(...router.getMiddlewareFactories());\n\n // Copy plugin factories\n clonedRouter.usePlugin(...router.getPlugins());\n\n // Copy config with proper depth:\n // - decoders/encoders: shallow (functions can't be cloned)\n // - defaultParams: deep (may contain nested objects)\n // - forwardMap: shallow (primitive string values only)\n const originalConfig = getConfig(router);\n\n setConfig(clonedRouter, {\n decoders: { ...originalConfig.decoders },\n encoders: { ...originalConfig.encoders },\n defaultParams: structuredClone(originalConfig.defaultParams),\n forwardMap: { ...originalConfig.forwardMap },\n });\n\n // Copy resolved forward map (stored in Symbol)\n // TODO(RFC-8): Replace with CacheManager copy logic\n setResolvedForwardMap(clonedRouter, { ...getResolvedForwardMap(router) });\n\n // Copy lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n router.getLifecycleFactories();\n\n for (const name of Object.keys(canDeactivateFactories)) {\n clonedRouter.canDeactivate(name, canDeactivateFactories[name]);\n }\n\n for (const name of Object.keys(canActivateFactories)) {\n clonedRouter.canActivate(name, canActivateFactories[name]);\n }\n\n return clonedRouter;\n };\n\n return router;\n}\n","// packages/real-router/modules/core/routes/routeTree.ts\n\nimport { logger } from \"@real-router/logger\";\nimport {\n createRouteTree,\n getSegmentsByName,\n hasSegmentsByName,\n nodeToDefinition,\n validateRoute,\n} from \"route-tree\";\nimport { validateRouteName } from \"type-guards\";\n\nimport {\n createApplyForwardToUpdate,\n createClearRouteConfigurations,\n createEnrichRoute,\n getRequiredParams,\n registerAllRouteHandlers,\n removeFromDefinitions,\n resolveForwardChain,\n sanitizeRoute,\n updateConfigEntry,\n validateAndCacheForwardMap,\n validateForwardToTargets,\n validateRouteProperties,\n} from \"./routeConfig\";\nimport { ROUTE_DEFINITIONS_SYMBOL, ROOT_PATH_SYMBOL } from \"../../constants\";\nimport {\n getConfig,\n getRouteTree,\n setRouteTree,\n setResolvedForwardMap,\n} from \"../../internals\";\n\nimport type { Router, Route, DefaultDependencies } from \"core-types\";\nimport type { RouteDefinition, RouteTree } from \"route-tree\";\n\n// Constants\nconst DEFAULT_ROUTE_NAME = \"\";\n\n// =============================================================================\n// Validation Helpers (extracted to reduce cognitive complexity)\n// =============================================================================\n\n/**\n * Gets the type description for error messages.\n */\nfunction getTypeDescription(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n\n if (Array.isArray(value)) {\n return \"array\";\n }\n\n return typeof value;\n}\n\n/**\n * Validates that updates is a plain object.\n *\n * @throws {TypeError} If updates is not a plain object\n */\nfunction validateUpdatesObject(updates: unknown): void {\n if (\n updates === null ||\n typeof updates !== \"object\" ||\n Array.isArray(updates)\n ) {\n throw new TypeError(\n `[real-router] updateRoute: updates must be an object, got ${getTypeDescription(updates)}`,\n );\n }\n}\n\n/**\n * Validates that defaultParams is an object or null.\n *\n * @throws {TypeError} If defaultParams is not an object or null\n */\nfunction validateDefaultParams(defaultParams: unknown): void {\n if (\n defaultParams !== undefined &&\n defaultParams !== null &&\n (typeof defaultParams !== \"object\" || Array.isArray(defaultParams))\n ) {\n throw new TypeError(\n `[real-router] updateRoute: defaultParams must be an object or null, got ${getTypeDescription(defaultParams)}`,\n );\n }\n}\n\n/**\n * Validates a params transformer function (decodeParams/encodeParams).\n *\n * @throws {TypeError} If value is not a function, null, or is async\n */\nfunction validateParamsTransformer(\n value: unknown,\n fieldName: \"decodeParams\" | \"encodeParams\",\n): void {\n if (value === undefined || value === null) {\n return;\n }\n\n if (typeof value !== \"function\") {\n throw new TypeError(\n `[real-router] updateRoute: ${fieldName} must be a function or null, got ${typeof value}`,\n );\n }\n\n // Async functions break matchPath/buildPath (they return Promise instead of Params)\n if (value.constructor.name === \"AsyncFunction\") {\n throw new TypeError(\n `[real-router] updateRoute: ${fieldName} cannot be an async function`,\n );\n }\n}\n\n/**\n * Adds route tree management capabilities to a router instance.\n * Handles route tree construction, addition, and removal.\n *\n * @param routes - Initial routes array\n * @returns Function to enhance router with route tree capabilities\n */\nexport function withRouteTree<Dependencies extends DefaultDependencies>(\n routes: Route<Dependencies>[],\n): (router: Router<Dependencies>) => Router<Dependencies> {\n return (router: Router<Dependencies>): Router<Dependencies> => {\n /**\n * Clears all configurations associated with a route and its children.\n * Created from factory with router bound.\n */\n const clearRouteConfigurations = createClearRouteConfigurations(router);\n\n /**\n * Validates and applies forwardTo update for a route.\n * Created from factory with forwardMap bound.\n */\n const applyForwardToUpdate = createApplyForwardToUpdate(\n getConfig(router).forwardMap,\n );\n\n /**\n * @deprecated Will be removed in next version.\n * Use `forwardTo` property in route configuration instead.\n *\n * @param fromRoute - Source route name\n * @param toRoute - Target route name\n * @returns Router instance for chaining\n * @throws {Error} If target route requires parameters not available in source route\n */\n router.forward = (fromRoute, toRoute) => {\n logger.warn(\n \"router.forward\",\n \"Method is deprecated. Use `forwardTo` property in route configuration instead.\",\n );\n\n // Get route tree for validation\n const tree = getRouteTree(router);\n\n // Validate source route exists\n const fromSegments = getSegmentsByName(tree, fromRoute);\n\n if (!fromSegments) {\n throw new Error(\n `[real-router] forward: source route \"${fromRoute}\" does not exist`,\n );\n }\n\n // Validate target route exists\n const toSegments = getSegmentsByName(tree, toRoute);\n\n if (!toSegments) {\n throw new Error(\n `[real-router] forward: target route \"${toRoute}\" does not exist`,\n );\n }\n\n // Validate target route doesn't require params not in source\n const fromParams = getRequiredParams(fromSegments);\n const toParams = getRequiredParams(toSegments);\n const missingParams: string[] = [];\n\n for (const param of toParams) {\n if (!fromParams.has(param)) {\n missingParams.push(param);\n }\n }\n\n if (missingParams.length > 0) {\n throw new Error(\n `[real-router] forward: target route \"${toRoute}\" requires params ` +\n `[${missingParams.join(\", \")}] that are not available in source route \"${fromRoute}\"`,\n );\n }\n\n getConfig(router).forwardMap[fromRoute] = toRoute;\n\n // Revalidate and cache after manual forward addition\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n // Internal state: route definitions and root path\n type RouterInternal = Record<symbol, RouteDefinition[] | string>;\n const routerInternal = router as RouterInternal;\n\n // Initialize route definitions and tree\n // Sanitize routes to store only essential properties (name, path, children)\n const routeDefinitions: RouteDefinition[] = routes.map((route) =>\n sanitizeRoute(route),\n );\n\n // Initialize root path (can be changed later via setRootPath)\n routerInternal[ROOT_PATH_SYMBOL] = \"\";\n\n setRouteTree(\n router,\n createRouteTree(\n DEFAULT_ROUTE_NAME,\n routerInternal[ROOT_PATH_SYMBOL],\n routeDefinitions,\n ),\n );\n\n // Initialize resolved forward map cache\n // TODO(RFC-8): Replace with CacheManager.getInstance().setResolvedForwardMap(router, {})\n setResolvedForwardMap(router, {});\n\n // Store definitions for dynamic addition\n routerInternal[ROUTE_DEFINITIONS_SYMBOL] = routeDefinitions;\n\n // Register handlers for all routes\n registerAllRouteHandlers(routes, router);\n\n // Validate and cache forwardTo chains\n validateAndCacheForwardMap(router);\n\n /**\n * Rebuilds the route tree from given definitions.\n *\n * @param definitions - Route definitions to build from\n * @param skipValidation - Skip validation if routes are pre-validated\n */\n function rebuildTree(\n definitions: readonly RouteDefinition[],\n skipValidation = false,\n ): void {\n const rootPath = routerInternal[ROOT_PATH_SYMBOL] as string;\n\n setRouteTree(\n router,\n createRouteTree(DEFAULT_ROUTE_NAME, rootPath, definitions, {\n skipValidation,\n }),\n );\n }\n\n /**\n * Gets the current route tree.\n */\n function getTree(): RouteTree {\n return getRouteTree(router);\n }\n\n /**\n * Validates a batch of routes before adding them.\n * Checks structure, duplicates, and forwardTo targets.\n */\n function validateRouteBatch(routesToAdd: Route<Dependencies>[]): void {\n const seenNames = new Set<string>();\n const seenPathsByParent = new Map<string, Set<string>>();\n\n for (const route of routesToAdd) {\n validateRoute(\n route,\n \"addRoute\",\n getTree(),\n \"\",\n seenNames,\n seenPathsByParent,\n );\n validateRouteProperties(route, route.name);\n }\n\n validateForwardToTargets(\n routesToAdd,\n getConfig(router).forwardMap,\n getTree(),\n );\n }\n\n /**\n * Adds one or more routes to the router tree.\n * Routes are sorted immediately after addition.\n *\n * @param addedRoutes - Route or array of routes to add\n * @returns Router instance for chaining\n * @throws {TypeError} If route structure is invalid\n * @throws {Error} If route already exists or duplicate in batch\n *\n * @example\n * // Single route\n * router.addRoute({ name: 'users', path: '/users' });\n *\n * @example\n * // Multiple routes - prefer batch over loop\n * router.addRoute([\n * { name: 'users', path: '/users' },\n * { name: 'users.view', path: '/:id' }\n * ]);\n */\n router.addRoute = (addedRoutes) => {\n const routesToAdd = Array.isArray(addedRoutes)\n ? [...addedRoutes]\n : [addedRoutes];\n\n // Phase 1: Pre-validation (all routes validated BEFORE any modification)\n validateRouteBatch(routesToAdd);\n\n // Phase 2: Add to definitions and register handlers\n for (const route of routesToAdd) {\n routeDefinitions.push(sanitizeRoute(route));\n }\n\n registerAllRouteHandlers(routesToAdd, router);\n\n // Phase 3: Rebuild tree\n rebuildTree(routeDefinitions, true);\n\n // Phase 4: Validate and cache forwardTo chains\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n /**\n * Removes a route and all its children from the router.\n * Clears all associated configurations, handlers and rebuilds the tree.\n *\n * @param name - Route name to remove (supports dot notation for nested routes)\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a valid route name\n *\n * @example\n * // Remove top-level route\n * router.removeRoute('users');\n *\n * @example\n * // Remove nested route (parent remains)\n * router.removeRoute('users.edit');\n */\n router.removeRoute = (name: string): Router<Dependencies> => {\n validateRouteName(name, \"removeRoute\");\n\n // Check if trying to remove currently active route (or its parent)\n const currentState = router.getState();\n\n if (currentState) {\n const currentName = currentState.name;\n const isExactMatch = currentName === name;\n const isParentOfCurrent = currentName.startsWith(`${name}.`);\n\n if (isExactMatch || isParentOfCurrent) {\n const suffix = isExactMatch ? \"\" : ` (current: \"${currentName}\")`;\n\n logger.warn(\n \"router.removeRoute\",\n `Cannot remove route \"${name}\" — it is currently active${suffix}. Navigate away first.`,\n );\n\n return router;\n }\n }\n\n // Edge case: Warn if navigation is in progress\n // We warn but don't block because we can't determine if this specific route\n // is the navigation target. After FSM migration (RFC-2), this will be improved\n // with RouterState.TRANSITIONING that tracks the target route.\n if (router.isNavigating()) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" removed while navigation is in progress. This may cause unexpected behavior.`,\n );\n }\n\n // Try to remove from definitions\n const wasRemoved = removeFromDefinitions(routeDefinitions, name);\n\n if (!wasRemoved) {\n logger.warn(\n \"router.removeRoute\",\n `Route \"${name}\" not found. No changes made.`,\n );\n\n return router;\n }\n\n // Clear configurations for removed route\n clearRouteConfigurations(name);\n\n // Rebuild tree with updated definitions\n rebuildTree(routeDefinitions, true);\n\n // Revalidate and cache forwardTo chains after removal\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n /**\n * Clears all routes from the router.\n * Removes all route definitions, configurations, and lifecycle handlers.\n * Preserves: listeners, plugins, dependencies, options, state.\n *\n * @returns Router instance for chaining\n *\n * @example\n * // Clear all routes and add new ones\n * router.clearRoutes().addRoute([\n * { name: 'home', path: '/' },\n * { name: 'about', path: '/about' }\n * ]);\n */\n router.clearRoutes = (): Router<Dependencies> => {\n if (router.isNavigating()) {\n logger.error(\n \"router.clearRoutes\",\n \"Cannot clear routes while navigation is in progress. Wait for navigation to complete.\",\n );\n\n return router;\n }\n\n // Clear all route definitions\n routeDefinitions.length = 0;\n\n const config = getConfig(router);\n\n // Clear all config entries (for...in avoids O(K) array allocation)\n for (const key in config.decoders) {\n delete config.decoders[key];\n }\n\n for (const key in config.encoders) {\n delete config.encoders[key];\n }\n\n for (const key in config.defaultParams) {\n delete config.defaultParams[key];\n }\n\n for (const key in config.forwardMap) {\n delete config.forwardMap[key];\n }\n\n // Clear all lifecycle handlers\n const [canDeactivateFactories, canActivateFactories] =\n router.getLifecycleFactories();\n\n for (const name in canActivateFactories) {\n router.clearCanActivate(name, true);\n }\n\n for (const name in canDeactivateFactories) {\n router.clearCanDeactivate(name, true);\n }\n\n // Clear router state since all routes are removed\n router.setState(undefined);\n\n // Rebuild empty tree\n rebuildTree(routeDefinitions, true);\n\n // Clear forward cache\n validateAndCacheForwardMap(router);\n\n return router;\n };\n\n /**\n * Retrieves a route by name with all its configuration.\n * Returns the full Route object reconstructed from internal storage.\n *\n * @param name - Route name (supports dot notation for nested routes)\n * @returns Route object with all properties, or undefined if not found\n * @throws {TypeError} If name is not a valid route name\n *\n * @example\n * // Get a top-level route\n * const usersRoute = router.getRoute('users');\n *\n * @example\n * // Get a nested route\n * const profileRoute = router.getRoute('users.profile');\n */\n router.getRoute = (name: string): Route<Dependencies> | undefined => {\n validateRouteName(name, \"getRoute\");\n\n const tree = getTree();\n const segments = getSegmentsByName(tree, name);\n\n if (!segments) {\n return undefined;\n }\n\n // Get the last segment (the target route)\n // segments is guaranteed to have at least one element here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const targetNode = segments.at(-1)!;\n const definition = nodeToDefinition(targetNode);\n\n // Get lifecycle factories for enrichment\n const [, canActivateFactories] = router.getLifecycleFactories();\n\n // Create enrichRoute function with bound config and factories\n const enrichRoute = createEnrichRoute(\n getConfig(router),\n canActivateFactories,\n );\n\n return enrichRoute(definition, name);\n };\n\n /**\n * Checks if a route exists in the router.\n *\n * @param name - Route name (supports dot notation for nested routes)\n * @returns true if route exists, false otherwise\n * @throws {TypeError} If name is not a valid route name\n */\n router.hasRoute = (name: string): boolean => {\n validateRouteName(name, \"hasRoute\");\n\n const tree = getTree();\n\n return hasSegmentsByName(tree, name);\n };\n\n /**\n * Updates a route's configuration without rebuilding the route tree.\n * Only updates specified properties; unspecified properties remain unchanged.\n * Use `null` to remove a property.\n *\n * @param name - Route name (supports dot notation for nested routes)\n * @param updates - Configuration updates to apply\n * @returns Router instance for chaining\n * @throws {TypeError} If name is not a valid route name\n * @throws {ReferenceError} If route does not exist\n * @throws {Error} If forwardTo target doesn't exist or creates cycle\n *\n * @example\n * // Add forwardTo\n * router.updateRoute('old', { forwardTo: 'new' });\n *\n * @example\n * // Remove forwardTo\n * router.updateRoute('old', { forwardTo: null });\n *\n * @example\n * // Update multiple properties\n * router.updateRoute('users', {\n * defaultParams: { page: 1 },\n * canActivate: authGuardFactory\n * });\n */\n router.updateRoute = (name, updates) => {\n validateRouteName(name, \"updateRoute\");\n\n // Validate updates is a plain object (JS runtime guard)\n validateUpdatesObject(updates);\n\n const tree = getTree();\n const segments = getSegmentsByName(tree, name);\n\n if (!segments) {\n throw new ReferenceError(\n `[real-router] updateRoute: route \"${name}\" does not exist`,\n );\n }\n\n // Warn if modifying config during navigation\n // Changes apply immediately but may cause inconsistent behavior\n if (router.isNavigating()) {\n logger.error(\n \"router.updateRoute\",\n `Route \"${name}\" config modified while navigation is in progress. ` +\n \"Changes will apply immediately and may affect the current transition.\",\n );\n }\n\n const config = getConfig(router);\n\n // Cache all property values upfront to protect against mutating getters\n // This ensures consistent behavior regardless of getter side effects\n const {\n forwardTo,\n defaultParams,\n decodeParams,\n encodeParams,\n canActivate,\n } = updates;\n\n // ============================================================\n // PHASE 1: VALIDATION (all validations before any mutations)\n // This ensures atomicity - either all updates apply or none do\n // ============================================================\n\n // Validate forwardTo (check target exists and no cycles)\n if (forwardTo !== undefined && forwardTo !== null) {\n // Check for indirect cycles BEFORE mutation\n // This prevents forwardMap corruption when cycle is detected\n const testMap = {\n ...config.forwardMap,\n [name]: forwardTo,\n };\n\n resolveForwardChain(name, testMap);\n }\n\n // Validate property types\n validateDefaultParams(defaultParams);\n validateParamsTransformer(decodeParams, \"decodeParams\");\n validateParamsTransformer(encodeParams, \"encodeParams\");\n\n // ============================================================\n // PHASE 2: MUTATION (all mutations after validations pass)\n // ============================================================\n\n // Apply forwardTo\n if (forwardTo !== undefined) {\n if (forwardTo === null) {\n delete config.forwardMap[name];\n } else {\n applyForwardToUpdate(name, forwardTo, segments, tree);\n }\n\n validateAndCacheForwardMap(router);\n }\n\n // Apply config entries\n updateConfigEntry(config.defaultParams, name, defaultParams);\n updateConfigEntry(config.decoders, name, decodeParams);\n updateConfigEntry(config.encoders, name, encodeParams);\n\n // Handle canActivate (uses different API)\n if (canActivate !== undefined) {\n if (canActivate === null) {\n router.clearCanActivate(name, true);\n } else {\n router.canActivate(name, canActivate);\n }\n }\n\n return router;\n };\n\n return router;\n };\n}\n","// packages/real-router/modules/core/routes.ts\n\nimport { withRoutePath } from \"./routePath\";\nimport { withRouteQuery } from \"./routeQuery\";\nimport { withRouteTree } from \"./routeTree\";\n\nimport type { Router, Route, DefaultDependencies } from \"core-types\";\n\n/**\n * Adds comprehensive route management capabilities to a router instance.\n * Orchestrates route tree operations, path building/matching, and state queries.\n *\n * This is a composition of specialized modules:\n * - withRouteTree: Route tree construction, addition, and removal\n * - withRoutePath: URL path building and matching\n * - withRouteQuery: Route activity checks and state inspection\n *\n * @param routes - Initial routes array\n * @returns Function to enhance router with route capabilities\n */\nexport function withRoutes<Dependencies extends DefaultDependencies>(\n routes: Route<Dependencies>[],\n): (router: Router<Dependencies>) => Router<Dependencies> {\n return (router: Router<Dependencies>): Router<Dependencies> => {\n // eslint-disable-next-line unicorn/no-array-reduce\n return [withRouteTree(routes), withRoutePath, withRouteQuery].reduce(\n (r, fn) => fn(r),\n router,\n );\n };\n}\n","// packages/real-router/modules/core/state.ts\n\nimport { logger } from \"@real-router/logger\";\nimport { getSegmentsByName } from \"route-tree\";\nimport {\n isNavigationOptions,\n isParams,\n isString,\n validateState,\n getTypeDescription,\n} from \"type-guards\";\n\nimport { constants } from \"@real-router/core\";\n\nimport { freezeStateInPlace } from \"../helpers\";\nimport { getConfig, getResolvedForwardMap, getRouteTree } from \"../internals\";\nimport { createRouteState } from \"./stateBuilder\";\n\nimport type {\n BuildStateResultWithSegments,\n DefaultDependencies,\n NavigationOptions,\n Params,\n Router,\n SimpleState,\n State,\n StateMetaInput,\n} from \"core-types\";\nimport type { RouteTree, RouteTreeState, RouteTreeStateMeta } from \"route-tree\";\n\n/**\n * Extracts URL param names from RouteTreeStateMeta.\n * This is an O(segments × params) operation but avoids tree traversal.\n *\n * @param meta - RouteTreeStateMeta containing param sources\n * @returns Array of URL param names\n *\n * @internal\n */\nfunction getUrlParamsFromMeta(meta: RouteTreeStateMeta): string[] {\n const urlParams: string[] = [];\n\n // meta structure: { \"segment1\": { param1: \"url\", param2: \"query\" }, ... }\n // Optimization: use for...in instead of Object.entries to avoid array allocation\n for (const segmentName in meta) {\n const paramMap = meta[segmentName];\n\n for (const param in paramMap) {\n if (paramMap[param] === \"url\") {\n urlParams.push(param);\n }\n }\n }\n\n return urlParams;\n}\n\n/**\n * Compares two parameter values for equality.\n * Supports deep equality for arrays (common in route params like tags, ids).\n *\n * @param val1 - First value\n * @param val2 - Second value\n * @returns True if values are equal\n */\nfunction areParamValuesEqual(val1: unknown, val2: unknown): boolean {\n // Fast path: strict equality for primitives and same references\n if (val1 === val2) {\n return true;\n }\n\n // Deep equality for arrays\n if (Array.isArray(val1) && Array.isArray(val2)) {\n if (val1.length !== val2.length) {\n return false;\n }\n\n return val1.every((v, i) => areParamValuesEqual(v, val2[i]));\n }\n\n // Different types or non-equal non-arrays\n return false;\n}\n\n/**\n * Enhances router with state management capabilities.\n *\n * Provides methods for getting, setting, and comparing route states.\n * Implements frozen state caching for performance optimization.\n *\n * @param router - Router instance to enhance\n * @returns Enhanced router with state management methods\n *\n * @internal This is a router enhancement function, not meant for direct use.\n */\nexport function withState<Dependencies extends DefaultDependencies>(\n router: Router<Dependencies>,\n): Router<Dependencies> {\n // Auto-incrementing state ID for tracking navigation history\n let stateId = 0;\n // Cached frozen state - avoids structuredClone on every getState() call\n let frozenState: State | undefined = undefined;\n // Previous state before the last setState call\n let previousState: State | undefined = undefined;\n\n // Lazy accessor for route tree (set by withRoutes, which runs after withState)\n const getTree = (): RouteTree => getRouteTree(router);\n\n // Cache for urlParams to avoid repeated route tree traversal\n // Key: route name, Value: array of URL param names\n const urlParamsCache = new Map<string, string[]>();\n\n const getUrlParams = (name: string): string[] => {\n // Check cache first\n const cached = urlParamsCache.get(name);\n\n if (cached !== undefined) {\n return cached;\n }\n\n // Compute and cache\n const segments = getSegmentsByName(getTree(), name);\n\n if (!segments) {\n // Cache empty result for non-existent routes\n urlParamsCache.set(name, []);\n\n return [];\n }\n\n const result = segments.flatMap((segment) =>\n /* v8 ignore next -- @preserve segments always have parsers */\n segment.parser ? segment.parser.urlParams : [],\n );\n\n urlParamsCache.set(name, result);\n\n return result;\n };\n\n /**\n * Returns the current router state.\n *\n * The returned state is deeply frozen (immutable) for safety.\n * Returns `undefined` if the router has not been started or has been stopped.\n *\n * @template P - Type of route parameters\n * @template MP - Type of meta parameters (URL vs query param sources)\n * @returns Current frozen state or undefined\n *\n * @example\n * ```typescript\n * const state = router.getState();\n * if (state) {\n * console.log(state.name, state.params);\n * }\n * ```\n */\n router.getState = <P extends Params = Params, MP extends Params = Params>():\n | State<P, MP>\n | undefined => {\n return frozenState as State<P, MP> | undefined;\n };\n\n /**\n * Sets the current router state.\n *\n * The state is deeply frozen before storage to ensure immutability.\n * The previous state is preserved and accessible via `getPreviousState()`.\n *\n * @param state - New state to set, or undefined to clear\n *\n * @remarks\n * This is primarily used internally by the navigation system.\n * Direct usage should be rare and careful.\n *\n * @example\n * ```typescript\n * // Used internally after successful navigation\n * router.setState(newState);\n *\n * // Clear state (e.g., on router.stop())\n * router.setState(undefined);\n * ```\n */\n router.setState = (state: State | undefined) => {\n // Validate state structure if provided\n if (state !== undefined) {\n validateState(state, \"router.setState\");\n }\n\n // Preserve current state as previous before updating\n previousState = frozenState;\n // If state is already frozen (from makeState()), use it directly.\n // For external states, freeze in place without cloning.\n // This allows Proxy states and avoids structuredClone overhead.\n if (!state) {\n frozenState = undefined;\n } else if (Object.isFrozen(state)) {\n // State is already frozen (typically from makeState)\n frozenState = state;\n } else {\n // External state - freeze in place without cloning.\n // Uses Object.freeze recursively, allowing Proxy objects and\n // preserving Symbol/function values in meta.options.\n frozenState = freezeStateInPlace(state);\n }\n };\n\n /**\n * Returns the previous router state (before the last navigation).\n *\n * Useful for implementing \"back\" functionality or transition animations.\n * The returned state is deeply frozen (immutable).\n *\n * @template P - Type of route parameters\n * @template MP - Type of meta parameters\n * @returns Previous frozen state or undefined if no previous navigation\n *\n * @example\n * ```typescript\n * router.navigate('users');\n * router.navigate('settings');\n *\n * const prev = router.getPreviousState();\n * console.log(prev?.name); // 'users'\n * ```\n */\n router.getPreviousState = <\n P extends Params = Params,\n MP extends Params = Params,\n >(): State<P, MP> | undefined => {\n return previousState as State<P, MP> | undefined;\n };\n\n /**\n * Creates a route state object.\n *\n * @template P - Type of route parameters. MUST include all properties from\n * route.defaultParams for proper type safety.\n * @template MP - Type of meta parameters (URL params)\n *\n * @param name - Route name\n * @param params - Route parameters (merged with defaultParams)\n * @param path - URL path (auto-built if not provided)\n * @param meta - State metadata\n * @param forceId - Force specific state ID\n * @returns Route state object\n *\n * @remarks\n * **Type Contract:**\n * The `params` result includes properties from `route.defaultParams`.\n * For correct typing, ensure that `P` includes all defaultParams properties:\n *\n * @example\n * ```typescript\n * // Route definition\n * { name: \"users\", path: \"/users\", defaultParams: { page: 1, limit: 10 } }\n *\n * // Correct usage — P includes defaultParams properties\n * type UsersParams = { page: number; limit: number; filter?: string };\n * router.makeState<UsersParams>('users', { page: 2, limit: 20 });\n *\n * // Incorrect usage — P missing defaultParams properties\n * type BadParams = { filter: string }; // Missing page, limit!\n * router.makeState<BadParams>('users', { filter: 'active' });\n * // Runtime: state.params = { page: 1, limit: 10, filter: 'active' }\n * // TypeScript: state.params = { filter: 'active' } — type mismatch!\n * ```\n */\n router.makeState = <P extends Params = Params, MP extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: StateMetaInput<MP>,\n forceId?: number,\n ): State<P, MP> => {\n // Validate name is a string\n if (!isString(name)) {\n throw new TypeError(\n `[router.makeState] Invalid name: ${getTypeDescription(name)}. Expected string.`,\n );\n }\n\n // Validate params if provided\n if (params !== undefined && !isParams(params)) {\n throw new TypeError(\n `[router.makeState] Invalid params: ${getTypeDescription(params)}. Expected plain object.`,\n );\n }\n\n // Validate path if provided\n if (path !== undefined && !isString(path)) {\n throw new TypeError(\n `[router.makeState] Invalid path: ${getTypeDescription(path)}. Expected string.`,\n );\n }\n\n // Validate forceId if provided\n if (forceId !== undefined && typeof forceId !== \"number\") {\n throw new TypeError(\n `[router.makeState] Invalid forceId: ${getTypeDescription(forceId)}. Expected number.`,\n );\n }\n\n const madeMeta = meta\n ? {\n ...meta,\n id: forceId ?? ++stateId,\n params: meta.params,\n options: meta.options,\n redirected: meta.redirected,\n }\n : undefined;\n\n // Optimization: avoid spreading when no defaultParams exist\n const routerDefaultParams = getConfig(router).defaultParams;\n const hasDefaultParams = Object.hasOwn(routerDefaultParams, name);\n // Contract: P MUST include all properties from defaultParams[name]\n // Note: always spread params when provided to handle Proxy objects correctly\n let mergedParams: P;\n\n if (hasDefaultParams) {\n mergedParams = { ...routerDefaultParams[name], ...params } as P;\n } else if (params) {\n mergedParams = { ...params };\n } else {\n mergedParams = {} as P;\n }\n\n const state: State<P, MP> = {\n name,\n params: mergedParams,\n path: path ?? router.buildPath(name, params),\n // write guard is meta\n meta: madeMeta,\n };\n\n // Freeze state immediately after creation for immutability guarantee.\n // This eliminates need for deepFreezeState in invokeEventListeners.\n return freezeStateInPlace(state);\n };\n\n /**\n * Creates a state for an unmatched (404) route.\n *\n * Used when no route matches the requested path.\n * The state name is set to `constants.UNKNOWN_ROUTE` (\"@@router/UNKNOWN_ROUTE\").\n *\n * @param path - The unmatched URL path\n * @param options - Optional navigation options (reload, replace, etc.)\n * @returns State object representing the unknown route\n *\n * @example\n * ```typescript\n * const notFound = router.makeNotFoundState('/non-existent-page');\n * // { name: '@@router/UNKNOWN_ROUTE', params: { path: '/non-existent-page' }, ... }\n * ```\n */\n router.makeNotFoundState = (\n path: string,\n options?: NavigationOptions,\n ): State => {\n // Validate path\n if (!isString(path)) {\n throw new TypeError(\n `[router.makeNotFoundState] Invalid path: ${getTypeDescription(path)}. Expected string.`,\n );\n }\n\n // Validate options if provided\n if (options !== undefined && !isNavigationOptions(options)) {\n throw new TypeError(\n `[router.makeNotFoundState] Invalid options: ${getTypeDescription(options)}. Expected NavigationOptions object.`,\n );\n }\n\n return router.makeState<{ path: string }>(\n constants.UNKNOWN_ROUTE,\n { path },\n path,\n options\n ? {\n options,\n params: {},\n redirected: false,\n }\n : undefined,\n );\n };\n\n /**\n * Compares two states for equality.\n *\n * By default, only URL path parameters are compared (query params ignored).\n * This matches typical navigation behavior where query params don't trigger\n * route change events.\n *\n * **Precondition:** States must be valid State objects (created via makeState, buildState, etc.).\n * No runtime validation is performed for performance reasons.\n *\n * @param state1 - First state to compare\n * @param state2 - Second state to compare\n * @param ignoreQueryParams - If true (default), only compare URL path params\n * @returns True if states are considered equal\n *\n * @example\n * ```typescript\n * // Same route, different query params — considered equal by default\n * router.areStatesEqual(\n * { name: 'users', params: { page: '1' } },\n * { name: 'users', params: { page: '2' } }\n * ); // true (page is a query param)\n *\n * // Compare all params including query params\n * router.areStatesEqual(state1, state2, false);\n * ```\n */\n router.areStatesEqual = (\n state1: State | null | undefined,\n state2: State | null | undefined,\n ignoreQueryParams = true,\n ): boolean => {\n // Handle null/undefined cases: both falsy = equal, one falsy = not equal\n if (!state1 || !state2) {\n return !!state1 === !!state2;\n }\n\n // No runtime validation for performance — states are validated at creation time\n\n // Different route names = definitely not equal\n if (state1.name !== state2.name) {\n return false;\n }\n\n // When ignoring query params, only compare URL path parameters\n // Optimization: use meta.params if available (avoids tree traversal)\n // Note: meta.params is RouteTreeStateMeta, not route params\n if (ignoreQueryParams) {\n // Try to get URL params from state meta (O(segments × params) but no tree lookup)\n // State meta is available when state was created via buildStateWithSegments/makeState\n const stateMeta = (state1.meta?.params ?? state2.meta?.params) as\n | RouteTreeStateMeta\n | undefined;\n\n const urlParams = stateMeta\n ? getUrlParamsFromMeta(stateMeta)\n : getUrlParams(state1.name);\n\n return urlParams.every((param) =>\n areParamValuesEqual(state1.params[param], state2.params[param]),\n );\n }\n\n // Full comparison: check all params from both states\n // Must verify BOTH:\n // 1. Same keys in both objects (not just same length)\n // 2. Same values for each key (with deep equality for arrays)\n const state1Keys = Object.keys(state1.params);\n const state2Keys = Object.keys(state2.params);\n\n // Different number of keys = not equal\n if (state1Keys.length !== state2Keys.length) {\n return false;\n }\n\n // Check that state2 has all keys from state1 AND values are equal\n // This also implicitly checks state1 has all keys from state2\n // (since lengths are equal, if all state1 keys exist in state2, they must be the same set)\n return state1Keys.every(\n (param) =>\n param in state2.params &&\n areParamValuesEqual(state1.params[param], state2.params[param]),\n );\n };\n\n /**\n * Checks if childState is a descendant of parentState in the route hierarchy.\n *\n * @deprecated This method will be removed in the next major version.\n * Use `router.isActiveRoute()` instead for most use cases.\n *\n * @example\n * ```typescript\n * // Instead of:\n * router.areStatesDescendants(parentState, childState);\n *\n * // Use isActiveRoute to check against current state:\n * router.isActiveRoute(parentState.name, parentState.params);\n * ```\n *\n * @param parentState - Potential parent state\n * @param childState - Potential child state\n * @returns True if childState is a descendant of parentState\n */\n router.areStatesDescendants = (\n parentState: State,\n childState: State,\n ): boolean => {\n // Validate states\n validateState(parentState, \"areStatesDescendants\");\n validateState(childState, \"areStatesDescendants\");\n\n logger.warn(\n \"real-router\",\n \"areStatesDescendants is deprecated and will be removed in the next major version. \" +\n \"Use router.isActiveRoute() instead.\",\n );\n\n // Check if childState.name starts with \"parentState.name.\"\n // Using startsWith instead of regex to avoid ReDoS and improve performance\n const parentPrefix = `${parentState.name}.`;\n\n if (!childState.name.startsWith(parentPrefix)) {\n return false;\n }\n\n // If child state name extends parent state name, and all parent state params\n // are in child state params (with deep equality for arrays).\n return Object.keys(parentState.params).every((p) =>\n areParamValuesEqual(parentState.params[p], childState.params[p]),\n );\n };\n\n /**\n * Resolves route forwarding and merges defaultParams.\n *\n * @template P - Type of route parameters. MUST include all properties from\n * defaultParams of both source route and forwarded route.\n *\n * @param routeName - Original route name\n * @param routeParams - Route parameters\n * @returns Resolved route name and merged parameters\n *\n * @remarks\n * **Type Contract:**\n * When using forwardTo, defaultParams from BOTH routes are merged:\n * 1. defaultParams[originalRoute]\n * 2. defaultParams[forwardedRoute]\n * 3. provided routeParams\n *\n * Ensure P includes properties from all sources.\n *\n * @example\n * ```typescript\n * // Route definitions\n * { name: \"old-users\", path: \"/old-users\", forwardTo: \"users\" }\n * { name: \"users\", path: \"/users\", defaultParams: { page: 1 } }\n *\n * router.forwardState(\"old-users\", { filter: \"active\" });\n * // Returns: { name: \"users\", params: { page: 1, filter: \"active\" } }\n * ```\n */\n router.forwardState = <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ): SimpleState<P> => {\n // Validate routeName is a string\n if (!isString(routeName)) {\n throw new TypeError(\n `[router.forwardState] Invalid routeName: ${getTypeDescription(routeName)}. Expected string.`,\n );\n }\n\n // Validate params\n if (!isParams(routeParams)) {\n throw new TypeError(\n `[router.forwardState] Invalid routeParams: ${getTypeDescription(routeParams)}. Expected plain object.`,\n );\n }\n\n // Use cached resolved forwardTo chain (O(1) lookup)\n // TODO(RFC-8): Replace with CacheManager.getInstance().getForwardTarget(router, routeName)\n const resolvedMap = getResolvedForwardMap(router);\n const name = resolvedMap[routeName] ?? routeName;\n const { defaultParams } = getConfig(router);\n\n // Contract: P MUST include all properties from defaultParams of both routes\n // Optimization: avoid spreading when no defaultParams exist\n const hasRouteDefaults = Object.hasOwn(defaultParams, routeName);\n const hasNameDefaults = Object.hasOwn(defaultParams, name);\n\n // Type assertion needed: merged params satisfy P contract per JSDoc\n let params: P;\n\n if (hasRouteDefaults && hasNameDefaults) {\n // Both routes have defaults - need all three spreads\n params = {\n ...defaultParams[routeName],\n ...defaultParams[name],\n ...routeParams,\n } as P;\n } else if (hasRouteDefaults) {\n // Only source route has defaults\n params = { ...defaultParams[routeName], ...routeParams } as P;\n } else if (hasNameDefaults) {\n // Only target route has defaults\n params = { ...defaultParams[name], ...routeParams } as P;\n } else {\n // No defaults - use routeParams directly\n params = routeParams;\n }\n\n return {\n name,\n params,\n };\n };\n\n /**\n * Builds a route tree state from route name and parameters.\n *\n * Resolves forwarding, applies defaultParams, and creates a state\n * with segment metadata. Returns undefined if the route doesn't exist.\n *\n * @template P - Type of route parameters\n * @param routeName - Route name (may be forwarded to another route)\n * @param routeParams - Route parameters\n * @returns Route tree state with segment info, or undefined if route not found\n *\n * @example\n * ```typescript\n * const state = router.buildState('users.view', { id: '123' });\n * if (state) {\n * console.log(state.name, state.params, state.meta);\n * }\n * ```\n */\n router.buildState = <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ): RouteTreeState<P> | undefined => {\n // Validate routeName is a string\n if (!isString(routeName)) {\n throw new TypeError(\n `[router.buildState] Invalid routeName: ${getTypeDescription(routeName)}. Expected string.`,\n );\n }\n\n // Validate params\n if (!isParams(routeParams)) {\n throw new TypeError(\n `[router.buildState] Invalid routeParams: ${getTypeDescription(routeParams)}. Expected plain object.`,\n );\n }\n\n // Resolve forwarding and merge defaultParams\n const { name, params } = router.forwardState(routeName, routeParams);\n\n // Get route segments from the tree\n const segments = getSegmentsByName(getTree(), name);\n\n if (!segments) {\n return undefined;\n }\n\n // Build state with segment metadata (URL vs query param sources)\n return createRouteState({ segments, params }, name);\n };\n\n /**\n * Builds state with segments for internal use.\n * Avoids duplicate getSegmentsByName call when path building is needed.\n *\n * @internal\n */\n router.buildStateWithSegments = <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ): BuildStateResultWithSegments<P> | undefined => {\n // Validate routeName is a string\n if (!isString(routeName)) {\n throw new TypeError(\n `[router.buildStateWithSegments] Invalid routeName: ${getTypeDescription(routeName)}. Expected string.`,\n );\n }\n\n // Validate params\n if (!isParams(routeParams)) {\n throw new TypeError(\n `[router.buildStateWithSegments] Invalid routeParams: ${getTypeDescription(routeParams)}. Expected plain object.`,\n );\n }\n\n // Resolve forwarding and merge defaultParams\n const { name, params } = router.forwardState(routeName, routeParams);\n\n // Get route segments from the tree\n const segments = getSegmentsByName(getTree(), name);\n\n if (!segments) {\n return undefined;\n }\n\n // Build state with segment metadata (URL vs query param sources)\n const state = createRouteState<P>({ segments, params }, name);\n\n return { state, segments };\n };\n\n return router;\n}\n","// packages/real-router/modules/typeGuards.ts\n\n/**\n * Re-export common type guards from centralized type-guards package\n */\nimport type { LoggerConfig, LogLevelConfig } from \"@real-router/logger\";\n\nexport {\n isObjKey,\n isString,\n isState,\n isParams,\n isNavigationOptions,\n isPromise,\n isBoolean,\n validateRouteName,\n} from \"type-guards\";\n\n/**\n * RealRouter-specific type guards for logger configuration\n */\n\nconst VALID_LEVELS_SET = new Set<string>([\"all\", \"warn-error\", \"error-only\"]);\n\nfunction isValidLevel(value: unknown): value is LogLevelConfig {\n return typeof value === \"string\" && VALID_LEVELS_SET.has(value);\n}\n\nfunction formatValue(value: unknown): string {\n if (typeof value === \"string\") {\n return `\"${value}\"`;\n }\n if (typeof value === \"object\") {\n return JSON.stringify(value);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n return String(value);\n}\n\nexport function isLoggerConfig(config: unknown): config is LoggerConfig {\n if (typeof config !== \"object\" || config === null) {\n throw new TypeError(\"Logger config must be an object\");\n }\n\n const obj = config;\n\n // Check for unknown properties\n for (const key of Object.keys(obj)) {\n if (key !== \"level\" && key !== \"callback\") {\n throw new TypeError(`Unknown logger config property: \"${key}\"`);\n }\n }\n\n // Validate level if present\n if (\"level\" in obj && obj.level !== undefined && !isValidLevel(obj.level)) {\n throw new TypeError(\n `Invalid logger level: ${formatValue(obj.level)}. Expected: \"all\" | \"warn-error\" | \"error-only\"`,\n );\n }\n\n // Validate callback if present\n if (\n \"callback\" in obj &&\n obj.callback !== undefined &&\n typeof obj.callback !== \"function\"\n ) {\n throw new TypeError(\n `Logger callback must be a function, got ${typeof obj.callback}`,\n );\n }\n\n return true;\n}\n","// packages/real-router/modules/createRouter.ts\n\nimport { logger } from \"@real-router/logger\";\n\nimport { CONFIG_SYMBOL } from \"./constants\";\nimport { withDependencies } from \"./core/dependencies\";\nimport { withMiddleware } from \"./core/middleware\";\nimport { withNavigation } from \"./core/navigation\";\nimport { withObservability } from \"./core/observable\";\nimport { withOptions } from \"./core/options\";\nimport { withPlugins } from \"./core/plugins\";\nimport { withRouteLifecycle } from \"./core/routeLifecycle\";\nimport { withRouterLifecycle } from \"./core/routerLifecycle\";\nimport { withRoutes } from \"./core/routes\";\nimport { withState } from \"./core/state\";\nimport { isLoggerConfig } from \"./typeGuards\";\n\nimport type {\n Config,\n DefaultDependencies,\n Options,\n Route,\n Router,\n} from \"core-types\";\n\ntype Enhancer<Dependencies extends DefaultDependencies = DefaultDependencies> =\n (router: Router<Dependencies>) => Router<Dependencies>;\n\nconst pipe =\n <Dependencies extends DefaultDependencies = DefaultDependencies>(\n ...fns: Enhancer<Dependencies>[]\n ) =>\n (arg: Router<Dependencies>): Router<Dependencies> =>\n // eslint-disable-next-line unicorn/no-array-reduce\n fns.reduce((prev: Router<Dependencies>, fn) => fn(prev), arg);\n\n/**\n * Creates a new router instance.\n */\nexport const createRouter = <\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: Route<Dependencies>[] = [],\n options: Partial<Options> = {},\n dependencies: Dependencies = {} as Dependencies,\n): Router<Dependencies> => {\n if (options.logger && isLoggerConfig(options.logger)) {\n logger.configure(options.logger);\n\n delete options.logger;\n }\n\n const config: Config = {\n decoders: {},\n encoders: {},\n defaultParams: {},\n forwardMap: {},\n };\n\n const uninitializedRouter = {\n [CONFIG_SYMBOL]: config,\n };\n\n return pipe<Dependencies>(\n withOptions(options),\n withDependencies(dependencies),\n withObservability,\n withState,\n withRouterLifecycle,\n withRouteLifecycle,\n withNavigation,\n withPlugins,\n withMiddleware,\n withRoutes(routes),\n )(uninitializedRouter as unknown as Router<Dependencies>);\n};\n"]}