@real-router/core 0.80.0 → 0.82.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.
Files changed (179) hide show
  1. package/README.md +68 -55
  2. package/dist/cjs/Router-CCmcEi-S.js +2 -0
  3. package/dist/cjs/Router-CCmcEi-S.js.map +1 -0
  4. package/dist/cjs/Router.d.ts +7 -6
  5. package/dist/cjs/Router.d.ts.map +1 -1
  6. package/dist/cjs/Router.js +1 -1
  7. package/dist/cjs/Router.js.map +1 -1
  8. package/dist/cjs/api/getPluginApi.d.ts.map +1 -1
  9. package/dist/cjs/api/getPluginApi.js +1 -1
  10. package/dist/cjs/api/getPluginApi.js.map +1 -1
  11. package/dist/cjs/api/getRoutesApi.d.ts.map +1 -1
  12. package/dist/cjs/api/getRoutesApi.js +1 -1
  13. package/dist/cjs/api/getRoutesApi.js.map +1 -1
  14. package/dist/cjs/api.js +2 -1
  15. package/dist/cjs/api.js.map +1 -1
  16. package/dist/cjs/buildParamMeta-0m11OIJS.js +2 -0
  17. package/dist/cjs/buildParamMeta-0m11OIJS.js.map +1 -0
  18. package/dist/cjs/channels/defaults.js +2 -0
  19. package/dist/cjs/channels/defaults.js.map +1 -0
  20. package/dist/cjs/channels/guard.js +2 -0
  21. package/dist/cjs/channels/guard.js.map +1 -0
  22. package/dist/cjs/channels/modeGate.js +2 -0
  23. package/dist/cjs/channels/modeGate.js.map +1 -0
  24. package/dist/cjs/constants.d.ts.map +1 -1
  25. package/dist/cjs/constants.js +1 -1
  26. package/dist/cjs/constants.js.map +1 -1
  27. package/dist/cjs/createRouter.d.ts +1 -1
  28. package/dist/cjs/createRouter.d.ts.map +1 -1
  29. package/dist/cjs/createRouter.js.map +1 -1
  30. package/dist/cjs/engine/builder/buildTree.js +1 -1
  31. package/dist/cjs/engine/builder/buildTree.js.map +1 -1
  32. package/dist/cjs/engine/path-matcher/SegmentMatcher.d.ts +14 -1
  33. package/dist/cjs/engine/path-matcher/SegmentMatcher.d.ts.map +1 -1
  34. package/dist/cjs/engine/path-matcher/SegmentMatcher.js +1 -1
  35. package/dist/cjs/engine/path-matcher/SegmentMatcher.js.map +1 -1
  36. package/dist/cjs/engine/path-matcher/registration/buildParts.js +1 -1
  37. package/dist/cjs/engine/path-matcher/registration/buildParts.js.map +1 -1
  38. package/dist/cjs/engine/path-matcher/registration/context.js +1 -1
  39. package/dist/cjs/engine/path-matcher/registration/context.js.map +1 -1
  40. package/dist/cjs/engine/path-matcher/registration/errors.js +1 -1
  41. package/dist/cjs/engine/path-matcher/registration/errors.js.map +1 -1
  42. package/dist/cjs/engine/path-matcher/registration/index.js +1 -1
  43. package/dist/cjs/engine/path-matcher/registration/index.js.map +1 -1
  44. package/dist/cjs/engine/path-matcher/registration/trieNodes.js.map +1 -1
  45. package/dist/cjs/engine/path-matcher/types.d.ts +3 -0
  46. package/dist/cjs/engine/path-matcher/types.d.ts.map +1 -1
  47. package/dist/cjs/engine/search-params/strategies/number.js +1 -1
  48. package/dist/cjs/engine/search-params/strategies/number.js.map +1 -1
  49. package/dist/cjs/engine/validation/routes.js +1 -1
  50. package/dist/cjs/engine/validation/routes.js.map +1 -1
  51. package/dist/cjs/helpers.js +1 -1
  52. package/dist/cjs/helpers.js.map +1 -1
  53. package/dist/cjs/index.d.ts +3 -3
  54. package/dist/cjs/index.js +2 -1
  55. package/dist/cjs/index.js.map +1 -1
  56. package/dist/cjs/internals.d.ts +30 -8
  57. package/dist/cjs/internals.d.ts.map +1 -1
  58. package/dist/cjs/internals.js +1 -1
  59. package/dist/cjs/internals.js.map +1 -1
  60. package/dist/cjs/limits.js +2 -0
  61. package/dist/cjs/limits.js.map +1 -0
  62. package/dist/cjs/namespaces/EventBusNamespace/EventBusNamespace.js.map +1 -1
  63. package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js +1 -1
  64. package/dist/cjs/namespaces/NavigationNamespace/NavigationNamespace.js.map +1 -1
  65. package/dist/cjs/namespaces/OptionsNamespace/OptionsNamespace.js.map +1 -1
  66. package/dist/cjs/namespaces/OptionsNamespace/constants.js +1 -1
  67. package/dist/cjs/namespaces/OptionsNamespace/constants.js.map +1 -1
  68. package/dist/cjs/namespaces/OptionsNamespace/helpers.js.map +1 -1
  69. package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js +1 -1
  70. package/dist/cjs/namespaces/RoutesNamespace/RoutesNamespace.js.map +1 -1
  71. package/dist/cjs/namespaces/RoutesNamespace/helpers.js +1 -1
  72. package/dist/cjs/namespaces/RoutesNamespace/helpers.js.map +1 -1
  73. package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts +8 -0
  74. package/dist/cjs/namespaces/RoutesNamespace/routesStore.d.ts.map +1 -1
  75. package/dist/cjs/namespaces/RoutesNamespace/routesStore.js +1 -1
  76. package/dist/cjs/namespaces/RoutesNamespace/routesStore.js.map +1 -1
  77. package/dist/cjs/namespaces/RoutesNamespace/types.d.ts +24 -7
  78. package/dist/cjs/namespaces/RoutesNamespace/types.d.ts.map +1 -1
  79. package/dist/cjs/namespaces/StateNamespace/StateNamespace.js +1 -1
  80. package/dist/cjs/namespaces/StateNamespace/StateNamespace.js.map +1 -1
  81. package/dist/cjs/pipeline/buildURL.js +2 -0
  82. package/dist/cjs/pipeline/buildURL.js.map +1 -0
  83. package/dist/cjs/pipeline/canonicalize.js +2 -0
  84. package/dist/cjs/pipeline/canonicalize.js.map +1 -0
  85. package/dist/cjs/pipeline/materialize.js +2 -0
  86. package/dist/cjs/pipeline/materialize.js.map +1 -0
  87. package/dist/cjs/pipeline/port.d.ts +147 -0
  88. package/dist/cjs/pipeline/port.d.ts.map +1 -0
  89. package/dist/cjs/routerFSM.js +1 -1
  90. package/dist/cjs/routerFSM.js.map +1 -1
  91. package/dist/cjs/transitionPath.js +1 -1
  92. package/dist/cjs/transitionPath.js.map +1 -1
  93. package/dist/cjs/types/RouterValidator.d.ts +14 -0
  94. package/dist/cjs/types/RouterValidator.d.ts.map +1 -1
  95. package/dist/cjs/types/api.d.ts +20 -11
  96. package/dist/cjs/types/api.d.ts.map +1 -1
  97. package/dist/cjs/types/base.d.ts +63 -4
  98. package/dist/cjs/types/base.d.ts.map +1 -1
  99. package/dist/cjs/types/constants.d.ts +1 -0
  100. package/dist/cjs/types/constants.d.ts.map +1 -1
  101. package/dist/cjs/types/router.d.ts +112 -23
  102. package/dist/cjs/types/router.d.ts.map +1 -1
  103. package/dist/cjs/types/tree-changed.d.ts +1 -1
  104. package/dist/cjs/types/tree-changed.d.ts.map +1 -1
  105. package/dist/cjs/types.d.ts +20 -11
  106. package/dist/cjs/types.d.ts.map +1 -1
  107. package/dist/cjs/utils/event-emitter/EventEmitter.js.map +1 -0
  108. package/dist/cjs/utils/fsm/fsm.js.map +1 -0
  109. package/dist/cjs/utils/logger/RouterLogger.js.map +1 -0
  110. package/dist/cjs/utils/logger/constants.js.map +1 -0
  111. package/dist/cjs/validation.js +2 -1
  112. package/dist/cjs/validation.js.map +1 -1
  113. package/dist/cjs/wiring/wireNamespaces.js +1 -1
  114. package/dist/cjs/wiring/wireNamespaces.js.map +1 -1
  115. package/dist/esm/Router-DEpNuwBW.mjs +2 -0
  116. package/dist/esm/Router-DEpNuwBW.mjs.map +1 -0
  117. package/dist/esm/Router.d.mts +7 -6
  118. package/dist/esm/Router.d.mts.map +1 -1
  119. package/dist/esm/api/getPluginApi.d.mts.map +1 -1
  120. package/dist/esm/api/getRoutesApi.d.mts.map +1 -1
  121. package/dist/esm/api.mjs +1 -1
  122. package/dist/esm/api.mjs.map +1 -1
  123. package/dist/esm/buildParamMeta-D8td47fL.mjs +2 -0
  124. package/dist/esm/buildParamMeta-D8td47fL.mjs.map +1 -0
  125. package/dist/esm/constants.d.mts.map +1 -1
  126. package/dist/esm/createRouter.d.mts +1 -1
  127. package/dist/esm/createRouter.d.mts.map +1 -1
  128. package/dist/esm/engine/path-matcher/SegmentMatcher.d.mts +14 -1
  129. package/dist/esm/engine/path-matcher/SegmentMatcher.d.mts.map +1 -1
  130. package/dist/esm/engine/path-matcher/types.d.mts +3 -0
  131. package/dist/esm/engine/path-matcher/types.d.mts.map +1 -1
  132. package/dist/esm/index.d.mts +3 -3
  133. package/dist/esm/index.mjs +1 -1
  134. package/dist/esm/index.mjs.map +1 -1
  135. package/dist/esm/internals.d.mts +30 -8
  136. package/dist/esm/internals.d.mts.map +1 -1
  137. package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts +8 -0
  138. package/dist/esm/namespaces/RoutesNamespace/routesStore.d.mts.map +1 -1
  139. package/dist/esm/namespaces/RoutesNamespace/types.d.mts +24 -7
  140. package/dist/esm/namespaces/RoutesNamespace/types.d.mts.map +1 -1
  141. package/dist/esm/pipeline/port.d.mts +147 -0
  142. package/dist/esm/pipeline/port.d.mts.map +1 -0
  143. package/dist/esm/types/RouterValidator.d.mts +14 -0
  144. package/dist/esm/types/RouterValidator.d.mts.map +1 -1
  145. package/dist/esm/types/api.d.mts +20 -11
  146. package/dist/esm/types/api.d.mts.map +1 -1
  147. package/dist/esm/types/base.d.mts +63 -4
  148. package/dist/esm/types/base.d.mts.map +1 -1
  149. package/dist/esm/types/constants.d.mts +1 -0
  150. package/dist/esm/types/constants.d.mts.map +1 -1
  151. package/dist/esm/types/router.d.mts +112 -23
  152. package/dist/esm/types/router.d.mts.map +1 -1
  153. package/dist/esm/types/tree-changed.d.mts +1 -1
  154. package/dist/esm/types/tree-changed.d.mts.map +1 -1
  155. package/dist/esm/types.d.mts +20 -11
  156. package/dist/esm/types.d.mts.map +1 -1
  157. package/dist/esm/validation.mjs +1 -1
  158. package/dist/esm/validation.mjs.map +1 -1
  159. package/package.json +2 -2
  160. package/dist/cjs/Router-DGUed2F4.js +0 -2
  161. package/dist/cjs/Router-DGUed2F4.js.map +0 -1
  162. package/dist/cjs/buildParamMeta-DniluAIV.js +0 -2
  163. package/dist/cjs/buildParamMeta-DniluAIV.js.map +0 -1
  164. package/dist/cjs/foundation/event-emitter/EventEmitter.js.map +0 -1
  165. package/dist/cjs/foundation/fsm/fsm.js.map +0 -1
  166. package/dist/cjs/foundation/logger/RouterLogger.js.map +0 -1
  167. package/dist/cjs/foundation/logger/constants.js.map +0 -1
  168. package/dist/cjs/namespaces/StateNamespace/helpers.js +0 -2
  169. package/dist/cjs/namespaces/StateNamespace/helpers.js.map +0 -1
  170. package/dist/cjs/stateMetaStore.js +0 -2
  171. package/dist/cjs/stateMetaStore.js.map +0 -1
  172. package/dist/esm/Router-Bk6PfSE8.mjs +0 -2
  173. package/dist/esm/Router-Bk6PfSE8.mjs.map +0 -1
  174. package/dist/esm/buildParamMeta-bOLhLF9h.mjs +0 -2
  175. package/dist/esm/buildParamMeta-bOLhLF9h.mjs.map +0 -1
  176. /package/dist/cjs/{foundation → utils}/event-emitter/EventEmitter.js +0 -0
  177. /package/dist/cjs/{foundation → utils}/fsm/fsm.js +0 -0
  178. /package/dist/cjs/{foundation → utils}/logger/RouterLogger.js +0 -0
  179. /package/dist/cjs/{foundation → utils}/logger/constants.js +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"number.js","names":[],"sources":["../../../../../src/engine/search-params/strategies/number.ts"],"sourcesContent":["/**\n * Number decoding strategies.\n *\n * @module search-params/strategies/number\n */\n\nimport type { NumberFormat } from \"../types\";\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for decoding number values.\n */\nexport interface NumberStrategy {\n decode: (decodedValue: string) => number | null;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * No special number handling - values remain strings.\n */\nexport const noneNumberStrategy: NumberStrategy = {\n decode: () => null, // passthrough\n};\n\n/**\n * Auto-detect numeric values and parse as numbers.\n * Matches integers and decimals via charCode scan (faster than regex for short strings).\n *\n * Recognizes an optional leading `-` so negatives round-trip symmetrically with the\n * values `navigate()`/`build()` produce (`build({ n: -5 })` → `\"n=-5\"`). Leading-zero\n * and unsafe-integer rejection apply to the magnitude regardless of sign. Exponent\n * notation stays a string — `build` never emits a canonical safe exponent, and unsafe\n * exponents would lose precision. (#742)\n */\nexport const autoNumberStrategy: NumberStrategy = {\n decode: (value) => {\n const length = value.length;\n\n if (length === 0) {\n return null;\n }\n\n // Optional leading minus; the magnitude (digits) begins at `start`.\n const start = value.codePointAt(0) === 45 ? 1 : 0; // '-'\n\n // A bare \"-\" has no magnitude.\n if (start === length) {\n return null;\n }\n\n // Leading zeros are not canonical numbers (\"00\", \"007\", \"-007\") — preserve as strings.\n // Allow \"0\" and \"0.x\" (single zero or decimal starting with 0).\n if (\n length - start > 1 &&\n value.codePointAt(start) === 48 &&\n value.codePointAt(start + 1) !== 46\n ) {\n return null;\n }\n\n let hasDot = false;\n\n for (let i = start; i < length; i++) {\n const ch = value.codePointAt(i);\n\n if (ch !== undefined && ch >= 48 && ch <= 57) {\n continue; // '0'-'9'\n }\n\n if (ch === 46 && !hasDot && i !== start && i !== length - 1) {\n hasDot = true;\n\n continue;\n }\n\n return null; // non-digit, non-dot, or invalid dot position\n }\n\n const num = Number(value);\n\n // Negative zero is not round-trippable: build(-0) emits \"0\" and\n // String(-0) === \"0\", so \"-0\"/\"-0.0\" must stay strings. (#898)\n if (Object.is(num, -0)) {\n return null;\n }\n\n // Reject unsafe integers precision loss would corrupt the value on roundtrip.\n if (!Number.isSafeInteger(num) && !hasDot) {\n return null;\n }\n\n return num;\n },\n};\n\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\n/**\n * Map of number format to strategy implementation.\n */\nexport const numberStrategies: Record<NumberFormat, NumberStrategy> = {\n auto: autoNumberStrategy,\n none: noneNumberStrategy,\n};\n"],"mappings":"AA0BA,MAAa,EAAqC,CAChD,WAAc,IAChB,EAYa,EAAqC,CAChD,OAAS,GAAU,CACjB,IAAM,EAAS,EAAM,OAErB,GAAI,IAAW,EACb,OAAO,KAIT,IAAM,EAAQ,IAAM,YAAY,CAAC,IAAM,IASvC,GANI,IAAU,GAOZ,EAAS,EAAQ,GACjB,EAAM,YAAY,CAAK,IAAM,IAC7B,EAAM,YAAY,EAAQ,CAAC,IAAM,GAEjC,OAAO,KAGT,IAAI,EAAS,GAEb,IAAK,IAAI,EAAI,EAAO,EAAI,EAAQ,IAAK,CACnC,IAAM,EAAK,EAAM,YAAY,CAAC,EAE1B,SAAO,IAAA,IAAa,GAAM,IAAM,GAAM,IAI1C,IAAI,IAAO,IAAM,CAAC,GAAU,IAAM,GAAS,IAAM,EAAS,EAAG,CAC3D,EAAS,GAET,QACF,CAEA,OAAO,IAFP,CAGF,CAEA,IAAM,EAAM,OAAO,CAAK,EAaxB,OATI,OAAO,GAAG,EAAK,EAAE,GAKjB,CAAC,OAAO,cAAc,CAAG,GAAK,CAAC,EAC1B,KAGF,CACT,CACF,EASa,EAAyD,CACpE,KAAM,EACN,KAAM,CACR"}
