@real-router/core 0.42.0 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -4
- package/dist/cjs/Router-BAks0PFv.js +6 -0
- package/dist/cjs/Router-BAks0PFv.js.map +1 -0
- package/dist/cjs/{Router-B2tmtNiM.d.ts → Router-Dh1xgFLI.d.ts} +67 -9
- package/dist/cjs/RouterError-AQUx-VLW.js +2 -0
- package/dist/cjs/RouterError-AQUx-VLW.js.map +1 -0
- package/dist/cjs/api.d.ts +1 -1
- package/dist/cjs/api.js +1 -1
- package/dist/cjs/{getPluginApi-BXrM_Nwv.js → getPluginApi-1VcDVGjf.js} +2 -2
- package/dist/cjs/{getPluginApi-BXrM_Nwv.js.map → getPluginApi-1VcDVGjf.js.map} +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/utils.js +1 -1
- package/dist/cjs/validation.d.ts +1 -1
- package/dist/esm/{Router-4JRfQLMM.d.mts → Router-BPkXwb1J.d.mts} +67 -9
- package/dist/esm/Router-C3BXH7z8.mjs +6 -0
- package/dist/esm/Router-C3BXH7z8.mjs.map +1 -0
- package/dist/esm/RouterError-BOUkCIgf.mjs +2 -0
- package/dist/esm/RouterError-BOUkCIgf.mjs.map +1 -0
- package/dist/esm/api.d.mts +1 -1
- package/dist/esm/api.mjs +1 -1
- package/dist/esm/{getPluginApi-D0bBPuLp.mjs → getPluginApi-BvOUPp3g.mjs} +2 -2
- package/dist/esm/{getPluginApi-D0bBPuLp.mjs.map → getPluginApi-BvOUPp3g.mjs.map} +1 -1
- package/dist/esm/index.d.mts +1 -1
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/utils.mjs +1 -1
- package/dist/esm/validation.d.mts +1 -1
- package/package.json +2 -2
- package/src/Router.ts +16 -2
- package/src/constants.ts +2 -0
- package/src/fsm/routerFSM.ts +17 -7
- package/src/getNavigator.ts +3 -1
- package/src/namespaces/EventBusNamespace/EventBusNamespace.ts +61 -7
- package/src/namespaces/NavigationNamespace/NavigationNamespace.ts +28 -10
- package/src/namespaces/NavigationNamespace/transition/guardPhase.ts +7 -0
- package/src/namespaces/NavigationNamespace/types.ts +3 -0
- package/src/namespaces/OptionsNamespace/constants.ts +3 -6
- package/src/namespaces/PluginsNamespace/constants.ts +2 -0
- package/src/namespaces/RouterLifecycleNamespace/RouterLifecycleNamespace.ts +1 -1
- package/src/types.ts +2 -1
- package/src/wiring/RouterWiringBuilder.ts +4 -1
- package/dist/cjs/Router-CVNR-dug.js +0 -6
- package/dist/cjs/Router-CVNR-dug.js.map +0 -1
- package/dist/cjs/RouterError-BkgjTHQg.js +0 -2
- package/dist/cjs/RouterError-BkgjTHQg.js.map +0 -1
- package/dist/esm/Router-C_k70gHi.mjs +0 -6
- package/dist/esm/Router-C_k70gHi.mjs.map +0 -1
- package/dist/esm/RouterError-D0RlQE_5.mjs +0 -2
- package/dist/esm/RouterError-D0RlQE_5.mjs.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=Object.freeze({ROUTER_NOT_STARTED:`NOT_STARTED`,NO_START_PATH_OR_STATE:`NO_START_PATH_OR_STATE`,ROUTER_ALREADY_STARTED:`ALREADY_STARTED`,ROUTE_NOT_FOUND:`ROUTE_NOT_FOUND`,SAME_STATES:`SAME_STATES`,CANNOT_DEACTIVATE:`CANNOT_DEACTIVATE`,CANNOT_ACTIVATE:`CANNOT_ACTIVATE`,TRANSITION_ERR:`TRANSITION_ERR`,TRANSITION_CANCELLED:`CANCELLED`,ROUTER_DISPOSED:`DISPOSED`,PLUGIN_CONFLICT:`PLUGIN_CONFLICT`}),t=`@@router/UNKNOWN_ROUTE`,n={UNKNOWN_ROUTE:t},r={ROUTER_START:`onStart`,ROUTER_STOP:`onStop`,TRANSITION_START:`onTransitionStart`,TRANSITION_CANCEL:`onTransitionCancel`,TRANSITION_SUCCESS:`onTransitionSuccess`,TRANSITION_ERROR:`onTransitionError`},i={ROUTER_START:`$start`,ROUTER_STOP:`$stop`,TRANSITION_START:`$$start`,TRANSITION_CANCEL:`$$cancel`,TRANSITION_SUCCESS:`$$success`,TRANSITION_ERROR:`$$error`},a={maxDependencies:100,maxPlugins:50,maxListeners:1e4,warnListeners:1e3,maxEventDepth:5,maxLifecycleHandlers:200},o=Object.freeze({});function s(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.name==`string`&&typeof t.path==`string`&&typeof t.params==`object`&&t.params!==null}function c(e){if(!e)return e;if(!s(e))throw TypeError(`[deepFreezeState] Expected valid State object, got: ${typeof e}`);let t=structuredClone(e),n=new WeakSet;function r(e){if(!(typeof e!=`object`||!e)&&!n.has(e))if(n.add(e),Object.freeze(e),Array.isArray(e))for(let t of e)r(t);else for(let t in e)r(e[t])}return r(t),t}const l=new WeakSet;function u(e){if(!(typeof e!=`object`||!e)&&!Object.isFrozen(e))if(Object.freeze(e),Array.isArray(e))for(let t of e)u(t);else for(let t in e)u(e[t])}function d(e){return!e||l.has(e)?e:(u(e),l.add(e),e)}function f(e={}){return{...a,...e}}const p=new Set(Object.values(e)),m=new Set([`code`,`segment`,`path`,`redirect`]),h=new Set([`setCode`,`setErrorInstance`,`setAdditionalFields`,`hasField`,`getField`,`toJSON`]);var g=class extends Error{segment;path;redirect;code;constructor(e,{message:t,segment:n,path:r,redirect:i,...a}={}){super(t??e),this.code=e,this.segment=n,this.path=r,this.redirect=i?c(i):void 0;for(let[e,t]of Object.entries(a)){if(m.has(e))throw TypeError(`[RouterError] Cannot set reserved property "${e}"`);h.has(e)||(this[e]=t)}}setCode(e){this.code=e,p.has(this.message)&&(this.message=e)}setErrorInstance(e){if(!e)throw TypeError(`[RouterError.setErrorInstance] err parameter is required and must be an Error instance`);this.message=e.message,this.cause=e.cause,this.stack=e.stack??``}setAdditionalFields(e){for(let[t,n]of Object.entries(e)){if(m.has(t))throw TypeError(`[RouterError.setAdditionalFields] Cannot set reserved property "${t}"`);h.has(t)||(this[t]=n)}}hasField(e){return e in this}getField(e){return this[e]}toJSON(){let e={code:this.code,message:this.message};this.segment!==void 0&&(e.segment=this.segment),this.path!==void 0&&(e.path=this.path),this.redirect!==void 0&&(e.redirect=this.redirect);let t=new Set([`code`,`message`,`segment`,`path`,`redirect`,`stack`]);for(let n in this)Object.hasOwn(this,n)&&!t.has(n)&&(e[n]=this[n]);return e}};export{o as a,e as c,a as i,i as l,f as n,t as o,d as r,n as s,g as t,r as u};
|
|
2
|
-
//# sourceMappingURL=RouterError-D0RlQE_5.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"RouterError-D0RlQE_5.mjs","names":[],"sources":["../../src/constants.ts","../../src/helpers.ts","../../src/RouterError.ts"],"sourcesContent":["// packages/core/src/constants.ts\n\nimport type {\n EventToNameMap,\n EventToPluginMap,\n ErrorCodeToValueMap,\n ErrorCodeKeys,\n ErrorCodeValues,\n} from \"@real-router/types\";\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 ROUTER_DISPOSED: \"DISPOSED\", // Router has been disposed\n PLUGIN_CONFLICT: \"PLUGIN_CONFLICT\", // Plugin tried to extend router with already-existing property\n});\n\n/**\n * General router constants.\n * Special route names and identifiers.\n */\nexport const UNKNOWN_ROUTE = \"@@router/UNKNOWN_ROUTE\";\n\nexport const constants: Constants = {\n UNKNOWN_ROUTE,\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\nexport const DEFAULT_LIMITS = {\n maxDependencies: 100,\n maxPlugins: 50,\n maxListeners: 10_000,\n warnListeners: 1000,\n maxEventDepth: 5,\n maxLifecycleHandlers: 200,\n} as const;\n\nexport const EMPTY_PARAMS: Readonly<Record<string, never>> = Object.freeze({});\n","// packages/core/src/helpers.ts\n\nimport { DEFAULT_LIMITS } from \"./constants\";\n\nimport type { Limits } from \"./types\";\nimport type { State, LimitsConfig } from \"@real-router/types\";\n\n// =============================================================================\n// State Helpers\n// =============================================================================\n\n/**\n * Structural type guard for State object.\n * Only checks required fields exist with correct types.\n * Does NOT validate params serializability (allows circular refs).\n *\n * Use `isState` from type-guards for full validation (serializable params).\n * Use this for internal operations like deepFreezeState that handle any object structure.\n *\n * @param value - Value to check\n * @returns true if value has State structure\n * @internal\n */\nfunction isStateStructural(value: unknown): value is State {\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 (structural check, allows circular refs)\n if (!isStateStructural(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 // Iterate without Object.values() allocation\n if (Array.isArray(obj)) {\n for (const item of obj) {\n freezeClonedRecursive(item);\n }\n } else {\n for (const key in obj) {\n freezeClonedRecursive((obj as Record<string, unknown>)[key]);\n }\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 freezeRecursive(state);\n\n // Mark root as processed for future calls\n frozenRoots.add(state);\n\n return state;\n}\n\n/**\n * Merges user limits with defaults.\n * Returns frozen object for immutability.\n */\nexport function createLimits(userLimits: Partial<LimitsConfig> = {}): Limits {\n return { ...DEFAULT_LIMITS, ...userLimits };\n}\n","// packages/core/src/RouterError.ts\n\nimport { errorCodes } from \"./constants\";\nimport { deepFreezeState } from \"./helpers\";\n\nimport type { State } from \"@real-router/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"],"mappings":"AAyBA,MAAa,EAAkC,OAAO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