1
+ {"version":3,"file":"number.js","names":[],"sources":["../../../../../src/engine/search-params/strategies/number.ts"],"sourcesContent":["/**\n * Number decoding strategies.\n *\n * @module search-params/strategies/number\n */\n\nimport type { NumberFormat } from \"../types\";\n\n// =============================================================================\n// Strategy Interface\n// =============================================================================\n\n/**\n * Strategy for decoding number values.\n */\nexport interface NumberStrategy {\n decode: (decodedValue: string) => number | null;\n}\n\n// =============================================================================\n// Strategy Implementations\n// =============================================================================\n\n/**\n * No special number handling - values remain strings.\n */\nexport const noneNumberStrategy: NumberStrategy = {\n decode: () => null, // passthrough\n};\n\n/**\n * Auto-detect numeric values and parse as numbers.\n * Matches integers and decimals via charCode scan (faster than regex for short strings).\n *\n * Recognizes an optional leading `-` so negatives round-trip symmetrically with the\n * values `navigate()`/`build()` produce (`build({ n: -5 })` → `\"n=-5\"`). Leading-zero\n * and unsafe-integer rejection apply to the magnitude regardless of sign. Exponent\n * notation stays a string — `build` never emits a canonical safe exponent, and unsafe\n * exponents would lose precision. (#742)\n */\nexport const autoNumberStrategy: NumberStrategy = {\n decode: (value) => {\n const length = value.length;\n\n if (length === 0) {\n return null;\n }\n\n // Optional leading minus; the magnitude (digits) begins at `start`.\n const start = value.codePointAt(0) === 45 ? 1 : 0; // '-'\n\n // A bare \"-\" has no magnitude.\n if (start === length) {\n return null;\n }\n\n // Leading zeros are not canonical numbers (\"00\", \"007\", \"-007\") — preserve as strings.\n // Allow \"0\" and \"0.x\" (single zero or decimal starting with 0).\n if (\n length - start > 1 &&\n value.codePointAt(start) === 48 &&\n value.codePointAt(start + 1) !== 46\n ) {\n return null;\n }\n\n let hasDot = false;\n\n for (let i = start; i < length; i++) {\n const ch = value.codePointAt(i);\n\n if (ch !== undefined && ch >= 48 && ch <= 57) {\n continue; // '0'-'9'\n }\n\n if (ch === 46 && !hasDot && i !== start && i !== length - 1) {\n hasDot = true;\n\n continue;\n }\n\n return null; // non-digit, non-dot, or invalid dot position\n }\n\n const num = Number(value);\n\n // The stated criterion is round-trip stability, enforced directly rather than\n // through per-case guards: `build` prints a number with String(), so a value\n // may be coerced only when String() reproduces the exact text we parsed. This\n // subsumes the former negative-zero guard (String(-0) === \"0\" \"-0\", #898)\n // and closes the decimal family the safe-integer check below deliberately\n // exempts — trailing zeros (\"2.0\" 2 → \"2\") and precision loss\n // (\"9007199254740993.5\" → 9007199254740994), both of which rebuilt a URL\n // different from the one that was matched. (#1565)\n if (String(num) !== value) {\n return null;\n }\n\n // Unsafe integers pass the text check (2**53 prints back exactly) but lose\n // precision in arithmetic, so they stay strings. Decimals are exempt: a\n // fractional value is never a \"safe integer\", and the check above already\n // proves its text round-trips.\n if (!Number.isSafeInteger(num) && !hasDot) {\n return null;\n }\n\n return num;\n },\n};\n\n// =============================================================================\n// Strategy Map\n// =============================================================================\n\n/**\n * Map of number format to strategy implementation.\n */\nexport const numberStrategies: Record<NumberFormat, NumberStrategy> = {\n auto: autoNumberStrategy,\n none: noneNumberStrategy,\n};\n"],"mappings":"AA0BA,MAAa,EAAqC,CAChD,WAAc,IAChB,EAYa,EAAqC,CAChD,OAAS,GAAU,CACjB,IAAM,EAAS,EAAM,OAErB,GAAI,IAAW,EACb,OAAO,KAIT,IAAM,EAAQ,IAAM,YAAY,CAAC,IAAM,IASvC,GANI,IAAU,GAOZ,EAAS,EAAQ,GACjB,EAAM,YAAY,CAAK,IAAM,IAC7B,EAAM,YAAY,EAAQ,CAAC,IAAM,GAEjC,OAAO,KAGT,IAAI,EAAS,GAEb,IAAK,IAAI,EAAI,EAAO,EAAI,EAAQ,IAAK,CACnC,IAAM,EAAK,EAAM,YAAY,CAAC,EAE1B,SAAO,IAAA,IAAa,GAAM,IAAM,GAAM,IAI1C,IAAI,IAAO,IAAM,CAAC,GAAU,IAAM,GAAS,IAAM,EAAS,EAAG,CAC3D,EAAS,GAET,QACF,CAEA,OAAO,IAFP,CAGF,CAEA,IAAM,EAAM,OAAO,CAAK,EAsBxB,OAZI,OAAO,CAAG,IAAM,GAQhB,CAAC,OAAO,cAAc,CAAG,GAAK,CAAC,EAC1B,KAGF,CACT,CACF,EASa,EAAyD,CACpE,KAAM,EACN,KAAM,CACR"}
@@ -1,2 +1,2 @@
1
- const e=require("../path-matcher/parseSegment.js"),t=require("../path-matcher/buildParamMeta.js");function n(e,t){return TypeError(`[router.${e}] ${t}`)}function r(e,t,r,i){let a=new Set;for(let o of e){if(a.has(o))throw n(r,`Invalid path for route "${t}": duplicate parameter name ':${o}' in "${i}" (a param name must be unique within a route — the second binding would overwrite the first)`);a.add(o)}}function i(e,r,i,a,o){let s=new Set(e);for(let e of r){if(t.INVALID_QUERY_NAME_RGX.test(e))throw n(a,`Invalid path for route "${i}": invalid query-param name "${e}" in "${o}" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`);if(s.has(e))throw n(a,`Invalid path for route "${i}": "${e}" is declared as both a path param and a query param in "${o}" — buildPath would emit its value twice (rename one)`)}}function a(e){let t=!0,n=!1;for(let r of e){if(r===`/`){t=!0;continue}if(t&&=(n=r===`:`||r===`*`,!1),!n&&r.codePointAt(0)>=128)return!0}return!1}function o(e,t,n){switch(e){case`name-less`:case`trailing-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') without a name in "${n}"`;case`fused-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') must begin a segment, but "${n}" fuses one to a static prefix (use a boundary marker like "/a/:b")`}}function s(e,t){return e.code===`optional-removed`?`Invalid path for route "${t}": optional params are not supported — "${e.segment}". Declare two sibling routes instead: "${e.withoutSegment}" and "${e.requiredForm}" (the route hierarchy already expresses optionality)`:`Invalid path for route "${t}": regex constraints are not supported — '<' and '>' are reserved in path segments ("${e.segment}"). Match the segment as a plain string and validate the value in a guard (canActivate) or app code`}function c(c,l,u,d){if(typeof c!=`string`){let e;throw e=c===null?`null`:Array.isArray(c)?`array`:typeof c,n(u,`Route path must be a string, got ${e}`)}if(c===``)return;if(/\s/.test(c))throw n(u,`Invalid path for route "${l}": whitespace not allowed in "${c}"`);if(!/^([/?~]|[^/]+$)/.test(c))throw n(u,`Route "${l}" has invalid path format: "${c}". Path should start with '/', '~', '?' or be a relative segment.`);if(c.includes(`//`))throw n(u,`Invalid path for route "${l}": double slashes not allowed in "${c}"`);let{pathPattern:f,urlParams:p,queryParams:m}=t.buildParamMeta(c);r(p,l,u,c),i(p,m,l,u,c);let h=e.describeRemovedForm(f);if(h!==void 0)throw n(u,s(h,l));let g=e.findSegmentGrammarError(f);if(g!==void 0)throw n(u,o(g,l,c));if(a(f))throw n(u,`Invalid path for route "${l}": non-ASCII static segment in "${c}" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`);let _=d&&d.paramMeta.urlParams.length>0;if(c.startsWith(`~`)&&_)throw n(u,`Absolute path "${c}" cannot be used under parent route with URL parameters`)}exports.validateRoutePath=c;
1
+ const e=require("../path-matcher/parseSegment.js"),t=require("../path-matcher/buildParamMeta.js");function n(e,t){return TypeError(`[router.${e}] ${t}`)}function r(e,t,r,i){let a=new Set;for(let o of e){if(a.has(o))throw n(r,`Invalid path for route "${t}": duplicate parameter name ':${o}' in "${i}" (a param name must be unique within a route — the second binding would overwrite the first)`);a.add(o)}}function i(e,r,i,a){for(let o of e)if(t.INVALID_QUERY_NAME_RGX.test(o))throw n(i,`Invalid path for route "${r}": invalid query-param name "${o}" in "${a}" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`)}function a(e){let t=!0,n=!1;for(let r of e){if(r===`/`){t=!0;continue}if(t&&=(n=r===`:`||r===`*`,!1),!n&&r.codePointAt(0)>=128)return!0}return!1}function o(e,t,n){switch(e){case`name-less`:case`trailing-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') without a name in "${n}"`;case`fused-marker`:return`Invalid path for route "${t}": parameter marker (':' or '*') must begin a segment, but "${n}" fuses one to a static prefix (use a boundary marker like "/a/:b")`}}function s(e,t){return e.code===`optional-removed`?`Invalid path for route "${t}": optional params are not supported — "${e.segment}". Declare two sibling routes instead: "${e.withoutSegment}" and "${e.requiredForm}" (the route hierarchy already expresses optionality)`:`Invalid path for route "${t}": regex constraints are not supported — '<' and '>' are reserved in path segments ("${e.segment}"). Match the segment as a plain string and validate the value in a guard (canActivate) or app code`}function c(c,l,u,d){if(typeof c!=`string`){let e;throw e=c===null?`null`:Array.isArray(c)?`array`:typeof c,n(u,`Route path must be a string, got ${e}`)}if(c===``)return;if(/\s/.test(c))throw n(u,`Invalid path for route "${l}": whitespace not allowed in "${c}"`);if(!/^([/?~]|[^/]+$)/.test(c))throw n(u,`Route "${l}" has invalid path format: "${c}". Path should start with '/', '~', '?' or be a relative segment.`);if(c.includes(`//`))throw n(u,`Invalid path for route "${l}": double slashes not allowed in "${c}"`);let{pathPattern:f,urlParams:p,queryParams:m}=t.buildParamMeta(c);r(p,l,u,c),i(m,l,u,c);let h=e.describeRemovedForm(f);if(h!==void 0)throw n(u,s(h,l));let g=e.findSegmentGrammarError(f);if(g!==void 0)throw n(u,o(g,l,c));if(a(f))throw n(u,`Invalid path for route "${l}": non-ASCII static segment in "${c}" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`);let _=d&&d.paramMeta.urlParams.length>0;if(c.startsWith(`~`)&&_)throw n(u,`Absolute path "${c}" cannot be used under parent route with URL parameters`)}exports.validateRoutePath=c;
2
2
  //# sourceMappingURL=routes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":["INVALID_QUERY_NAME_RGX","buildParamMeta","describeRemovedForm","findSegmentGrammarError"],"sources":["../../../../src/engine/validation/routes.ts"],"sourcesContent":["import {\n buildParamMeta,\n describeRemovedForm,\n findSegmentGrammarError,\n INVALID_QUERY_NAME_RGX,\n} from \"../path-matcher\";\n\nimport type { RemovedForm, SegmentErrorCode } from \"../path-matcher\";\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 * Rejects a param name repeated within one route's own path (`/:id/:id`, a\n * param+splat clash `/:x/*x`, #1151). `buildParamMeta.urlParams` lists every\n * path-binding name — params AND splats — in order, keeping duplicates (`/:x/*x`\n * → `[\"x\", \"x\"]`), so a single pass over it catches both. The trie binds the\n * duplicates at different positions under one name, so match's later capture\n * silently overwrites the earlier and `rewritePathOnMatch` then rewrites the\n * user's URL from the single survivor. The #736 conflict guard only fires on\n * DIFFERENTLY-named params at one position, so this same-name case slips through.\n * path-matcher's `registerTree` backstop additionally catches CROSS-level dups (a\n * parent's param reused by a child), which this per-path gate cannot see.\n * Extracted so `validateRoutePath` stays within the cognitive-complexity budget.\n */\nfunction validateUniqueParamNames(\n urlParams: readonly string[],\n routeName: string,\n methodName: string,\n path: string,\n): void {\n const seen = new Set<string>();\n\n for (const name of urlParams) {\n if (seen.has(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": duplicate parameter name ':${name}' in \"${path}\" (a param name must be unique within a route — the second binding would overwrite the first)`,\n );\n }\n\n seen.add(name);\n }\n}\n\n/**\n * #1242 §5.1/§5.3: rejects a malformed query-param declaration — a query name\n * carrying `<`/`>` (`/a?fil<ter` — a `<` in a plain query tail; never round-trips),\n * or one that collides with a path-param name (`/a/:tab?tab`, where buildPath emits\n * the value twice). Narrow to `<>`: a `=` in the declaration (`?tab=1`, §5.2) is\n * tolerated today and left as a separate call. (Under M1 a reverse-order typo\n * `/a/:b?<c>` is caught earlier as optional-removed — the `?<` keeps it in the\n * path, §3.3.) path-matcher's `registerTree` backstops both; this gate adds the\n * route-contextual message.\n */\nfunction validateQueryParamDeclarations(\n urlParams: readonly string[],\n queryParams: readonly string[],\n routeName: string,\n methodName: string,\n path: string,\n): void {\n const urlParamSet = new Set(urlParams);\n\n for (const name of queryParams) {\n if (INVALID_QUERY_NAME_RGX.test(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": invalid query-param name \"${name}\" in \"${path}\" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`,\n );\n }\n\n if (urlParamSet.has(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": \"${name}\" is declared as both a path param and a query param in \"${path}\" — buildPath would emit its value twice (rename one)`,\n );\n }\n }\n}\n\n/**\n * Reports whether a path has a raw non-ASCII code point (≥ U+0080) in a STATIC\n * segment (`/café`, `/меню`, #1154). match rejects any non-ASCII input byte\n * (`#scanPath`) and compares static trie keys raw, so such a route registers but\n * is unmatchable — `buildPath` emits `/café`, which its own `match` rejects. Only\n * static text is flagged: a marker-led segment (`:café`, a non-ASCII param NAME)\n * is skipped. A `for…of` code-point scan tracking segment start. Runs AFTER the\n * removed-form / grammar rejections, so no `<`/`>` (a former constraint) can\n * reach it — the 3-token grammar has no constraint body to skip (M1, #1516).\n */\nfunction hasNonAsciiStatic(path: string): boolean {\n let atSegmentStart = true;\n let segmentIsMarker = false;\n\n for (const char of path) {\n if (char === \"/\") {\n atSegmentStart = true;\n\n continue;\n }\n\n if (atSegmentStart) {\n segmentIsMarker = char === \":\" || char === \"*\";\n atSegmentStart = false;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- non-empty code point from for-of\n if (!segmentIsMarker && char.codePointAt(0)! >= 0x80) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Maps a SURVIVING per-segment grammar error code (from `findSegmentGrammarError`)\n * to the gate's route-contextual message. The removed-form codes (`optional-removed`\n * / `constraint-removed`) are NOT handled here — they carry a richer replacement\n * recipe built by `removedFormMessage` from `describeRemovedForm`.\n */\nfunction gateGrammarMessage(\n code: Exclude<SegmentErrorCode, \"optional-removed\" | \"constraint-removed\">,\n routeName: string,\n path: string,\n): string {\n switch (code) {\n case \"name-less\":\n case \"trailing-marker\": {\n return `Invalid path for route \"${routeName}\": parameter marker (':' or '*') without a name in \"${path}\"`;\n }\n case \"fused-marker\": {\n return `Invalid path for route \"${routeName}\": parameter marker (':' or '*') must begin a segment, but \"${path}\" fuses one to a static prefix (use a boundary marker like \"/a/:b\")`;\n }\n }\n}\n\n/**\n * Builds the route-contextual replacement recipe for a removed form (M1) — the\n * RICH tier (the matcher backstop uses a shorter, path-free recipe). For an\n * optional it names the offending segment and the two concrete sibling paths that\n * replace it (computed from the actual path by `describeRemovedForm`); for a\n * constraint it names the offending segment and points to a guard.\n */\nfunction removedFormMessage(removed: RemovedForm, routeName: string): string {\n if (removed.code === \"optional-removed\") {\n return `Invalid path for route \"${routeName}\": optional params are not supported — \"${removed.segment}\". Declare two sibling routes instead: \"${removed.withoutSegment}\" and \"${removed.requiredForm}\" (the route hierarchy already expresses optionality)`;\n }\n\n return `Invalid path for route \"${routeName}\": regex constraints are not supported — '<' and '>' are reserved in path segments (\"${removed.segment}\"). Match the segment as a plain string and validate the value in a guard (canActivate) or app code`;\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 */\n// A format-validation gate: a flat sequence of INDEPENDENT guard clauses (type,\n// whitespace, format, double-slash, dup-param, query-decl, the M1 removed-form\n// recipe, surviving grammar markers (name-less / fused / trailing), non-ASCII\n// static, absolute-under-param). Each is a simple early throw; extracting them\n// would only scatter one checklist.\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 // The grammar checks below scan only the URL-path portion: `buildParamMeta`\n // strips the query the same way the trie does, so a `:`/`*` inside a query\n // declaration is not falsely flagged. (`buildParamMeta` is total — the 3-token\n // grammar has no constraint body to compile, so it never throws — M1, #1516.)\n const { pathPattern, urlParams, queryParams } = buildParamMeta(path);\n\n // Duplicate param name within this route's own path (`/:id/:id`, `/:x/*x`, #1151).\n validateUniqueParamNames(urlParams, routeName, methodName, path);\n\n // Malformed query-param declarations (#1242 §5.1/§5.2/§5.3): a query name with\n // `<>`, or one that collides with a path-param name.\n validateQueryParamDeclarations(\n urlParams,\n queryParams,\n routeName,\n methodName,\n path,\n );\n\n // Removed-form (M1) rejection first — a `:x?` optional or a `<re>` constraint —\n // with the RICH route-contextual replacement recipe (the offending segment plus,\n // for an optional, the two computed sibling paths). Returns undefined when the\n // path's first grammar error is a SURVIVING code, so the fall-through below runs.\n const removed = describeRemovedForm(pathPattern);\n\n if (removed !== undefined) {\n throw createRouterError(methodName, removedFormMessage(removed, routeName));\n }\n\n // Surviving per-segment grammar rejections via the canonical `parseSegment`\n // tokenizer: name-less (#858/#863), fused-marker (#1050), trailing-marker\n // (#1324). `findSegmentGrammarError` runs the same split+parse the matcher uses,\n // so the gate cannot drift. (Only removed-form codes reach `removed` above; the\n // first error here is therefore always a surviving code.)\n const grammarError = findSegmentGrammarError(pathPattern);\n\n if (grammarError !== undefined) {\n throw createRouterError(\n methodName,\n gateGrammarMessage(\n grammarError as Exclude<\n SegmentErrorCode,\n \"optional-removed\" | \"constraint-removed\"\n >,\n routeName,\n path,\n ),\n );\n }\n\n // Raw non-ASCII in a STATIC segment (`/café`, `/меню`, #1154). match rejects\n // non-ASCII input and compares static keys raw, so the route registers but never\n // matches. Reject with the percent-encode workaround (path-matcher backstops at\n // `registerTree`); a non-ASCII param NAME or constraint body is unaffected.\n if (hasNonAsciiStatic(pathPattern)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": non-ASCII static segment in \"${path}\" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`,\n );\n }\n\n // Absolute paths under parameterized parents\n // Check if parent has URL parameters via paramTypeMap\n const hasUrlParams = parentNode && parentNode.paramMeta.urlParams.length > 0;\n\n if (path.startsWith(\"~\") && hasUrlParams) {\n throw createRouterError(\n methodName,\n `Absolute path \"${path}\" cannot be used under parent route with URL parameters`,\n );\n }\n}\n"],"mappings":"kGAkBA,SAAS,EAAkB,EAAoB,EAA4B,CACzE,OAAW,UAAU,WAAW,EAAW,IAAI,GAAS,CAC1D,CAeA,SAAS,EACP,EACA,EACA,EACA,EACM,CACN,IAAM,EAAO,IAAI,IAEjB,IAAK,IAAM,KAAQ,EAAW,CAC5B,GAAI,EAAK,IAAI,CAAI,EACf,MAAM,EACJ,EACA,2BAA2B,EAAU,gCAAgC,EAAK,QAAQ,EAAK,8FACzF,EAGF,EAAK,IAAI,CAAI,CACf,CACF,CAYA,SAAS,EACP,EACA,EACA,EACA,EACA,EACM,CACN,IAAM,EAAc,IAAI,IAAI,CAAS,EAErC,IAAK,IAAM,KAAQ,EAAa,CAC9B,GAAIA,EAAAA,uBAAuB,KAAK,CAAI,EAClC,MAAM,EACJ,EACA,2BAA2B,EAAU,+BAA+B,EAAK,QAAQ,EAAK,qGACxF,EAGF,GAAI,EAAY,IAAI,CAAI,EACtB,MAAM,EACJ,EACA,2BAA2B,EAAU,MAAM,EAAK,2DAA2D,EAAK,sDAClH,CAEJ,CACF,CAYA,SAAS,EAAkB,EAAuB,CAChD,IAAI,EAAiB,GACjB,EAAkB,GAEtB,IAAK,IAAM,KAAQ,EAAM,CACvB,GAAI,IAAS,IAAK,CAChB,EAAiB,GAEjB,QACF,CAQA,GANA,AAEE,KADA,EAAkB,IAAS,KAAO,IAAS,IAC1B,IAIf,CAAC,GAAmB,EAAK,YAAY,CAAC,GAAM,IAC9C,MAAO,EAEX,CAEA,MAAO,EACT,CAQA,SAAS,EACP,EACA,EACA,EACQ,CACR,OAAQ,EAAR,CACE,IAAK,YACL,IAAK,kBACH,MAAO,2BAA2B,EAAU,sDAAsD,EAAK,GAEzG,IAAK,eACH,MAAO,2BAA2B,EAAU,8DAA8D,EAAK,oEAEnH,CACF,CASA,SAAS,EAAmB,EAAsB,EAA2B,CAK3E,OAJI,EAAQ,OAAS,mBACZ,2BAA2B,EAAU,0CAA0C,EAAQ,QAAQ,0CAA0C,EAAQ,eAAe,SAAS,EAAQ,aAAa,uDAGhM,2BAA2B,EAAU,uFAAuF,EAAQ,QAAQ,oGACrJ,CA0CA,SAAgB,EACd,EACA,EACA,EACA,EACwB,CAExB,GAAI,OAAO,GAAS,SAAU,CAE5B,IAAI,EAUJ,KARA,CAKE,EALE,IAAS,KACA,OACF,MAAM,QAAQ,CAAI,EAChB,QAEA,OAAO,EAGd,EACJ,EACA,oCAAoC,GACtC,CACF,CAGA,GAAI,IAAS,GACX,OAIF,GAAI,KAAK,KAAK,CAAI,EAChB,MAAM,EACJ,EACA,2BAA2B,EAAU,gCAAgC,EAAK,EAC5E,EAIF,GAAI,CAAC,kBAAkB,KAAK,CAAI,EAC9B,MAAM,EACJ,EACA,UAAU,EAAU,8BAA8B,EAAK,kEACzD,EAIF,GAAI,EAAK,SAAS,IAAI,EACpB,MAAM,EACJ,EACA,2BAA2B,EAAU,oCAAoC,EAAK,EAChF,EAOF,GAAM,CAAE,cAAa,YAAW,eAAgBC,EAAAA,eAAe,CAAI,EAGnE,EAAyB,EAAW,EAAW,EAAY,CAAI,EAI/D,EACE,EACA,EACA,EACA,EACA,CACF,EAMA,IAAM,EAAUC,EAAAA,oBAAoB,CAAW,EAE/C,GAAI,IAAY,IAAA,GACd,MAAM,EAAkB,EAAY,EAAmB,EAAS,CAAS,CAAC,EAQ5E,IAAM,EAAeC,EAAAA,wBAAwB,CAAW,EAExD,GAAI,IAAiB,IAAA,GACnB,MAAM,EACJ,EACA,EACE,EAIA,EACA,CACF,CACF,EAOF,GAAI,EAAkB,CAAW,EAC/B,MAAM,EACJ,EACA,2BAA2B,EAAU,kCAAkC,EAAK,0JAC9E,EAKF,IAAM,EAAe,GAAc,EAAW,UAAU,UAAU,OAAS,EAE3E,GAAI,EAAK,WAAW,GAAG,GAAK,EAC1B,MAAM,EACJ,EACA,kBAAkB,EAAK,wDACzB,CAEJ"}
1
+ {"version":3,"file":"routes.js","names":["INVALID_QUERY_NAME_RGX","buildParamMeta","describeRemovedForm","findSegmentGrammarError"],"sources":["../../../../src/engine/validation/routes.ts"],"sourcesContent":["import {\n buildParamMeta,\n describeRemovedForm,\n findSegmentGrammarError,\n INVALID_QUERY_NAME_RGX,\n} from \"../path-matcher\";\n\nimport type { RemovedForm, SegmentErrorCode } from \"../path-matcher\";\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 * Rejects a param name repeated within one route's own path (`/:id/:id`, a\n * param+splat clash `/:x/*x`, #1151). `buildParamMeta.urlParams` lists every\n * path-binding name — params AND splats — in order, keeping duplicates (`/:x/*x`\n * → `[\"x\", \"x\"]`), so a single pass over it catches both. The trie binds the\n * duplicates at different positions under one name, so match's later capture\n * silently overwrites the earlier and `rewritePathOnMatch` then rewrites the\n * user's URL from the single survivor. The #736 conflict guard only fires on\n * DIFFERENTLY-named params at one position, so this same-name case slips through.\n * path-matcher's `registerTree` backstop additionally catches CROSS-level dups (a\n * parent's param reused by a child), which this per-path gate cannot see.\n * Extracted so `validateRoutePath` stays within the cognitive-complexity budget.\n */\nfunction validateUniqueParamNames(\n urlParams: readonly string[],\n routeName: string,\n methodName: string,\n path: string,\n): void {\n const seen = new Set<string>();\n\n for (const name of urlParams) {\n if (seen.has(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": duplicate parameter name ':${name}' in \"${path}\" (a param name must be unique within a route — the second binding would overwrite the first)`,\n );\n }\n\n seen.add(name);\n }\n}\n\n/**\n * #1242 §5.1/§5.3: rejects a malformed query-param declaration — a query name\n * carrying `<`/`>` (`/a?fil<ter` — a `<` in a plain query tail; never round-trips),\n * or one that collides with a path-param name (`/a/:tab?tab`, where buildPath emits\n * the value twice). Narrow to `<>`: a `=` in the declaration (`?tab=1`, §5.2) is\n * tolerated today and left as a separate call. (Under M1 a reverse-order typo\n * `/a/:b?<c>` is caught earlier as optional-removed — the `?<` keeps it in the\n * path, §3.3.) path-matcher's `registerTree` backstops both; this gate adds the\n * route-contextual message.\n */\nfunction validateQueryParamDeclarations(\n queryParams: readonly string[],\n routeName: string,\n methodName: string,\n path: string,\n): void {\n // A path/query name collision (`/a/:tab?tab`) is legal under M2: `tab` lives\n // in both `state.params` and `state.search` as separate channels (RFC-4 M2 /\n // #1548), so the former \"declared as both\" rejection is gone. Only a query\n // name that can never round-trip (contains `<`/`>`) is still rejected.\n for (const name of queryParams) {\n if (INVALID_QUERY_NAME_RGX.test(name)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": invalid query-param name \"${name}\" in \"${path}\" (a query-param name cannot contain '<' or '>' — it would never round-trip; rename the query param)`,\n );\n }\n }\n}\n\n/**\n * Reports whether a path has a raw non-ASCII code point (≥ U+0080) in a STATIC\n * segment (`/café`, `/меню`, #1154). match rejects any non-ASCII input byte\n * (`#scanPath`) and compares static trie keys raw, so such a route registers but\n * is unmatchable — `buildPath` emits `/café`, which its own `match` rejects. Only\n * static text is flagged: a marker-led segment (`:café`, a non-ASCII param NAME)\n * is skipped. A `for…of` code-point scan tracking segment start. Runs AFTER the\n * removed-form / grammar rejections, so no `<`/`>` (a former constraint) can\n * reach it — the 3-token grammar has no constraint body to skip (M1, #1516).\n */\nfunction hasNonAsciiStatic(path: string): boolean {\n let atSegmentStart = true;\n let segmentIsMarker = false;\n\n for (const char of path) {\n if (char === \"/\") {\n atSegmentStart = true;\n\n continue;\n }\n\n if (atSegmentStart) {\n segmentIsMarker = char === \":\" || char === \"*\";\n atSegmentStart = false;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- non-empty code point from for-of\n if (!segmentIsMarker && char.codePointAt(0)! >= 0x80) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Maps a SURVIVING per-segment grammar error code (from `findSegmentGrammarError`)\n * to the gate's route-contextual message. The removed-form codes (`optional-removed`\n * / `constraint-removed`) are NOT handled here — they carry a richer replacement\n * recipe built by `removedFormMessage` from `describeRemovedForm`.\n */\nfunction gateGrammarMessage(\n code: Exclude<SegmentErrorCode, \"optional-removed\" | \"constraint-removed\">,\n routeName: string,\n path: string,\n): string {\n switch (code) {\n case \"name-less\":\n case \"trailing-marker\": {\n return `Invalid path for route \"${routeName}\": parameter marker (':' or '*') without a name in \"${path}\"`;\n }\n case \"fused-marker\": {\n return `Invalid path for route \"${routeName}\": parameter marker (':' or '*') must begin a segment, but \"${path}\" fuses one to a static prefix (use a boundary marker like \"/a/:b\")`;\n }\n }\n}\n\n/**\n * Builds the route-contextual replacement recipe for a removed form (M1) — the\n * RICH tier (the matcher backstop uses a shorter, path-free recipe). For an\n * optional it names the offending segment and the two concrete sibling paths that\n * replace it (computed from the actual path by `describeRemovedForm`); for a\n * constraint it names the offending segment and points to a guard.\n */\nfunction removedFormMessage(removed: RemovedForm, routeName: string): string {\n if (removed.code === \"optional-removed\") {\n return `Invalid path for route \"${routeName}\": optional params are not supported — \"${removed.segment}\". Declare two sibling routes instead: \"${removed.withoutSegment}\" and \"${removed.requiredForm}\" (the route hierarchy already expresses optionality)`;\n }\n\n return `Invalid path for route \"${routeName}\": regex constraints are not supported — '<' and '>' are reserved in path segments (\"${removed.segment}\"). Match the segment as a plain string and validate the value in a guard (canActivate) or app code`;\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 */\n// A format-validation gate: a flat sequence of INDEPENDENT guard clauses (type,\n// whitespace, format, double-slash, dup-param, query-decl, the M1 removed-form\n// recipe, surviving grammar markers (name-less / fused / trailing), non-ASCII\n// static, absolute-under-param). Each is a simple early throw; extracting them\n// would only scatter one checklist.\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 // The grammar checks below scan only the URL-path portion: `buildParamMeta`\n // strips the query the same way the trie does, so a `:`/`*` inside a query\n // declaration is not falsely flagged. (`buildParamMeta` is total — the 3-token\n // grammar has no constraint body to compile, so it never throws — M1, #1516.)\n const { pathPattern, urlParams, queryParams } = buildParamMeta(path);\n\n // Duplicate param name within this route's own path (`/:id/:id`, `/:x/*x`, #1151).\n validateUniqueParamNames(urlParams, routeName, methodName, path);\n\n // Malformed query-param declarations (#1242 §5.1): a query name with `<>`\n // (never round-trips). Name collisions with a path param are legal under M2\n // (separate params/search channels, #1548).\n validateQueryParamDeclarations(queryParams, routeName, methodName, path);\n\n // Removed-form (M1) rejection first — a `:x?` optional or a `<re>` constraint —\n // with the RICH route-contextual replacement recipe (the offending segment plus,\n // for an optional, the two computed sibling paths). Returns undefined when the\n // path's first grammar error is a SURVIVING code, so the fall-through below runs.\n const removed = describeRemovedForm(pathPattern);\n\n if (removed !== undefined) {\n throw createRouterError(methodName, removedFormMessage(removed, routeName));\n }\n\n // Surviving per-segment grammar rejections via the canonical `parseSegment`\n // tokenizer: name-less (#858/#863), fused-marker (#1050), trailing-marker\n // (#1324). `findSegmentGrammarError` runs the same split+parse the matcher uses,\n // so the gate cannot drift. (Only removed-form codes reach `removed` above; the\n // first error here is therefore always a surviving code.)\n const grammarError = findSegmentGrammarError(pathPattern);\n\n if (grammarError !== undefined) {\n throw createRouterError(\n methodName,\n gateGrammarMessage(\n grammarError as Exclude<\n SegmentErrorCode,\n \"optional-removed\" | \"constraint-removed\"\n >,\n routeName,\n path,\n ),\n );\n }\n\n // Raw non-ASCII in a STATIC segment (`/café`, `/меню`, #1154). match rejects\n // non-ASCII input and compares static keys raw, so the route registers but never\n // matches. Reject with the percent-encode workaround (path-matcher backstops at\n // `registerTree`); a non-ASCII param NAME or constraint body is unaffected.\n if (hasNonAsciiStatic(pathPattern)) {\n throw createRouterError(\n methodName,\n `Invalid path for route \"${routeName}\": non-ASCII static segment in \"${path}\" — match compares static segments raw and rejects non-ASCII input, so this route would never match. Percent-encode it (e.g. '/caf%C3%A9') or use a param`,\n );\n }\n\n // Absolute paths under parameterized parents\n // Check if parent has URL parameters via paramTypeMap\n const hasUrlParams = parentNode && parentNode.paramMeta.urlParams.length > 0;\n\n if (path.startsWith(\"~\") && hasUrlParams) {\n throw createRouterError(\n methodName,\n `Absolute path \"${path}\" cannot be used under parent route with URL parameters`,\n );\n }\n}\n"],"mappings":"kGAkBA,SAAS,EAAkB,EAAoB,EAA4B,CACzE,OAAW,UAAU,WAAW,EAAW,IAAI,GAAS,CAC1D,CAeA,SAAS,EACP,EACA,EACA,EACA,EACM,CACN,IAAM,EAAO,IAAI,IAEjB,IAAK,IAAM,KAAQ,EAAW,CAC5B,GAAI,EAAK,IAAI,CAAI,EACf,MAAM,EACJ,EACA,2BAA2B,EAAU,gCAAgC,EAAK,QAAQ,EAAK,8FACzF,EAGF,EAAK,IAAI,CAAI,CACf,CACF,CAYA,SAAS,EACP,EACA,EACA,EACA,EACM,CAKN,IAAK,IAAM,KAAQ,EACjB,GAAIA,EAAAA,uBAAuB,KAAK,CAAI,EAClC,MAAM,EACJ,EACA,2BAA2B,EAAU,+BAA+B,EAAK,QAAQ,EAAK,qGACxF,CAGN,CAYA,SAAS,EAAkB,EAAuB,CAChD,IAAI,EAAiB,GACjB,EAAkB,GAEtB,IAAK,IAAM,KAAQ,EAAM,CACvB,GAAI,IAAS,IAAK,CAChB,EAAiB,GAEjB,QACF,CAQA,GANA,AAEE,KADA,EAAkB,IAAS,KAAO,IAAS,IAC1B,IAIf,CAAC,GAAmB,EAAK,YAAY,CAAC,GAAM,IAC9C,MAAO,EAEX,CAEA,MAAO,EACT,CAQA,SAAS,EACP,EACA,EACA,EACQ,CACR,OAAQ,EAAR,CACE,IAAK,YACL,IAAK,kBACH,MAAO,2BAA2B,EAAU,sDAAsD,EAAK,GAEzG,IAAK,eACH,MAAO,2BAA2B,EAAU,8DAA8D,EAAK,oEAEnH,CACF,CASA,SAAS,EAAmB,EAAsB,EAA2B,CAK3E,OAJI,EAAQ,OAAS,mBACZ,2BAA2B,EAAU,0CAA0C,EAAQ,QAAQ,0CAA0C,EAAQ,eAAe,SAAS,EAAQ,aAAa,uDAGhM,2BAA2B,EAAU,uFAAuF,EAAQ,QAAQ,oGACrJ,CA0CA,SAAgB,EACd,EACA,EACA,EACA,EACwB,CAExB,GAAI,OAAO,GAAS,SAAU,CAE5B,IAAI,EAUJ,KARA,CAKE,EALE,IAAS,KACA,OACF,MAAM,QAAQ,CAAI,EAChB,QAEA,OAAO,EAGd,EACJ,EACA,oCAAoC,GACtC,CACF,CAGA,GAAI,IAAS,GACX,OAIF,GAAI,KAAK,KAAK,CAAI,EAChB,MAAM,EACJ,EACA,2BAA2B,EAAU,gCAAgC,EAAK,EAC5E,EAIF,GAAI,CAAC,kBAAkB,KAAK,CAAI,EAC9B,MAAM,EACJ,EACA,UAAU,EAAU,8BAA8B,EAAK,kEACzD,EAIF,GAAI,EAAK,SAAS,IAAI,EACpB,MAAM,EACJ,EACA,2BAA2B,EAAU,oCAAoC,EAAK,EAChF,EAOF,GAAM,CAAE,cAAa,YAAW,eAAgBC,EAAAA,eAAe,CAAI,EAGnE,EAAyB,EAAW,EAAW,EAAY,CAAI,EAK/D,EAA+B,EAAa,EAAW,EAAY,CAAI,EAMvE,IAAM,EAAUC,EAAAA,oBAAoB,CAAW,EAE/C,GAAI,IAAY,IAAA,GACd,MAAM,EAAkB,EAAY,EAAmB,EAAS,CAAS,CAAC,EAQ5E,IAAM,EAAeC,EAAAA,wBAAwB,CAAW,EAExD,GAAI,IAAiB,IAAA,GACnB,MAAM,EACJ,EACA,EACE,EAIA,EACA,CACF,CACF,EAOF,GAAI,EAAkB,CAAW,EAC/B,MAAM,EACJ,EACA,2BAA2B,EAAU,kCAAkC,EAAK,0JAC9E,EAKF,IAAM,EAAe,GAAc,EAAW,UAAU,UAAU,OAAS,EAE3E,GAAI,EAAK,WAAW,GAAG,GAAK,EAC1B,MAAM,EACJ,EACA,kBAAkB,EAAK,wDACzB,CAEJ"}
@@ -1,2 +1,2 @@
1
- const e=require("./constants.js");function t(e){return Object.freeze(e)}function n(t={}){return{...e.DEFAULT_LIMITS,...t}}function r(t){if(t===void 0)return t;let n;for(let e in t){if(!Object.hasOwn(t,e))continue;let r=t[e];r!==void 0&&(n??={},n[e]=r)}return n??e.EMPTY_PARAMS}exports.createLimits=n,exports.freezeStateInPlace=t,exports.normalizeParams=r;
1
+ const e=require("./constants.js");function t(e,t){if(e===void 0)return n(t);let r={};for(let t in e)Object.hasOwn(e,t)&&e[t]!==void 0&&(r[t]=e[t]);if(t!==void 0)for(let e in t)Object.hasOwn(t,e)&&t[e]!==void 0&&(r[e]=t[e]);return r}function n(e){if(e===void 0)return;let t;for(let n in e)Object.hasOwn(e,n)&&e[n]===void 0&&(t??={...e},delete t[n]);return t??e}const r=new Set([`string`,`number`,`boolean`]);function i(e){return r.has(typeof e)}function a(e,t){if(e===t)return!0;if(Array.isArray(e)){if(!Array.isArray(t))return e.length===1&&a(e[0],t);if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!a(e[n],t[n]))return!1;return!0}return Array.isArray(t)?t.length===1&&a(e,t[0]):i(e)&&i(t)&&String(e)===String(t)}function o(e){return Object.freeze(e)}function s(e,n,r,i=!1){if(e!==void 0)return Object.freeze(t(e,n));if(n===void 0||n===r)return r;if(i)return Object.freeze(n);let a=t(void 0,n);return Object.freeze(a===n?{...n}:a)}function c(t){if(t===void 0)return t;let n;for(let e in t){if(!Object.hasOwn(t,e))continue;let r=t[e];r!==void 0&&(n??={},n[e]=r)}return n??e.EMPTY_PARAMS}exports.areParamValuesEqual=a,exports.freezeStateInPlace=o,exports.mergeDefined=t,exports.mergeWithDefault=s,exports.normalizeParams=c;
2
2
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","names":["DEFAULT_LIMITS","EMPTY_PARAMS"],"sources":["../../src/helpers.ts"],"sourcesContent":["// packages/core/src/helpers.ts\n\nimport { DEFAULT_LIMITS, EMPTY_PARAMS } from \"./constants\";\n\nimport type { Params, State, LimitsConfig } from \"./types\";\nimport type { Limits } from \"./types/internal\";\n\n// =============================================================================\n// State Helpers\n// =============================================================================\n\n/**\n * Shallow-freezes a State object in place.\n *\n * Freezes only the top-level State object (blocks reassignment of `name`,\n * `params`, `path`, `transition`, `context`). Nested objects (`params`,\n * `transition`, `transition.segments`, `transition.segments.{deactivated,activated}`)\n * are expected to be **already frozen at creation time** by their producers:\n *\n * - `params` frozen in `makeState()` / `navigateToNotFound()`\n * - `transition`, `segments`, `deactivated`, `activated` frozen in\n * `buildTransitionMeta()` (or inline in `navigateToNotFound()`)\n *\n * `state.context` is **intentionally not frozen** — plugins write to it via\n * `claim.write(state, value)` after state creation.\n *\n * @internal\n */\nexport function freezeStateInPlace<T extends State>(state: T): T {\n // `Object.freeze` returns non-objects (incl. null/undefined) unchanged, so the\n // former `if (!state) return state` guard was redundant — callers also gate it\n // (`state ? freezeStateInPlace(state) : undefined`) and `T extends State` is\n // typed non-null.\n return Object.freeze(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\n// =============================================================================\n// Params Helpers\n// =============================================================================\n\n/**\n * Strips `undefined` values from a params object before handoff to the query\n * string engine and state storage.\n *\n * **Why this exists:** `router.navigate(name, { x: undefined })` must not put\n * `x` into the resulting URL (publicly documented contract). The underlying\n * query engine (`search-params`) already does this, but the contract belongs\n * to `@real-router/core` — this function guarantees it at the core boundary\n * so that:\n * - Plugin interceptors on `forwardState` that inject `undefined` values are\n * caught before they reach the engine\n * - `state.params` never contains `undefined` values (roundtrip consistent\n * with URL)\n * - The contract is verifiable at core's own test surface (doesn't depend on\n * engine behavior for regression detection)\n *\n * Single pass. When nothing survives (empty input, or every value `undefined`)\n * it returns the shared frozen `EMPTY_PARAMS` singleton, so `makeState`'s\n * `params === EMPTY_PARAMS` reuse branch fires and an empty-params navigation\n * allocates zero transient `{}` (#1027); a non-empty input returns a fresh\n * object. Either way reference identity is not preserved across calls, and the\n * result MUST be treated as read-only — callers must not mutate it (the empty\n * case is a shared frozen singleton).\n */\nexport function normalizeParams(params: Params): Params;\n\nexport function normalizeParams(params: undefined): undefined;\n\nexport function normalizeParams(params: Params | undefined): Params | undefined;\n\nexport function normalizeParams(\n params: Params | undefined,\n): Params | undefined {\n if (params === undefined) {\n return params;\n }\n\n let normalized: Params | undefined;\n\n for (const key in params) {\n if (!Object.hasOwn(params, key)) {\n continue;\n }\n\n const value = params[key];\n\n if (value !== undefined) {\n // Lazy allocation: an all-empty / all-undefined input costs zero objects.\n normalized ??= {};\n normalized[key] = value;\n }\n }\n\n // Reuse the shared singleton when nothing survived so makeState's\n // `params === EMPTY_PARAMS` reuse branch fires (#1027).\n return normalized ?? EMPTY_PARAMS;\n}\n"],"mappings":"kCA4BA,SAAgB,EAAoC,EAAa,CAK/D,OAAO,OAAO,OAAO,CAAK,CAC5B,CAMA,SAAgB,EAAa,EAAoC,CAAC,EAAW,CAC3E,MAAO,CAAE,GAAGA,EAAAA,eAAgB,GAAG,CAAW,CAC5C,CAoCA,SAAgB,EACd,EACoB,CACpB,GAAI,IAAW,IAAA,GACb,OAAO,EAGT,IAAI,EAEJ,IAAK,IAAM,KAAO,EAAQ,CACxB,GAAI,CAAC,OAAO,OAAO,EAAQ,CAAG,EAC5B,SAGF,IAAM,EAAQ,EAAO,GAEjB,IAAU,IAAA,KAEZ,IAAe,CAAC,EAChB,EAAW,GAAO,EAEtB,CAIA,OAAO,GAAcC,EAAAA,YACvB"}
1
+ {"version":3,"file":"helpers.js","names":["EMPTY_PARAMS"],"sources":["../../src/helpers.ts"],"sourcesContent":["// packages/core/src/helpers.ts\n\nimport { EMPTY_PARAMS } from \"./constants\";\n\nimport type { Params, State } from \"./types\";\n\n// =============================================================================\n// Default merge — `undefined` ≡ absence (#1550 / #1551)\n// =============================================================================\n\n/**\n * Merges a route default UNDER a value (the value wins), treating `undefined` as\n * **absence on both sides** (#1550 / #1551).\n *\n * A key survives only when its winning value is defined:\n * - `mergeDefined({ page: \"1\" }, { page: undefined })` → `{ page: \"1\" }` — an\n * explicit `undefined` from the caller does not outrank the default (this is\n * what the path channel always did via `normalizeParams`, and what the query\n * channel did not, #1550);\n * - `mergeDefined({ q: undefined }, undefined)` → `{}` — a default that itself\n * carries `undefined` behaves exactly like no default entry, instead of\n * leaking an `undefined`-valued own key into the frozen state (#1551).\n *\n * Because the rule lives in the merge rather than in a separately-ordered\n * \"normalize\" stage, it holds for every producer and cannot be reintroduced by\n * whichever side is merged last.\n *\n * Allocation contract: **may return the `value` argument itself** when there is\n * no default and nothing to strip (the hot path — callers pass an\n * already-normalized bag), so a caller that freezes or stores the result must\n * copy it first. `undefined` in ⇒ `undefined` out when there is no default, which\n * keeps the matcher's single-bag fallback (`search ?? params`) reachable.\n */\nexport function mergeDefined<T extends Record<string, unknown>>(\n defaultValue: T,\n value: T | undefined,\n): T;\n\nexport function mergeDefined<T extends Record<string, unknown>>(\n defaultValue: T | undefined,\n value: T,\n): T;\n\nexport function mergeDefined<T extends Record<string, unknown>>(\n defaultValue: T | undefined,\n value: T | undefined,\n): T | undefined;\n\nexport function mergeDefined<T extends Record<string, unknown>>(\n defaultValue: T | undefined,\n value: T | undefined,\n): T | undefined {\n if (defaultValue === undefined) {\n return stripUndefined(value);\n }\n\n const merged: Record<string, unknown> = {};\n\n for (const key in defaultValue) {\n if (Object.hasOwn(defaultValue, key) && defaultValue[key] !== undefined) {\n merged[key] = defaultValue[key];\n }\n }\n\n if (value !== undefined) {\n for (const key in value) {\n if (!Object.hasOwn(value, key)) {\n continue;\n }\n\n // `undefined` means \"I said nothing\", so the default keeps the slot.\n if (value[key] === undefined) {\n continue;\n }\n\n merged[key] = value[key];\n }\n }\n\n return merged as T;\n}\n\n/**\n * Drops `undefined`-valued own keys, returning the input **unchanged** when there\n * are none (no allocation on the common path). `undefined` in ⇒ `undefined` out —\n * unlike {@link normalizeParams}, which collapses an all-`undefined` bag to the\n * shared `EMPTY_PARAMS` singleton and is the path-channel entry guard.\n */\nfunction stripUndefined<T extends Record<string, unknown>>(\n value: T | undefined,\n): T | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n let stripped: Record<string, unknown> | undefined;\n\n for (const key in value) {\n if (!(Object.hasOwn(value, key) && value[key] === undefined)) {\n continue;\n }\n\n stripped ??= { ...value };\n\n delete stripped[key];\n }\n\n return (stripped as T | undefined) ?? value;\n}\n\n// =============================================================================\n// Param value comparison (#1554)\n// =============================================================================\n\n/** The value types a channel prints into (and parses back from) a URL. */\nconst PRINTABLE_TYPES = new Set([\"string\", \"number\", \"boolean\"]);\n\n/** A value the two channels can carry across a URL round-trip. */\nfunction isPrintableScalar(value: unknown): value is string | number | boolean {\n return PRINTABLE_TYPES.has(typeof value);\n}\n\n/**\n * Compares two param / query values for equality **independently of where they\n * came from** (#1554).\n *\n * The two directions produce different value DOMAINS for the same location: the\n * URL direction parses (`?page=2` → `2`, `?a=1&a=2` → `[1, 2]`, a path slot is\n * always a string), the intent direction keeps whatever the caller supplied\n * (`{ page: \"2\" }` stays a string). Both build the SAME `state.path`, so a\n * `===`-based comparison reported a URL-derived state and an intent-derived\n * state on one location as UNEQUAL — an active link rendered inactive.\n *\n * The rule is therefore \"equal when both values print the same query string\":\n * - **scalars** (string / number / boolean) compare by their printed form, so\n * `2 ≡ \"2\"` and `true ≡ \"true\"`;\n * - **arrays** compare element-wise under the same rule, and a **singleton\n * array** compares against a bare scalar (`[\"1\"]` and `1` both print `?a=1`);\n * - everything else (`null`, `undefined`, objects) keeps strict semantics —\n * those print differently (`?a` vs `?a=` vs nothing at all), so tolerating\n * them would equate genuinely different URLs.\n *\n * Value normalization is deliberately NOT done: `state.search` keeps the mixed\n * domain (RFC-4 M2 / §10.14 decision (б)) and comparison is the single place\n * that knows the two domains describe the same location. Unifying the domain\n * itself belongs to the typed search-schema stage.\n */\nexport function areParamValuesEqual(val1: unknown, val2: unknown): boolean {\n if (val1 === val2) {\n return true;\n }\n\n if (Array.isArray(val1)) {\n // A singleton array prints exactly like its element (`[\"1\"]` and `1` both\n // print `?a=1`), so compare across the shape instead of rejecting on it.\n if (!Array.isArray(val2)) {\n return val1.length === 1 && areParamValuesEqual(val1[0], val2);\n }\n\n if (val1.length !== val2.length) {\n return false;\n }\n\n // eslint-disable-next-line unicorn/no-for-loop -- hot path: for-of entries() allocates iterator per recursive call\n for (let i = 0; i < val1.length; i++) {\n if (!areParamValuesEqual(val1[i], val2[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n if (Array.isArray(val2)) {\n return val2.length === 1 && areParamValuesEqual(val1, val2[0]);\n }\n\n return (\n isPrintableScalar(val1) &&\n isPrintableScalar(val2) &&\n String(val1) === String(val2)\n );\n}\n\n// =============================================================================\n// State Helpers\n// =============================================================================\n\n/**\n * Shallow-freezes a State object in place.\n *\n * Freezes only the top-level State object (blocks reassignment of `name`,\n * `params`, `path`, `transition`, `context`). Nested objects (`params`,\n * `transition`, `transition.segments`, `transition.segments.{deactivated,activated}`)\n * are expected to be **already frozen at creation time** by their producers:\n *\n * - `params` frozen in `makeState()` / `navigateToNotFound()`\n * - `transition`, `segments`, `deactivated`, `activated` frozen in\n * `buildTransitionMeta()` (or inline in `navigateToNotFound()`)\n *\n * `state.context` is **intentionally not frozen** — plugins write to it via\n * `claim.write(state, value)` after state creation.\n *\n * @internal\n */\nexport function freezeStateInPlace<T extends State>(state: T): T {\n // `Object.freeze` returns non-objects (incl. null/undefined) unchanged, so the\n // former `if (!state) return state` guard was redundant — callers also gate it\n // (`state ? freezeStateInPlace(state) : undefined`) and `T extends State` is\n // typed non-null.\n return Object.freeze(state);\n}\n\n/**\n * Merges a channel's route default UNDER a routed value (the value wins) and\n * freezes the result. Reuses the shared frozen `empty` singleton (EMPTY_PARAMS /\n * EMPTY_SEARCH, #1027) when there is neither a default nor a value — so the hot\n * path (no defaults, empty params) allocates zero objects. A defaulted channel\n * always spreads (a fresh frozen object); an undefined-default channel freezes a\n * copy of the value (never the caller's object).\n *\n * `undefined` is absence on BOTH sides (`mergeDefined`, #1550 / #1551): an\n * explicitly-`undefined` caller value leaves the default in place, and a default\n * that carries `undefined` behaves like no entry — so the frozen state never\n * exposes an `undefined`-valued own key on either channel.\n *\n * `valueIsOwned` says the caller minted `value` itself and nothing else holds a\n * reference — then the defensive copy is skipped and the bag is frozen in place\n * (#1589). Only `canonicalize`'s PATH channel may pass it, because only there is\n * the value the fresh object `normalizeParams` just returned. Passing it for a\n * bag that came from user code would freeze the caller's object.\n *\n * Lives here, not in a namespace, because the rule outlived its call count:\n * stage ③ (`applyDefaults`) had TWO callers when the pipeline landed\n * (`StateNamespace.makeState` and `pipeline/canonicalize`) and has ONE since\n * Phase 4 folded the first onto the second — but the chain fold in\n * `RoutesNamespace` still layers hop defaults through `mergeDefined` directly,\n * so a second copy of \"default under value\" would be a second source of truth\n * for the rule, the same drift trap #1550/#1551 closed\n * by collapsing the four merge sites onto `mergeDefined`.\n *\n * @internal\n */\nexport function mergeWithDefault(\n defaultValue: Record<string, unknown> | undefined,\n value: Record<string, unknown> | undefined,\n empty: Readonly<Record<string, never>>,\n valueIsOwned = false,\n): Readonly<Record<string, unknown>> {\n if (defaultValue !== undefined) {\n return Object.freeze(mergeDefined(defaultValue, value));\n }\n\n if (value === undefined || value === empty) {\n return empty;\n }\n\n // OWNED value: freeze in place. The copy below exists solely so the CALLER's\n // bag is never frozen out from under it — when the bag was minted one line\n // earlier by `normalizeParams` (which always returns a fresh object or the\n // frozen `empty` singleton, never its input) there is no caller to protect,\n // and `undefined` values are already stripped, so `mergeDefined`'s walk is\n // redundant too. Measured on #1589: without this the path channel is copied\n // TWICE per producer call — once to normalize, once to freeze — on `navigate`,\n // `buildPath`, `matchPath`, `isActiveRoute` and `canNavigateTo` alike.\n if (valueIsOwned) {\n return Object.freeze(value);\n }\n\n // `mergeDefined` returns the argument itself when there is nothing to strip,\n // so copy before freezing — the caller's bag must never be frozen.\n const defined = mergeDefined(undefined, value);\n\n return Object.freeze(defined === value ? { ...value } : defined);\n}\n\n// =============================================================================\n// Params Helpers\n// =============================================================================\n\n/**\n * Strips `undefined` values from a params object before handoff to the query\n * string engine and state storage.\n *\n * **Why this exists:** `router.navigate(name, { x: undefined })` must not put\n * `x` into the resulting URL (publicly documented contract). The underlying\n * query engine (`search-params`) already does this, but the contract belongs\n * to `@real-router/core` — this function guarantees it at the core boundary\n * so that:\n * - Plugin interceptors on `forwardState` that inject `undefined` values are\n * caught before they reach the engine\n * - `state.params` never contains `undefined` values (roundtrip consistent\n * with URL)\n * - The contract is verifiable at core's own test surface (doesn't depend on\n * engine behavior for regression detection)\n *\n * Single pass. When nothing survives (empty input, or every value `undefined`)\n * it returns the shared frozen `EMPTY_PARAMS` singleton, so the merge's\n * `value === empty` reuse branch (`mergeWithDefault`) fires and an empty-params\n * navigation allocates zero transient `{}` (#1027); a non-empty input returns a fresh\n * object. Either way reference identity is not preserved across calls, and the\n * result MUST be treated as read-only — callers must not mutate it (the empty\n * case is a shared frozen singleton).\n */\nexport function normalizeParams(params: Params): Params;\n\nexport function normalizeParams(params: undefined): undefined;\n\nexport function normalizeParams(params: Params | undefined): Params | undefined;\n\nexport function normalizeParams(\n params: Params | undefined,\n): Params | undefined {\n if (params === undefined) {\n return params;\n }\n\n let normalized: Params | undefined;\n\n for (const key in params) {\n if (!Object.hasOwn(params, key)) {\n continue;\n }\n\n const value = params[key];\n\n if (value !== undefined) {\n // Lazy allocation: an all-empty / all-undefined input costs zero objects.\n normalized ??= {};\n normalized[key] = value;\n }\n }\n\n // Reuse the shared singleton when nothing survived so the merge's\n // `value === empty` reuse branch fires (#1027).\n return normalized ?? EMPTY_PARAMS;\n}\n"],"mappings":"kCAgDA,SAAgB,EACd,EACA,EACe,CACf,GAAI,IAAiB,IAAA,GACnB,OAAO,EAAe,CAAK,EAG7B,IAAM,EAAkC,CAAC,EAEzC,IAAK,IAAM,KAAO,EACZ,OAAO,OAAO,EAAc,CAAG,GAAK,EAAa,KAAS,IAAA,KAC5D,EAAO,GAAO,EAAa,IAI/B,GAAI,IAAU,IAAA,GACZ,IAAK,IAAM,KAAO,EACX,OAAO,OAAO,EAAO,CAAG,GAKzB,EAAM,KAAS,IAAA,KAInB,EAAO,GAAO,EAAM,IAIxB,OAAO,CACT,CAQA,SAAS,EACP,EACe,CACf,GAAI,IAAU,IAAA,GACZ,OAGF,IAAI,EAEJ,IAAK,IAAM,KAAO,EACV,OAAO,OAAO,EAAO,CAAG,GAAK,EAAM,KAAS,IAAA,KAIlD,IAAa,CAAE,GAAG,CAAM,EAExB,OAAO,EAAS,IAGlB,OAAQ,GAA8B,CACxC,CAOA,MAAM,EAAkB,IAAI,IAAI,CAAC,SAAU,SAAU,SAAS,CAAC,EAG/D,SAAS,EAAkB,EAAoD,CAC7E,OAAO,EAAgB,IAAI,OAAO,CAAK,CACzC,CA2BA,SAAgB,EAAoB,EAAe,EAAwB,CACzE,GAAI,IAAS,EACX,MAAO,GAGT,GAAI,MAAM,QAAQ,CAAI,EAAG,CAGvB,GAAI,CAAC,MAAM,QAAQ,CAAI,EACrB,OAAO,EAAK,SAAW,GAAK,EAAoB,EAAK,GAAI,CAAI,EAG/D,GAAI,EAAK,SAAW,EAAK,OACvB,MAAO,GAIT,IAAK,IAAI,EAAI,EAAG,EAAI,EAAK,OAAQ,IAC/B,GAAI,CAAC,EAAoB,EAAK,GAAI,EAAK,EAAE,EACvC,MAAO,GAIX,MAAO,EACT,CAMA,OAJI,MAAM,QAAQ,CAAI,EACb,EAAK,SAAW,GAAK,EAAoB,EAAM,EAAK,EAAE,EAI7D,EAAkB,CAAI,GACtB,EAAkB,CAAI,GACtB,OAAO,CAAI,IAAM,OAAO,CAAI,CAEhC,CAuBA,SAAgB,EAAoC,EAAa,CAK/D,OAAO,OAAO,OAAO,CAAK,CAC5B,CAgCA,SAAgB,EACd,EACA,EACA,EACA,EAAe,GACoB,CACnC,GAAI,IAAiB,IAAA,GACnB,OAAO,OAAO,OAAO,EAAa,EAAc,CAAK,CAAC,EAGxD,GAAI,IAAU,IAAA,IAAa,IAAU,EACnC,OAAO,EAWT,GAAI,EACF,OAAO,OAAO,OAAO,CAAK,EAK5B,IAAM,EAAU,EAAa,IAAA,GAAW,CAAK,EAE7C,OAAO,OAAO,OAAO,IAAY,EAAQ,CAAE,GAAG,CAAM,EAAI,CAAO,CACjE,CAoCA,SAAgB,EACd,EACoB,CACpB,GAAI,IAAW,IAAA,GACb,OAAO,EAGT,IAAI,EAEJ,IAAK,IAAM,KAAO,EAAQ,CACxB,GAAI,CAAC,OAAO,OAAO,EAAQ,CAAG,EAC5B,SAGF,IAAM,EAAQ,EAAO,GAEjB,IAAU,IAAA,KAEZ,IAAe,CAAC,EAChB,EAAW,GAAO,EAEtB,CAIA,OAAO,GAAcA,EAAAA,YACvB"}
@@ -1,8 +1,8 @@
1
1
  import { RouteTree } from "./engine/builder/types.js";
2
2
  import { QueryParamsMode, QueryParamsOptions, RouteParams, RouteTreeState } from "./types/route-node-types.js";
3
- import { Params, SerializedRouterState, SimpleState, State, StateMetaInput, TransitionMeta, TransitionPhase, TransitionReason, Unsubscribe } from "./types/base.js";
3
+ import { NavigationTarget, Params, ParamsSearch, SearchParamPrimitive, SearchParamValue, SearchParams, SerializedRouterState, SimpleState, State, TransitionMeta, TransitionPhase, TransitionReason, Unsubscribe } from "./types/base.js";
4
4
  import { LimitsConfig } from "./types/limits.js";
5
- import { DefaultDependencies, DefaultParamsCallback, DefaultRouteCallback, ForwardToCallback, GuardFn, GuardFnFactory, LeaveFn, LeaveState, Listener, LogCallback, LogLevel, LogLevelConfig, LoggerConfig, Navigator, Options, Plugin, PluginFactory, Route, RouteConfigUpdate, RouterLogger, SubscribeFn, SubscribeState, Subscription } from "./types/router.js";
5
+ import { AnyOptions, DefaultDependencies, DefaultParamsCallback, DefaultRouteCallback, DefaultSearchCallback, ForwardToCallback, GuardFn, GuardFnFactory, LeaveFn, LeaveState, Listener, LogCallback, LogLevel, LogLevelConfig, LoggerConfig, Navigator, Options, Plugin, PluginFactory, Route, RouteConfigUpdate, RouterLogger, SubscribeFn, SubscribeState, Subscription } from "./types/router.js";
6
6
  import { ErrorCodeKeys, ErrorCodeToValueMap, ErrorCodeValues, EventMethodMap, EventName, EventToNameMap, EventToPluginMap, EventsKeys, PluginMethod } from "./types/constants.js";
7
7
  import { TreeChangedAdd, TreeChangedClear, TreeChangedEvent, TreeChangedRemove, TreeChangedReplace, TreeChangedUpdate, TreeStructuralPatch } from "./types/tree-changed.js";
8
8
  import { ContextNamespaceClaim, DependenciesApi, InterceptableMethodMap, InterceptorFn, LifecycleApi, PluginApi, RoutesApi } from "./types/api.js";
@@ -14,4 +14,4 @@ import { RouterError } from "./RouterError.js";
14
14
  import { createRouter } from "./createRouter.js";
15
15
  import { getNavigator } from "./getNavigator.js";
16
16
  import { resolveForwardChain } from "./namespaces/RoutesNamespace/forwardChain.js";
17
- export { type Constants, type ContextNamespaceClaim, type DefaultDependencies, type DefaultParamsCallback, type DefaultRouteCallback, type DependenciesApi, type ErrorCodeKeys, type ErrorCodeToValueMap, type ErrorCodeValues, type ErrorCodes, type EventMethodMap, type EventName, type EventToNameMap, type EventToPluginMap, type EventsKeys, type ForwardToCallback, type GuardFn, type GuardFnFactory, type InterceptableMethodMap, type InterceptorFn, type LeaveFn, type LeaveState, type LifecycleApi, type LimitsConfig, type Listener, type LogCallback, type LogLevel, type LogLevelConfig, type LoggerConfig, type NavigationOptions, type Navigator, type Options, type Params, type Plugin, type PluginApi, type PluginFactory, type PluginMethod, type QueryParamsMode, type QueryParamsOptions, type Route, type RouteConfigUpdate, type RouteParams, type RouteTree, type RouteTreeState, Router, RouterError, type RouterLogger, type RouterValidator, type RoutesApi, type SerializedRouterState, type SimpleState, type State, type StateContext, type StateMetaInput, type SubscribeFn, type SubscribeState, type Subscription, type TransitionMeta, type TransitionPhase, type TransitionReason, type TreeChangedAdd, type TreeChangedClear, type TreeChangedEvent, type TreeChangedRemove, type TreeChangedReplace, type TreeChangedUpdate, type TreeStructuralPatch, UNKNOWN_ROUTE, type Unsubscribe, constants, createRouter, errorCodes, events, getNavigator, resolveForwardChain };
17
+ export { type AnyOptions, type Constants, type ContextNamespaceClaim, type DefaultDependencies, type DefaultParamsCallback, type DefaultRouteCallback, type DefaultSearchCallback, type DependenciesApi, type ErrorCodeKeys, type ErrorCodeToValueMap, type ErrorCodeValues, type ErrorCodes, type EventMethodMap, type EventName, type EventToNameMap, type EventToPluginMap, type EventsKeys, type ForwardToCallback, type GuardFn, type GuardFnFactory, type InterceptableMethodMap, type InterceptorFn, type LeaveFn, type LeaveState, type LifecycleApi, type LimitsConfig, type Listener, type LogCallback, type LogLevel, type LogLevelConfig, type LoggerConfig, type NavigationOptions, type NavigationTarget, type Navigator, type Options, type Params, type ParamsSearch, type Plugin, type PluginApi, type PluginFactory, type PluginMethod, type QueryParamsMode, type QueryParamsOptions, type Route, type RouteConfigUpdate, type RouteParams, type RouteTree, type RouteTreeState, Router, RouterError, type RouterLogger, type RouterValidator, type RoutesApi, type SearchParamPrimitive, type SearchParamValue, type SearchParams, type SerializedRouterState, type SimpleState, type State, type StateContext, type SubscribeFn, type SubscribeState, type Subscription, type TransitionMeta, type TransitionPhase, type TransitionReason, type TreeChangedAdd, type TreeChangedClear, type TreeChangedEvent, type TreeChangedRemove, type TreeChangedReplace, type TreeChangedUpdate, type TreeStructuralPatch, UNKNOWN_ROUTE, type Unsubscribe, constants, createRouter, errorCodes, events, getNavigator, resolveForwardChain };
package/dist/cjs/index.js CHANGED
@@ -1 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./constants.js"),t=require("./namespaces/RoutesNamespace/forwardChain.js"),n=require("./RouterError.js"),r=require("./Router.js"),i=require("./createRouter.js"),a=require("./getNavigator.js");exports.Router=r.Router,exports.RouterError=n.RouterError,exports.UNKNOWN_ROUTE=e.UNKNOWN_ROUTE,exports.constants=e.constants,exports.createRouter=i.createRouter,exports.errorCodes=e.errorCodes,exports.events=e.events,exports.getNavigator=a.getNavigator,exports.resolveForwardChain=t.resolveForwardChain;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Router-CCmcEi-S.js"),t=(t=[],n={},r={})=>new e.t(t,n,r),n=new WeakMap,r=e=>{let t=n.get(e);return t||(t=Object.freeze({navigate:e.navigate,getState:e.getState,isActiveRoute:e.isActiveRoute,canNavigateTo:e.canNavigateTo,subscribe:e.subscribe,subscribeLeave:e.subscribeLeave,isLeaveApproved:e.isLeaveApproved}),n.set(e,t)),t};exports.Router=e.t,exports.RouterError=e.n,exports.UNKNOWN_ROUTE=e.D,exports.constants=e.O,exports.createRouter=t,exports.errorCodes=e.k,exports.events=e.A,exports.getNavigator=r,exports.resolveForwardChain=e.g;
2
+ //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Router"],"sources":["../../src/createRouter.ts","../../src/getNavigator.ts"],"sourcesContent":["// packages/core/src/createRouter.ts\n\nimport { Router } from \"./Router\";\n\nimport type { DefaultDependencies, Options, Route } from \"./types\";\n\n/**\n * Creates a new router instance.\n *\n * @param routes - Array of route definitions\n * @param options - Router configuration options\n * @param dependencies - Dependencies to inject into the router\n * @returns A new Router instance\n *\n * @example\n * const router = createRouter([\n * { name: 'home', path: '/' },\n * { name: 'users', path: '/users' },\n * ]);\n *\n * router.start('/');\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 return new Router<Dependencies>(routes, options, dependencies);\n};\n","import type { Navigator, DefaultDependencies, Router } from \"./types\";\n\nconst cache = new WeakMap<Router, Navigator>();\n\nexport const getNavigator = <\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n): Navigator => {\n let nav = cache.get(router);\n\n if (!nav) {\n nav = Object.freeze({\n navigate: router.navigate,\n getState: router.getState,\n isActiveRoute: router.isActiveRoute,\n canNavigateTo: router.canNavigateTo,\n subscribe: router.subscribe,\n subscribeLeave: router.subscribeLeave,\n isLeaveApproved: router.isLeaveApproved,\n } as Navigator);\n cache.set(router, nav);\n }\n\n return nav;\n};\n"],"mappings":"2GAsBa,GAGX,EAAgC,CAAC,EACjC,EAA4B,CAAC,EAC7B,EAA6B,CAAC,IAEvB,IAAIA,EAAAA,EAAqB,EAAQ,EAAS,CAAY,EC3BzD,EAAQ,IAAI,QAEL,EAGX,GACc,CACd,IAAI,EAAM,EAAM,IAAI,CAAM,EAe1B,OAbK,IACH,EAAM,OAAO,OAAO,CAClB,SAAU,EAAO,SACjB,SAAU,EAAO,SACjB,cAAe,EAAO,cACtB,cAAe,EAAO,cACtB,UAAW,EAAO,UAClB,eAAgB,EAAO,eACvB,gBAAiB,EAAO,eAC1B,CAAc,EACd,EAAM,IAAI,EAAQ,CAAG,GAGhB,CACT"}
1
+ {"version":3,"file":"index.js","names":["Router"],"sources":["../../src/createRouter.ts","../../src/getNavigator.ts"],"sourcesContent":["// packages/core/src/createRouter.ts\n\nimport { Router } from \"./Router\";\n\nimport type { DefaultDependencies, Options, Route } from \"./types\";\n\n/**\n * Creates a new router instance.\n *\n * @param routes - Array of route definitions\n * @param options - Router configuration options\n * @param dependencies - Dependencies to inject into the router\n * @returns A new Router instance\n *\n * @example\n * const router = createRouter([\n * { name: 'home', path: '/' },\n * { name: 'users', path: '/users' },\n * ]);\n *\n * router.start('/');\n */\nexport const createRouter = <\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n routes: Route<Dependencies>[] = [],\n options: Partial<Options<Dependencies>> = {},\n dependencies: Dependencies = {} as Dependencies,\n): Router<Dependencies> => {\n return new Router<Dependencies>(routes, options, dependencies);\n};\n","import type { Navigator, DefaultDependencies, Router } from \"./types\";\n\nconst cache = new WeakMap<Router, Navigator>();\n\nexport const getNavigator = <\n Dependencies extends DefaultDependencies = DefaultDependencies,\n>(\n router: Router<Dependencies>,\n): Navigator => {\n let nav = cache.get(router);\n\n if (!nav) {\n nav = Object.freeze({\n navigate: router.navigate,\n getState: router.getState,\n isActiveRoute: router.isActiveRoute,\n canNavigateTo: router.canNavigateTo,\n subscribe: router.subscribe,\n subscribeLeave: router.subscribeLeave,\n isLeaveApproved: router.isLeaveApproved,\n } as Navigator);\n cache.set(router, nav);\n }\n\n return nav;\n};\n"],"mappings":"2GAsBa,GAGX,EAAgC,CAAC,EACjC,EAA0C,CAAC,EAC3C,EAA6B,CAAC,IAEvB,IAAIA,EAAAA,EAAqB,EAAQ,EAAS,CAAY,EC3BzD,EAAQ,IAAI,QAEL,EAGX,GACc,CACd,IAAI,EAAM,EAAM,IAAI,CAAM,EAe1B,OAbK,IACH,EAAM,OAAO,OAAO,CAClB,SAAU,EAAO,SACjB,SAAU,EAAO,SACjB,cAAe,EAAO,cACtB,cAAe,EAAO,cACtB,UAAW,EAAO,UAClB,eAAgB,EAAO,eACvB,gBAAiB,EAAO,eAC1B,CAAc,EACd,EAAM,IAAI,EAAQ,CAAG,GAGhB,CACT"}
@@ -1,20 +1,34 @@
1
1
  import { RouteTree } from "./engine/builder/types.js";
2
2
  import { RouteTreeState } from "./types/route-node-types.js";
3
- import { Params, SerializedRouterState, SimpleState, State, Unsubscribe } from "./types/base.js";
4
- import { DefaultDependencies, LoggerConfig, Options, Plugin, PluginFactory, Router, RouterLogger } from "./types/router.js";
3
+ import { Params, SearchParams, SerializedRouterState, SimpleState, State, Unsubscribe } from "./types/base.js";
4
+ import { AnyOptions, DefaultDependencies, LoggerConfig, Options, Plugin, PluginFactory, Router, RouterLogger } from "./types/router.js";
5
5
  import { EventMethodMap, EventName } from "./types/constants.js";
6
6
  import { TreeChangedEvent } from "./types/tree-changed.js";
7
7
  import { NavigationOptions } from "./types.js";
8
8
  import { RouterValidator } from "./types/RouterValidator.js";
9
9
  import { DependenciesStore } from "./namespaces/DependenciesNamespace/dependenciesStore.js";
10
+ import { RouteResolver } from "./pipeline/port.js";
10
11
  import { RoutesStore } from "./namespaces/RoutesNamespace/routesStore.js";
11
12
  //#region src/internals.d.ts
12
13
  interface RouterInternals<D extends DefaultDependencies = DefaultDependencies> {
13
- readonly makeState: <P extends Params = Params>(name: string, params?: P, path?: string, meta?: Record<string, Record<string, "url" | "query">>) => State<P>;
14
- readonly forwardState: <P extends Params = Params>(routeName: string, routeParams: P) => SimpleState<P>;
14
+ readonly makeState: <P extends Params = Params, S extends SearchParams = SearchParams>(name: string, params?: P, search?: S, path?: string) => State<P, S>;
15
+ /**
16
+ * Per-segment param-source map for a route name (`{ segment: { param: "url" |
17
+ * "query" } }`), read from the live matcher — the ownership channel for
18
+ * `getTransitionPath` (RFC-4 M2 / #1548, replaced the removed per-State
19
+ * `stateMetaStore` WeakMap). `undefined` when the name is not in the tree.
20
+ */
21
+ readonly getMetaForState: (name: string) => Record<string, Record<string, "url" | "query">> | undefined;
22
+ /**
23
+ * The route's DECLARED query-param names — the same registry the URL build
24
+ * prints from (#1556), minus path slots. Feeds the always-on channel guard
25
+ * (#1572); read here rather than re-derived, so classification cannot drift.
26
+ */
27
+ readonly getQueryParams: (name: string) => readonly string[];
28
+ readonly forwardState: <P extends Params = Params, S extends SearchParams = SearchParams>(routeName: string, routeParams: P, routeSearch?: S) => SimpleState<P, S>;
15
29
  readonly buildStateResolved: (resolvedName: string, resolvedParams: Params) => RouteTreeState | undefined;
16
- readonly matchPath: <P extends Params = Params>(path: string, options?: Options) => State<P> | undefined;
17
- readonly getOptions: () => Options;
30
+ readonly matchPath: <P extends Params = Params>(path: string, options?: AnyOptions) => State<P> | undefined;
31
+ readonly getOptions: () => Options<D>;
18
32
  readonly addEventListener: <E extends EventName>(eventName: E, cb: Plugin[EventMethodMap[E]]) => Unsubscribe;
19
33
  /**
20
34
  * Route-tree mutation channel — internal access for the `getRoutesApi`
@@ -33,7 +47,15 @@ interface RouterInternals<D extends DefaultDependencies = DefaultDependencies> {
33
47
  */
34
48
  readonly isEmitting: () => boolean;
35
49
  };
36
- readonly buildPath: (route: string, params?: Params) => string;
50
+ readonly buildPath: (route: string, params?: Params, search?: SearchParams) => string;
51
+ /**
52
+ * The navigation pipeline's read-model, for entry points that live on this
53
+ * plugin-facing surface rather than in a namespace. Resolved LAZILY: the port
54
+ * is created during wiring, and `registerInternals` runs before that, so the
55
+ * accessor is a closure rather than a value — the same shape the interceptable
56
+ * methods above already use.
57
+ */
58
+ readonly port: () => RouteResolver;
37
59
  readonly emitTransitionError: (error: Error) => void;
38
60
  /**
39
61
  * Emits `TRANSITION_SUCCESS` directly (no FSM transition) — used by
@@ -67,7 +89,7 @@ interface RouterInternals<D extends DefaultDependencies = DefaultDependencies> {
67
89
  readonly logger: RouterLogger;
68
90
  readonly dependenciesGetStore: () => DependenciesStore<D>;
69
91
  readonly getCloneState: () => {
70
- options: Options;
92
+ options: Options<D>;
71
93
  dependencies: Record<string, unknown>;
72
94
  pluginFactories: PluginFactory<D>[];
73
95
  loggerConfig: LoggerConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"internals.d.ts","names":[],"sources":["../../src/internals.ts"],"mappings":";;;;;;;;;;;UAyBiB,gBACf,UAAU,sBAAsB;WAEvB,YAAY,UAAU,SAAS,QACtC,cACA,SAAS,GACT,eACA,OAAO,eAAe,qCACnB,MAAM;WAEF,eAAe,UAAU,SAAS,QACzC,mBACA,aAAa,MACV,YAAY;WAER,qBACP,sBACA,gBAAgB,WACb;WAEI,YAAY,UAAU,SAAS,QACtC,cACA,UAAU,YACP,MAAM;WAEF,kBAAkB;WAElB,mBAAmB,UAAU,WACpC,WAAW,GACX,IAAI,OAAO,eAAe,QACvB;;;;;;;;WASI;aACE,OAAO,OAAO;aACd,YACP,UAAU,OAAO,8BACd;aACI;;;;;aAKA;;WAGF,YAAY,eAAe,SAAS;WAEpC,sBAAsB,OAAO;;;;;;;WAQ7B,wBACP,SAAS,OACT,WAAW,mBACX,OAAO;;;;;;;;WAUA,qBAAqB,iBAAiB;WAEtC,QAAQ,iBAAiB,QAAQ;;;;;;;WAQjC,kBACP,OAAO,OACP,UAAU,sBACP,QAAQ;WAGJ,cAAc,cAEnB,UAAU,wBAAwB;WAI7B,cAAc;WACd;WAEA,eAAe;WAEf;EAET,WAAW;WAQF,QAAQ;WAGR,4BAA4B,kBAAkB;WAM9C;IACP,SAAS;IACT,cAAc;IACd,iBAAiB,cAAc;IAK/B,cAAc;;WAIP,qBAAqB,YAAY;WAGjC;WACA;WACA;WACA,WAAW,OAAO;WAClB;IAAoB;;WACpB,qBAAqB;;;;;;;;;;EAW9B,gBAAgB;;iBAMF,aAAa,UAAU,qBACrC,QAAQ,OAAgB,KACvB,gBAAgB"}
1
+ {"version":3,"file":"internals.d.ts","names":[],"sources":["../../src/internals.ts"],"mappings":";;;;;;;;;;;;UA8BiB,gBACf,UAAU,sBAAsB;WAEvB,YACP,UAAU,SAAS,QACnB,UAAU,eAAe,cAEzB,cACA,SAAS,GACT,SAAS,GACT,kBACG,MAAM,GAAG;;;;;;;WAQL,kBACP,iBACG,eAAe;;;;;;WAOX,iBAAiB;WAEjB,eACP,UAAU,SAAS,QACnB,UAAU,eAAe,cAEzB,mBACA,aAAa,GACb,cAAc,MACX,YAAY,GAAG;WAEX,qBACP,sBACA,gBAAgB,WACb;WAEI,YAAY,UAAU,SAAS,QACtC,cACA,UAAU,eACP,MAAM;WAEF,kBAAkB,QAAQ;WAE1B,mBAAmB,UAAU,WACpC,WAAW,GACX,IAAI,OAAO,eAAe,QACvB;;;;;;;;WASI;aACE,OAAO,OAAO;aACd,YACP,UAAU,OAAO,8BACd;aACI;;;;;aAKA;;WAGF,YACP,eACA,SAAS,QACT,SAAS;;;;;;;;WAUF,YAAY;WAEZ,sBAAsB,OAAO;;;;;;;WAQ7B,wBACP,SAAS,OACT,WAAW,mBACX,OAAO;;;;;;;;WAUA,qBAAqB,iBAAiB;WAEtC,QAAQ,iBAAiB,QAAQ;;;;;;;WAQjC,kBACP,OAAO,OACP,UAAU,sBACP,QAAQ;WAGJ,cAAc,cAEnB,UAAU,wBAAwB;WAI7B,cAAc;WACd;WAEA,eAAe;WAEf;EAET,WAAW;WAQF,QAAQ;WAGR,4BAA4B,kBAAkB;WAM9C;IACP,SAAS,QAAQ;IACjB,cAAc;IACd,iBAAiB,cAAc;IAK/B,cAAc;;WAIP,qBAAqB,YAAY;WAGjC;WACA;WACA;WACA,WAAW,OAAO;WAClB;IAAoB;;WACpB,qBAAqB;;;;;;;;;;EAW9B,gBAAgB;;iBAMF,aAAa,UAAU,qBACrC,QAAQ,OAAgB,KACvB,gBAAgB"}
@@ -1,2 +1,2 @@
1
- const e=new WeakMap;function t(t){let n=e.get(t);if(!n)throw TypeError(`[real-router] Invalid router instance — not found in internals registry`);return n}function n(t,n){e.set(t,n)}function r(e,t,n){let r=t;for(let t of e){let e=r;r=(...n)=>t(e,...n)}return r(...n)}function i(e,t,n){return((...i)=>{let a=n.get(e);return!a||a.length===0?t(...i):r(a,t,i)})}function a(e,t,n){return(i,a)=>{let o=n.get(e);return!o||o.length===0?t(i,a):r(o,t,[i,a])}}exports.createBinaryInterceptable=a,exports.createInterceptable=i,exports.getInternals=t,exports.registerInternals=n;
1
+ const e=require("./channels/guard.js"),t=new WeakMap;function n(e){let n=t.get(e);if(!n)throw TypeError(`[real-router] Invalid router instance — not found in internals registry`);return n}function r(t,n,r,i){e.assertChannelCorrect(n,r,i,t.getQueryParams(r))}function i(e,n){t.set(e,n)}function a(e,t,n){let r=t;for(let t of e){let e=r;r=(...n)=>t(e,...n)}return r(...n)}function o(e,t,n){return((...r)=>{let i=n.get(e);return!i||i.length===0?t(...r):a(i,t,r)})}function s(e,t,n){return(r,i,o)=>{let s=n.get(e);return!s||s.length===0?t(r,i,o):a(s,t,[r,i,o])}}exports.createInterceptable=o,exports.createTernaryInterceptable=s,exports.getInternals=n,exports.registerInternals=i,exports.throwOnMisChanneledKey=r;
2
2
  //# sourceMappingURL=internals.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"internals.js","names":[],"sources":["../../src/internals.ts"],"sourcesContent":["import type { RouteTree } from \"./engine\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type {\n DefaultDependencies,\n EventName,\n LoggerConfig,\n NavigationOptions,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouterLogger,\n RouteTreeState,\n SerializedRouterState,\n SimpleState,\n State,\n TreeChangedEvent,\n Unsubscribe,\n EventMethodMap,\n PluginFactory,\n} from \"./types\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <P extends Params = Params>(\n name: string,\n params?: P,\n path?: string,\n meta?: Record<string, Record<string, \"url\" | \"query\">>,\n ) => State<P>;\n\n readonly forwardState: <P extends Params = Params>(\n routeName: string,\n routeParams: P,\n ) => SimpleState<P>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params>(\n path: string,\n options?: Options,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n /**\n * Route-tree mutation channel — internal access for the `getRoutesApi`\n * wrapper. A dedicated bridge is required because the public\n * `addEventListener<E extends EventName>` structurally rejects\n * `\"TREE_CHANGED\"` (it is not in the public `EventName` union), is strict on\n * duplicates, and exposes neither `emit` nor `listenerCount`.\n */\n readonly treeChanged: {\n readonly emit: (event: TreeChangedEvent) => void;\n readonly subscribe: (\n handler: (event: TreeChangedEvent) => void,\n ) => Unsubscribe;\n readonly listenerCount: () => number;\n /**\n * True while a `TREE_CHANGED` emit is on the stack — `getRoutesApi` reads it\n * to reject reentrant route-CRUD from a `subscribeChanges` handler (#1032).\n */\n readonly isEmitting: () => boolean;\n };\n\n readonly buildPath: (route: string, params?: Params) => string;\n\n readonly emitTransitionError: (error: Error) => void;\n\n /**\n * Emits `TRANSITION_SUCCESS` directly (no FSM transition) — used by\n * `getRoutesApi().replace()` to notify `router.subscribe` listeners when a\n * structural replace revalidates the active state (#950). Mirrors the success\n * emission `completeTransition` / `navigateToNotFound` perform.\n */\n readonly emitTransitionSuccess: (\n toState: State,\n fromState: State | undefined,\n opts?: NavigationOptions,\n ) => void;\n\n /**\n * Commits the not-found (`UNKNOWN_ROUTE`) state for `path` and emits\n * `TRANSITION_SUCCESS` — the `NavigationNamespace.navigateToNotFound`\n * primitive. `replace()` uses it when a structural replace drops the active\n * route, so subscribers are notified instead of the state silently clearing\n * (#950).\n */\n readonly navigateToNotFound: (path: string) => State;\n\n readonly start: (path: string) => Promise<State>;\n\n /**\n * Plugin-only navigation entry point — delegates to\n * `NavigationNamespace.navigateToState` (`getPluginApi(router).navigateToState`).\n * Hidden from `Router`/`Navigator` to keep the userland surface minimal;\n * see `core-types/src/api.ts` for usage docs.\n */\n readonly navigateToState: (\n state: State,\n options?: NavigationOptions,\n ) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Per-router logger instance (built from `options.logger` in the Router\n // constructor). The facade reads it as `getInternals(this).logger`; namespaces\n // receive it via their deps at wiring; plugins reach it through\n // `getPluginApi(router).logger`. Replaces the former process-global singleton\n // from the standalone `@real-router/logger` package (now folded into\n // `foundation/logger`), whose `configure()` leaked across routers (#724).\n readonly logger: RouterLogger;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173, consolidated #964). One accessor for the\n // source-side snapshot a clone carries over besides the route store, so a new\n // clone-relevant subsystem is wired in a single place instead of being spread\n // across separate methods.\n readonly getCloneState: () => {\n options: Options;\n dependencies: Record<string, unknown>;\n pluginFactories: PluginFactory<D>[];\n // Resolved logger config of the base router, so a clone can build its OWN\n // logger inheriting the base's level/callback. Frozen `options` do NOT carry\n // `logger` (stripped in the constructor), so `options` above can't convey it;\n // cloneRouter merges a per-request override (traceId) over this snapshot.\n loggerConfig: LoggerConfig;\n };\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n readonly clearState: () => void;\n readonly setState: (state: State) => void;\n readonly routerExtensions: { keys: string[] }[];\n readonly contextClaimRecords: Set<string>;\n\n /**\n * One-shot hydration scratchpad populated by `hydrateRouter` immediately\n * before delegating to `router.start(parsed.path)` and cleared in the\n * matching `finally`. SSR loader plugins read this slot directly via\n * `getInternals(router).hydrationState` to short-circuit their own loader\n * call when the server-resolved namespace value is already present in the\n * parsed state (#596). `null` outside of an active `hydrateRouter`\n * invocation.\n */\n hydrationState: SerializedRouterState | null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n\n chain = (...chainArgs: any[]) => interceptor(prev, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\n/**\n * Variadic interceptor wrapper — wraps a function of any arity, returning the\n * same callable type `T`. Use {@link createBinaryInterceptable} instead when the\n * wrapped method takes exactly two args and the caller needs the precise\n * `(a, b) => r` signature preserved (the variadic form widens args to `any[]`).\n */\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\n/**\n * Two-argument interceptor wrapper — preserves the exact `(a: A, b: B) => R`\n * signature, which the variadic {@link createInterceptable} cannot express\n * (it widens args to `any[]`). Used for the binary interceptable methods\n * `forwardState(routeName, routeParams)` and `buildPath(route, params)`.\n */\nexport function createBinaryInterceptable<A, B, R>(\n name: string,\n original: (a: A, b: B) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B) => R {\n return (arg1: A, arg2: B) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\n"],"mappings":"AAqLA,MAAM,EAAY,IAAI,QAEtB,SAAgB,EACd,EACoB,CACpB,IAAM,EAAM,EAAU,IAAI,CAAM,EAEhC,GAAI,CAAC,EACH,MAAU,UACR,yEACF,EAGF,OAAO,CACT,CAEA,SAAgB,EACd,EACA,EACM,CACN,EAAU,IAAI,EAAQ,CAAG,CAC3B,CAGA,SAAS,EACP,EACA,EACA,EACG,CACH,IAAI,EAAQ,EAEZ,IAAK,IAAM,KAAe,EAAc,CACtC,IAAM,EAAO,EAEb,GAAS,GAAG,IAAqB,EAAY,EAAM,GAAG,CAAS,CACjE,CAEA,OAAO,EAAM,GAAG,CAAI,CACtB,CAQA,SAAgB,EACd,EACA,EACA,EAIG,CACH,QAAS,GAAG,IAAgB,CAC1B,IAAM,EAAQ,EAAa,IAAI,CAAI,EAMnC,MAJI,CAAC,GAAS,EAAM,SAAW,EACtB,EAAS,GAAG,CAAI,EAGlB,EAAwB,EAAO,EAAU,CAAI,CACtD,EACF,CAQA,SAAgB,EACd,EACA,EACA,EAImB,CACnB,OAAQ,EAAS,IAAY,CAC3B,IAAM,EAAQ,EAAa,IAAI,CAAI,EAMnC,MAJI,CAAC,GAAS,EAAM,SAAW,EACtB,EAAS,EAAM,CAAI,EAGrB,EAAwB,EAAO,EAAU,CAAC,EAAM,CAAI,CAAC,CAC9D,CACF"}
1
+ {"version":3,"file":"internals.js","names":[],"sources":["../../src/internals.ts"],"sourcesContent":["import { assertChannelCorrect } from \"./channels\";\n\nimport type { RouteTree } from \"./engine\";\nimport type { DependenciesStore } from \"./namespaces\";\nimport type { RoutesStore } from \"./namespaces/RoutesNamespace\";\nimport type { RouteResolver } from \"./pipeline\";\nimport type { Router as RouterClass } from \"./Router\";\nimport type {\n AnyOptions,\n DefaultDependencies,\n EventName,\n LoggerConfig,\n NavigationOptions,\n Options,\n Params,\n Plugin,\n Router as RouterInterface,\n RouterLogger,\n RouteTreeState,\n SearchParams,\n SerializedRouterState,\n SimpleState,\n State,\n TreeChangedEvent,\n Unsubscribe,\n EventMethodMap,\n PluginFactory,\n} from \"./types\";\nimport type { RouterValidator } from \"./types/RouterValidator\";\n\nexport interface RouterInternals<\n D extends DefaultDependencies = DefaultDependencies,\n> {\n readonly makeState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n name: string,\n params?: P,\n search?: S,\n path?: string,\n ) => State<P, S>;\n\n /**\n * Per-segment param-source map for a route name (`{ segment: { param: \"url\" |\n * \"query\" } }`), read from the live matcher — the ownership channel for\n * `getTransitionPath` (RFC-4 M2 / #1548, replaced the removed per-State\n * `stateMetaStore` WeakMap). `undefined` when the name is not in the tree.\n */\n readonly getMetaForState: (\n name: string,\n ) => Record<string, Record<string, \"url\" | \"query\">> | undefined;\n\n /**\n * The route's DECLARED query-param names — the same registry the URL build\n * prints from (#1556), minus path slots. Feeds the always-on channel guard\n * (#1572); read here rather than re-derived, so classification cannot drift.\n */\n readonly getQueryParams: (name: string) => readonly string[];\n\n readonly forwardState: <\n P extends Params = Params,\n S extends SearchParams = SearchParams,\n >(\n routeName: string,\n routeParams: P,\n routeSearch?: S,\n ) => SimpleState<P, S>;\n\n readonly buildStateResolved: (\n resolvedName: string,\n resolvedParams: Params,\n ) => RouteTreeState | undefined;\n\n readonly matchPath: <P extends Params = Params>(\n path: string,\n options?: AnyOptions,\n ) => State<P> | undefined;\n\n readonly getOptions: () => Options<D>;\n\n readonly addEventListener: <E extends EventName>(\n eventName: E,\n cb: Plugin[EventMethodMap[E]],\n ) => Unsubscribe;\n\n /**\n * Route-tree mutation channel — internal access for the `getRoutesApi`\n * wrapper. A dedicated bridge is required because the public\n * `addEventListener<E extends EventName>` structurally rejects\n * `\"TREE_CHANGED\"` (it is not in the public `EventName` union), is strict on\n * duplicates, and exposes neither `emit` nor `listenerCount`.\n */\n readonly treeChanged: {\n readonly emit: (event: TreeChangedEvent) => void;\n readonly subscribe: (\n handler: (event: TreeChangedEvent) => void,\n ) => Unsubscribe;\n readonly listenerCount: () => number;\n /**\n * True while a `TREE_CHANGED` emit is on the stack — `getRoutesApi` reads it\n * to reject reentrant route-CRUD from a `subscribeChanges` handler (#1032).\n */\n readonly isEmitting: () => boolean;\n };\n\n readonly buildPath: (\n route: string,\n params?: Params,\n search?: SearchParams,\n ) => string;\n\n /**\n * The navigation pipeline's read-model, for entry points that live on this\n * plugin-facing surface rather than in a namespace. Resolved LAZILY: the port\n * is created during wiring, and `registerInternals` runs before that, so the\n * accessor is a closure rather than a value — the same shape the interceptable\n * methods above already use.\n */\n readonly port: () => RouteResolver;\n\n readonly emitTransitionError: (error: Error) => void;\n\n /**\n * Emits `TRANSITION_SUCCESS` directly (no FSM transition) — used by\n * `getRoutesApi().replace()` to notify `router.subscribe` listeners when a\n * structural replace revalidates the active state (#950). Mirrors the success\n * emission `completeTransition` / `navigateToNotFound` perform.\n */\n readonly emitTransitionSuccess: (\n toState: State,\n fromState: State | undefined,\n opts?: NavigationOptions,\n ) => void;\n\n /**\n * Commits the not-found (`UNKNOWN_ROUTE`) state for `path` and emits\n * `TRANSITION_SUCCESS` — the `NavigationNamespace.navigateToNotFound`\n * primitive. `replace()` uses it when a structural replace drops the active\n * route, so subscribers are notified instead of the state silently clearing\n * (#950).\n */\n readonly navigateToNotFound: (path: string) => State;\n\n readonly start: (path: string) => Promise<State>;\n\n /**\n * Plugin-only navigation entry point — delegates to\n * `NavigationNamespace.navigateToState` (`getPluginApi(router).navigateToState`).\n * Hidden from `Router`/`Navigator` to keep the userland surface minimal;\n * see `core-types/src/api.ts` for usage docs.\n */\n readonly navigateToState: (\n state: State,\n options?: NavigationOptions,\n ) => Promise<State>;\n\n /* eslint-disable @typescript-eslint/no-explicit-any -- heterogeneous map: stores different InterceptorFn<M> types under different keys */\n readonly interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >;\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n readonly setRootPath: (rootPath: string) => void;\n readonly getRootPath: () => string;\n\n readonly getTree: () => RouteTree;\n\n readonly isDisposed: () => boolean;\n\n validator: RouterValidator | null;\n\n // Per-router logger instance (built from `options.logger` in the Router\n // constructor). The facade reads it as `getInternals(this).logger`; namespaces\n // receive it via their deps at wiring; plugins reach it through\n // `getPluginApi(router).logger`. Replaces the former process-global singleton\n // from the standalone `@real-router/logger` package (now folded into\n // `utils/logger`), whose `configure()` leaked across routers (#724).\n readonly logger: RouterLogger;\n\n // Dependencies (issue #172)\n readonly dependenciesGetStore: () => DependenciesStore<D>;\n\n // Clone support (issue #173, consolidated #964). One accessor for the\n // source-side snapshot a clone carries over besides the route store, so a new\n // clone-relevant subsystem is wired in a single place instead of being spread\n // across separate methods.\n readonly getCloneState: () => {\n options: Options<D>;\n dependencies: Record<string, unknown>;\n pluginFactories: PluginFactory<D>[];\n // Resolved logger config of the base router, so a clone can build its OWN\n // logger inheriting the base's level/callback. Frozen `options` do NOT carry\n // `logger` (stripped in the constructor), so `options` above can't convey it;\n // cloneRouter merges a per-request override (traceId) over this snapshot.\n loggerConfig: LoggerConfig;\n };\n\n // Consolidated route data store (issue #174 Phase 2)\n readonly routeGetStore: () => RoutesStore<D>;\n\n // Cross-namespace state (issue #174)\n readonly getStateName: () => string | undefined;\n readonly isTransitioning: () => boolean;\n readonly clearState: () => void;\n readonly setState: (state: State) => void;\n readonly routerExtensions: { keys: string[] }[];\n readonly contextClaimRecords: Set<string>;\n\n /**\n * One-shot hydration scratchpad populated by `hydrateRouter` immediately\n * before delegating to `router.start(parsed.path)` and cleared in the\n * matching `finally`. SSR loader plugins read this slot directly via\n * `getInternals(router).hydrationState` to short-circuit their own loader\n * call when the server-resolved namespace value is already present in the\n * parsed state (#596). `null` outside of an active `hydrateRouter`\n * invocation.\n */\n hydrationState: SerializedRouterState | null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- existential type: stores RouterInternals for all Dependencies types\nconst internals = new WeakMap<object, RouterInternals<any>>();\n\nexport function getInternals<D extends DefaultDependencies>(\n router: RouterInterface<D>,\n): RouterInternals<D> {\n const ctx = internals.get(router);\n\n if (!ctx) {\n throw new TypeError(\n \"[real-router] Invalid router instance — not found in internals registry\",\n );\n }\n\n return ctx as RouterInternals<D>;\n}\n\n/**\n * Channel guard, position P1 (#1572) — the caller's RAW `params` argument, at\n * the API boundary and BEFORE any interceptor runs, so what it reports is what\n * the CALLER wrote (a plugin's later injection is P2's population, not this one).\n *\n * THROWS. The warn-first step (#1572) announced the contract so every call site\n * could identify itself in the logs; this is the promotion it announced.\n *\n * A `TypeError`, synchronous, rather than a `RouterError` on a rejected promise:\n * this is an ARGUMENT-shape defect at the API boundary, caught before any\n * interceptor or transition exists — the same class as the `subscribe` /\n * `navigateToNotFound` / `start` guards beside it. Rejecting instead would let a\n * `.catch()` written for navigation failures swallow a programming error.\n *\n * P3 (`navigateToState`) keeps REJECTING — deliberately asymmetric, because it\n * takes a ready-made `State` from a popstate handler, where a new synchronous\n * throw would change an existing method's failure shape.\n *\n * The predicates (`buildPath` / `isActiveRoute` / `canNavigateTo`) are still NOT\n * instrumented: they run on every `<Link>` render, an answer there is read\n * immediately and corrupts nothing, and throwing inside a render in six adapters\n * is not a trade this guard is worth.\n *\n * ⚠ Not instrumented ≠ blind. `canNavigateTo` answers whether `navigate` WOULD\n * work, so it consults {@link findMisChanneledKey} directly and returns `false`\n * for a shape this function would have thrown on (#1576) — an answer, not a\n * throw, so the render-path trade above is untouched. `buildPath` /\n * `isActiveRoute` ask a different question and are unchanged.\n *\n * @internal\n */\nexport function throwOnMisChanneledKey<D extends DefaultDependencies>(\n ctx: RouterInternals<D>,\n method: string,\n routeName: string,\n params: Params | undefined,\n): void {\n assertChannelCorrect(\n method,\n routeName,\n params,\n ctx.getQueryParams(routeName),\n );\n}\n\nexport function registerInternals<D extends DefaultDependencies>(\n router: RouterClass<D>,\n ctx: RouterInternals<D>,\n): void {\n internals.set(router, ctx);\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument -- internal chain execution: type safety enforced at public API boundary (PluginApi.addInterceptor) */\nfunction executeInterceptorChain<T>(\n interceptors: ((next: (...args: any[]) => any, ...args: any[]) => any)[],\n original: (...args: any[]) => T,\n args: any[],\n): T {\n let chain = original as (...args: any[]) => any;\n\n for (const interceptor of interceptors) {\n const prev = chain;\n\n chain = (...chainArgs: any[]) => interceptor(prev, ...chainArgs);\n }\n\n return chain(...args) as T;\n}\n\n/**\n * Variadic interceptor wrapper — wraps a function of any arity, returning the\n * same callable type `T`. Use {@link createTernaryInterceptable} instead when\n * the wrapped method takes exactly three args and the caller needs the precise\n * `(a, b, c) => r` signature preserved (the variadic form widens args to\n * `any[]`).\n */\nexport function createInterceptable<T extends (...args: any[]) => any>(\n name: string,\n original: T,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): T {\n return ((...args: any[]) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(...args);\n }\n\n return executeInterceptorChain(chain, original, args);\n }) as T;\n}\n\n/**\n * Three-argument interceptor wrapper — preserves the exact\n * `(a: A, b: B, c: C) => R` signature that the variadic\n * {@link createInterceptable} widens to `any[]`. Backs both search-aware\n * interceptables — `buildPath(route, params, search)` and\n * `forwardState(name, params, search)` (RFC-4 M2 / #1548). Every first-party\n * plugin registers the full three-argument form; a shorter-arity interceptor\n * from a third party remains type-valid (TS allows fewer params, and `next(a,\n * b)` leaves the third arg `undefined`).\n */\nexport function createTernaryInterceptable<A, B, C, R>(\n name: string,\n original: (a: A, b: B, c: C) => R,\n interceptors: Map<\n string,\n ((next: (...args: any[]) => any, ...args: any[]) => any)[]\n >,\n): (a: A, b: B, c: C) => R {\n return (arg1: A, arg2: B, arg3: C) => {\n const chain = interceptors.get(name);\n\n if (!chain || chain.length === 0) {\n return original(arg1, arg2, arg3);\n }\n\n return executeInterceptorChain(chain, original, [arg1, arg2, arg3]);\n };\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */\n"],"mappings":"uCA+NM,EAAY,IAAI,QAEtB,SAAgB,EACd,EACoB,CACpB,IAAM,EAAM,EAAU,IAAI,CAAM,EAEhC,GAAI,CAAC,EACH,MAAU,UACR,yEACF,EAGF,OAAO,CACT,CAiCA,SAAgB,EACd,EACA,EACA,EACA,EACM,CACN,EAAA,qBACE,EACA,EACA,EACA,EAAI,eAAe,CAAS,CAC9B,CACF,CAEA,SAAgB,EACd,EACA,EACM,CACN,EAAU,IAAI,EAAQ,CAAG,CAC3B,CAGA,SAAS,EACP,EACA,EACA,EACG,CACH,IAAI,EAAQ,EAEZ,IAAK,IAAM,KAAe,EAAc,CACtC,IAAM,EAAO,EAEb,GAAS,GAAG,IAAqB,EAAY,EAAM,GAAG,CAAS,CACjE,CAEA,OAAO,EAAM,GAAG,CAAI,CACtB,CASA,SAAgB,EACd,EACA,EACA,EAIG,CACH,QAAS,GAAG,IAAgB,CAC1B,IAAM,EAAQ,EAAa,IAAI,CAAI,EAMnC,MAJI,CAAC,GAAS,EAAM,SAAW,EACtB,EAAS,GAAG,CAAI,EAGlB,EAAwB,EAAO,EAAU,CAAI,CACtD,EACF,CAYA,SAAgB,EACd,EACA,EACA,EAIyB,CACzB,OAAQ,EAAS,EAAS,IAAY,CACpC,IAAM,EAAQ,EAAa,IAAI,CAAI,EAMnC,MAJI,CAAC,GAAS,EAAM,SAAW,EACtB,EAAS,EAAM,EAAM,CAAI,EAG3B,EAAwB,EAAO,EAAU,CAAC,EAAM,EAAM,CAAI,CAAC,CACpE,CACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("./constants.js");function t(t={}){return{...e.DEFAULT_LIMITS,...t}}exports.createLimits=t;
2
+ //# sourceMappingURL=limits.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.js","names":["DEFAULT_LIMITS"],"sources":["../../src/limits.ts"],"sourcesContent":["// packages/core/src/limits.ts\n\nimport { DEFAULT_LIMITS } from \"./constants\";\n\nimport type { LimitsConfig } from \"./types\";\nimport type { Limits } from \"./types/internal\";\n\n/**\n * Merges user limits with the defaults; returns a frozen-by-type value.\n *\n * Its own module rather than a corner of `helpers.ts`, where it sat until the\n * applicability audit: resource limits share nothing with that file's subject —\n * path/query channels, the default merge, value comparison, the state shape —\n * and a reader scanning `helpers.ts` for the channel model had to step over it.\n * The two places it could have gone instead both cost more than they save:\n * `types/limits.ts` is a TYPES module (and is re-exported into the public\n * `@real-router/core/types` entry, where runtime code has no business, least of\n * all under the two-phase dts build the augmentation invariant depends on), and\n * `constants.ts` exports no functions at all.\n *\n * @internal\n */\nexport function createLimits(userLimits: Partial<LimitsConfig> = {}): Limits {\n return { ...DEFAULT_LIMITS, ...userLimits };\n}\n"],"mappings":"kCAsBA,SAAgB,EAAa,EAAoC,CAAC,EAAW,CAC3E,MAAO,CAAE,GAAGA,EAAAA,eAAgB,GAAG,CAAW,CAC5C"}