@timber-js/app 0.2.0-alpha.190 → 0.2.0-alpha.192

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 (123) hide show
  1. package/dist/_chunks/{actions-35jnMdeJ.js → actions-BjbbNRFN.js} +3 -3
  2. package/dist/_chunks/{actions-35jnMdeJ.js.map → actions-BjbbNRFN.js.map} +1 -1
  3. package/dist/_chunks/als-registry-C6kcfprT.js.map +1 -1
  4. package/dist/_chunks/als-slots-BEEIPKYm.js.map +1 -1
  5. package/dist/_chunks/{cache-api-DjNrIWRR.js → cache-api-DllJ-Lyw.js} +2 -2
  6. package/dist/_chunks/{cache-api-DjNrIWRR.js.map → cache-api-DllJ-Lyw.js.map} +1 -1
  7. package/dist/_chunks/{cli-check-CpmN7Nh-.js → cli-check-DJZDc22E.js} +3 -3
  8. package/dist/_chunks/{cli-check-CpmN7Nh-.js.map → cli-check-DJZDc22E.js.map} +1 -1
  9. package/dist/_chunks/{cli-schema-sync-CGMp_Psg.js → cli-schema-sync-D4_AZVUb.js} +2 -2
  10. package/dist/_chunks/{cli-schema-sync-CGMp_Psg.js.map → cli-schema-sync-D4_AZVUb.js.map} +1 -1
  11. package/dist/_chunks/{convention-lint-kXsgc_-7.js → convention-lint-CpteIpTm.js} +2 -2
  12. package/dist/_chunks/{convention-lint-kXsgc_-7.js.map → convention-lint-CpteIpTm.js.map} +1 -1
  13. package/dist/_chunks/{logger-D8xJZXIN.js → logger-CH7IcMmg.js} +1 -16
  14. package/dist/_chunks/{logger-D8xJZXIN.js.map → logger-CH7IcMmg.js.map} +1 -1
  15. package/dist/_chunks/{scanner-C8b0Gcw3.js → scanner-CAietmj4.js} +2 -2
  16. package/dist/_chunks/{scanner-C8b0Gcw3.js.map → scanner-CAietmj4.js.map} +1 -1
  17. package/dist/_chunks/segment-context-CjOlyB8Y.js.map +1 -1
  18. package/dist/_chunks/segment-keys-BawYuNFO.js.map +1 -1
  19. package/dist/_chunks/slot-params-BCTmZkQB.js.map +1 -1
  20. package/dist/_chunks/ssr-data-14MXm7Pj.js.map +1 -1
  21. package/dist/_chunks/use-segment-params-C4r4BD9T.js.map +1 -1
  22. package/dist/_chunks/{walkers-RzN6AFjr.js → walkers-BsVLmD1S.js} +2 -2
  23. package/dist/_chunks/{walkers-RzN6AFjr.js.map → walkers-BsVLmD1S.js.map} +1 -1
  24. package/dist/cache/index.js +1 -1
  25. package/dist/cli.js +2 -2
  26. package/dist/client/internal.js.map +1 -1
  27. package/dist/client/params-context.d.ts +2 -1
  28. package/dist/client/params-context.d.ts.map +1 -1
  29. package/dist/client/ssr-data.d.ts +2 -1
  30. package/dist/client/ssr-data.d.ts.map +1 -1
  31. package/dist/client/state.d.ts +3 -2
  32. package/dist/client/state.d.ts.map +1 -1
  33. package/dist/client/use-segment-params.d.ts +5 -4
  34. package/dist/client/use-segment-params.d.ts.map +1 -1
  35. package/dist/config-types.d.ts +24 -6
  36. package/dist/config-types.d.ts.map +1 -1
  37. package/dist/index.js +35 -32
  38. package/dist/index.js.map +1 -1
  39. package/dist/plugins/mdx.d.ts +17 -4
  40. package/dist/plugins/mdx.d.ts.map +1 -1
  41. package/dist/plugins/server-bundle.d.ts.map +1 -1
  42. package/dist/routing/index.js +2 -2
  43. package/dist/routing/segment-keys.d.ts +2 -1
  44. package/dist/routing/segment-keys.d.ts.map +1 -1
  45. package/dist/server/action-handler.d.ts.map +1 -1
  46. package/dist/server/als-registry.d.ts +10 -5
  47. package/dist/server/als-registry.d.ts.map +1 -1
  48. package/dist/server/chain-url-parts.d.ts +2 -1
  49. package/dist/server/chain-url-parts.d.ts.map +1 -1
  50. package/dist/server/index.d.ts +1 -0
  51. package/dist/server/index.d.ts.map +1 -1
  52. package/dist/server/index.js +2 -2
  53. package/dist/server/internal.js +3 -3
  54. package/dist/server/internal.js.map +1 -1
  55. package/dist/server/metadata-collector.d.ts +40 -18
  56. package/dist/server/metadata-collector.d.ts.map +1 -1
  57. package/dist/server/param-coercion.d.ts +2 -1
  58. package/dist/server/param-coercion.d.ts.map +1 -1
  59. package/dist/server/pipeline-phases.d.ts.map +1 -1
  60. package/dist/server/pipeline.d.ts +3 -2
  61. package/dist/server/pipeline.d.ts.map +1 -1
  62. package/dist/server/prebuilt/cache-key.d.ts +2 -1
  63. package/dist/server/prebuilt/cache-key.d.ts.map +1 -1
  64. package/dist/server/prebuilt/payload-source.d.ts +2 -1
  65. package/dist/server/prebuilt/payload-source.d.ts.map +1 -1
  66. package/dist/server/prebuilt/synthetic-store.d.ts +2 -1
  67. package/dist/server/prebuilt/synthetic-store.d.ts.map +1 -1
  68. package/dist/server/prebuilt-builder.d.ts +4 -3
  69. package/dist/server/prebuilt-builder.d.ts.map +1 -1
  70. package/dist/server/prebuilt-runtime.d.ts.map +1 -1
  71. package/dist/server/request-context.d.ts +6 -5
  72. package/dist/server/request-context.d.ts.map +1 -1
  73. package/dist/server/route-element-builder.d.ts.map +1 -1
  74. package/dist/server/sitemap-generator.d.ts +2 -1
  75. package/dist/server/sitemap-generator.d.ts.map +1 -1
  76. package/dist/server/slot-resolver.d.ts +1 -1
  77. package/dist/server/slot-resolver.d.ts.map +1 -1
  78. package/dist/server/ssr-bridge-types.d.ts +5 -3
  79. package/dist/server/ssr-bridge-types.d.ts.map +1 -1
  80. package/dist/server/types.d.ts +2 -1
  81. package/dist/server/types.d.ts.map +1 -1
  82. package/dist/shared/als-slots.d.ts +3 -2
  83. package/dist/shared/als-slots.d.ts.map +1 -1
  84. package/dist/shared/param-value.d.ts +25 -1
  85. package/dist/shared/param-value.d.ts.map +1 -1
  86. package/dist/shared/payload-root.d.ts +2 -1
  87. package/dist/shared/payload-root.d.ts.map +1 -1
  88. package/dist/shared/slot-params.d.ts +4 -3
  89. package/dist/shared/slot-params.d.ts.map +1 -1
  90. package/docs/api/34-api-config.mdx +9 -8
  91. package/docs/more/04b-mdx.mdx +38 -18
  92. package/package.json +7 -3
  93. package/src/client/params-context.ts +2 -2
  94. package/src/client/ssr-data.ts +2 -1
  95. package/src/client/state.ts +3 -2
  96. package/src/client/use-segment-params.ts +6 -5
  97. package/src/config-types.ts +27 -7
  98. package/src/plugins/mdx.ts +69 -35
  99. package/src/plugins/server-bundle.ts +2 -1
  100. package/src/routing/segment-keys.ts +5 -2
  101. package/src/server/action-handler.ts +106 -8
  102. package/src/server/als-registry.ts +10 -5
  103. package/src/server/chain-url-parts.ts +2 -1
  104. package/src/server/index.ts +4 -0
  105. package/src/server/metadata-collector.ts +114 -40
  106. package/src/server/param-coercion.ts +7 -7
  107. package/src/server/pipeline-phases.ts +3 -1
  108. package/src/server/pipeline.ts +3 -2
  109. package/src/server/prebuilt/cache-key.ts +2 -1
  110. package/src/server/prebuilt/payload-source.ts +2 -1
  111. package/src/server/prebuilt/synthetic-store.ts +2 -1
  112. package/src/server/prebuilt-builder.ts +6 -5
  113. package/src/server/prebuilt-runtime.ts +5 -3
  114. package/src/server/request-context.ts +6 -8
  115. package/src/server/route-element-builder.ts +18 -40
  116. package/src/server/sitemap-generator.ts +7 -9
  117. package/src/server/slot-resolver.ts +2 -1
  118. package/src/server/ssr-bridge-types.ts +6 -3
  119. package/src/server/types.ts +2 -1
  120. package/src/shared/als-slots.ts +3 -1
  121. package/src/shared/param-value.ts +44 -7
  122. package/src/shared/payload-root.ts +2 -1
  123. package/src/shared/slot-params.ts +11 -12
@@ -1 +1 @@
1
- {"version":3,"file":"segment-context-CjOlyB8Y.js","names":[],"sources":["../../src/shared/param-value.ts","../../src/client/segment-context.ts"],"sourcesContent":["/**\n * The canonical form of a segment param value.\n *\n * `getSegmentParams()` on the server and `useSegmentParams()` on the client\n * must return the same value — same prototype, same own properties. This\n * module is how that is guaranteed, and the mechanism matters:\n *\n * **Both sides are images of one normalizer.** A codec's output is deep-cloned\n * into a closed canonical domain at coercion time, and *that clone* is what the\n * server returns and what goes on the wire. Server and client agree by\n * construction, because neither holds the codec's original.\n *\n * That replaces predicting what React Flight would do to an arbitrary value.\n * Prediction is what the previous design attempted and it cannot be finished:\n * the question \"will Flight's decode output be observably identical to this\n * input?\" ranges over every way a JS object can carry state that is not in its\n * serialization — own keys, enumerability, symbols, holes, accessors,\n * subclassing, exotic objects — and a `Proxy` defeats it outright, since a\n * lying `getPrototypeOf` trap makes any static check unsound. Twelve review\n * findings on PR #992 were each one more case of that set, and the set does\n * not close.\n *\n * Normalizing closes it. The only remaining question is whether Flight\n * round-trips the normalizer's *output range* — a finite domain we defined,\n * covered by `tests/e2e/segment-params.test.ts` against the real serializer.\n *\n * ## The domain\n *\n * - `undefined`, `null`, `string`, `number`, `boolean`, `bigint`\n * - null-prototype objects, own enumerable string keys only\n * - dense arrays\n * - `Date`, `Map`, `Set` — rebuilt, never the codec's instance\n *\n * ...and it is a **tree**: no value appears twice, and nothing is cyclic.\n * That is not a simplification, it is the last prediction being removed.\n * Flight encodes a `Date` by value at each occurrence but tracks plain objects\n * for reference dedup, so preserving aliasing would carry it across for some\n * types and drop it for others — and knowing which is exactly the kind of\n * guess this design exists to stop making (codex, PR #992). A tree has no\n * sharing to preserve or lose, so what Flight does about it is unobservable.\n *\n * Anything else throws, naming the param and what it was. Note what is *not*\n * a rejection: a `Date` subclass normalizes to a `Date`, a decorated array to\n * a plain one, a sparse array to a dense one, a getter to the value it\n * returned. Those used to be twelve separate checks. They are not divergences\n * any more, because the normalization happens once and both sides see its\n * result — so they need no checks at all.\n *\n * Own properties that Flight would drop (non-enumerable, symbol-keyed) are\n * dropped here instead, symmetrically. Prototype pollution is handled by the\n * same pass: `__proto__` is never copied, and every object is\n * `Object.create(null)` (design/13-security.md #36b/#36c, TIM-873).\n *\n * ## The prototype flip\n *\n * Flight refuses to serialize a null-prototype object, so the canonical form\n * cannot go on the wire as-is. `toPlainRecord` and `toNullProtoRecord` flip\n * the prototype on the way out and back. They are exact inverses and both\n * total, because they only ever see canonical values — there is nothing to\n * validate and no shape to special-case.\n *\n * See design/41-global-params.md §\"Transport\".\n */\n\n/** Types the canonical form rebuilds rather than rejects. */\nconst REBUILT = ['Date', 'Map', 'Set'] as const;\n\n/** The domain, for error messages. Derived, never a second hand-written list. */\nconst DOMAIN = `a string, number, boolean, bigint, null, undefined, a plain object, an array, or ${REBUILT.join('/')}`;\n\nfunction reject(path: string, was: string, hint: string): never {\n throw new Error(\n `[timber] Segment param \"${path || '(root)'}\" was coerced to ${was}, which cannot ` +\n `cross to the client. A param value may be ${DOMAIN}.\\n` +\n ` ${hint}\\n` +\n ` See design/41-global-params.md §\"Transport\".`\n );\n}\n\nfunction describe(value: object): string {\n return (value as { constructor?: { name?: string } }).constructor?.name ?? 'an object';\n}\n\n/**\n * Deep-clone a codec's output into the canonical form, or throw.\n *\n * `seen` accumulates every object the walk has entered, and a second encounter\n * is rejected. That is one rule for two things — a shared reference and a cycle\n * are both \"this object again\" — and it is what keeps the result a tree.\n */\nexport function normalizeParamValue(value: unknown, path = ''): unknown {\n return normalize(value, path, new Set());\n}\n\nfunction normalize(value: unknown, path: string, seen: Set<object>): unknown {\n if (value === null) return null;\n\n const kind = typeof value;\n if (kind === 'string' || kind === 'number' || kind === 'boolean' || kind === 'bigint') {\n return value;\n }\n if (kind === 'undefined') return undefined;\n if (kind === 'function') {\n reject(path, 'a function', 'Return the data it would produce, not the function.');\n }\n if (kind === 'symbol') {\n reject(path, 'a symbol', 'Return a string instead — a symbol has no wire representation.');\n }\n\n const object = value as object;\n if (seen.has(object)) {\n throw new Error(\n `[timber] Segment param \"${path || '(root)'}\" is a value that already appears ` +\n `elsewhere in the same param — a shared reference or a cycle. A param value is a ` +\n `tree: React Flight carries a repeated \\`Date\\` by value and a repeated object by ` +\n `reference, so sharing would survive for some types and not others.\\n` +\n ` Return separate values, or move the shared part outside the params.\\n` +\n ` See design/41-global-params.md §\"Transport\".`\n );\n }\n seen.add(object);\n\n if (Array.isArray(object)) {\n // Read by index, so holes become `undefined` — on both sides, which is\n // the point. A subclass and any own properties are left behind for the\n // same reason: the clone is a plain, dense array either way.\n const out: unknown[] = [];\n for (let index = 0; index < object.length; index++) {\n out.push(normalize((object as unknown[])[index], `${path}[${index}]`, seen));\n }\n return out;\n }\n\n if (object instanceof Date) {\n // A fresh Date, so a subclass or an attached property cannot travel half\n // way and be dropped by the wire.\n return new Date(object.getTime());\n }\n\n if (object instanceof Map) {\n const out = new Map<unknown, unknown>();\n for (const [key, entry] of object) {\n out.set(\n normalize(key, `${path}<key>`, seen),\n normalize(entry, `${path}.get(${keyLabel(key)})`, seen)\n );\n }\n return out;\n }\n\n if (object instanceof Set) {\n const out = new Set<unknown>();\n let index = 0;\n for (const entry of object) out.add(normalize(entry, `${path}[${index++}]`, seen));\n return out;\n }\n\n // Everything else is judged by its prototype. A `Proxy` can lie here, and\n // that is fine: whatever it answers, the clone below reads through it once\n // and both sides see the same snapshot.\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== null && prototype !== Object.prototype) {\n reject(\n path,\n `a ${describe(object)} instance`,\n 'Return a plain object with the fields you need.'\n );\n }\n\n // Own *enumerable string* keys only — the rest is what Flight would drop,\n // so dropping it here keeps the two sides identical. `__proto__` is skipped\n // rather than copied: it has a language-level setter that would change the\n // prototype chain of the copy (TIM-655, TIM-855, TIM-873).\n const out: Record<string, unknown> = Object.create(null);\n for (const key of Object.keys(object)) {\n if (key === '__proto__') continue;\n out[key] = normalize(\n (object as Record<string, unknown>)[key],\n path ? `${path}.${key}` : key,\n seen\n );\n }\n return out;\n}\n\nfunction keyLabel(key: unknown): string {\n return typeof key === 'string' ? JSON.stringify(key) : String(key);\n}\n\n// ─── Prototype flip ──────────────────────────────────────────────\n\n/**\n * Canonical form → wire form. React Flight rejects a null prototype\n * (\"Classes or null prototypes are not supported\"), so objects cross as plain\n * ones and are restored on arrival.\n */\nexport function toPlainRecord<T>(value: T): T {\n return reproto(value, {}) as T;\n}\n\n/** Wire form → canonical form. The exact inverse of `toPlainRecord`. */\nexport function toNullProtoRecord<T>(value: T): T {\n return reproto(value, null) as T;\n}\n\n/**\n * Rebuild a canonical value with objects on `proto`.\n *\n * Total by construction: its input is always canonical, so the cases are the\n * domain and nothing else. No validation, no shape it might not have seen, and\n * no cycle to guard — a canonical value is a tree. That is what moving the\n * checking to `normalizeParamValue` bought.\n */\nfunction reproto(value: unknown, proto: object | null): unknown {\n if (value === null || typeof value !== 'object') return value;\n\n const object = value as object;\n\n // A Date carries no nested values, so it crosses as itself.\n if (object instanceof Date) return object;\n\n if (Array.isArray(object)) {\n return (object as unknown[]).map((item) => reproto(item, proto));\n }\n\n if (object instanceof Map) {\n const out = new Map<unknown, unknown>();\n for (const [key, entry] of object) out.set(reproto(key, proto), reproto(entry, proto));\n return out;\n }\n\n if (object instanceof Set) {\n const out = new Set<unknown>();\n for (const entry of object) out.add(reproto(entry, proto));\n return out;\n }\n\n const out: Record<string, unknown> = proto === null ? Object.create(null) : {};\n for (const key of Object.keys(object)) {\n if (key === '__proto__') continue;\n out[key] = reproto((object as Record<string, unknown>)[key], proto);\n }\n return out;\n}\n","/**\n * Segment Context — provides layout segment position for useSelectedLayoutSegment hooks.\n *\n * Each layout in the segment tree is wrapped with a SegmentProvider that stores\n * the URL segments from root to the current layout level. The hooks read this\n * context to determine which child segments are active below the calling layout.\n *\n * The context value is intentionally minimal: just the segment path array and\n * parallel route keys. No internal cache details are exposed.\n *\n * Design docs: design/19-client-navigation.md, design/14-ecosystem.md\n */\n\n'use client';\n\nimport { createContext, useContext, createElement, useMemo } from 'react';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface SegmentContextValue {\n /** URL segments from root to this layout (e.g. ['', 'dashboard', 'settings']) */\n segments: string[];\n /** Parallel route slot keys available at this layout level (e.g. ['sidebar', 'modal']) */\n parallelRouteKeys: string[];\n}\n\n// ─── Context ─────────────────────────────────────────────────────\n\nconst SegmentContext = createContext<SegmentContextValue | null>(null);\n\n/** Read the segment context. Returns null if no provider is above this component. */\nexport function useSegmentContext(): SegmentContextValue | null {\n return useContext(SegmentContext);\n}\n\n// ─── Provider ────────────────────────────────────────────────────\n\ninterface SegmentProviderProps {\n segments: string[];\n /**\n * Unique identifier for this segment, used by the client-side segment\n * merger for element caching. For route groups this includes the group\n * name (e.g., \"/(marketing)\") since groups share their parent's urlPath.\n * Falls back to the reconstructed path from `segments` if not provided.\n */\n segmentId?: string;\n parallelRouteKeys: string[];\n children: React.ReactNode;\n}\n\n/**\n * Wraps each layout to provide segment position context.\n * Injected by rsc-entry.ts during element tree construction.\n */\nexport function SegmentProvider({\n segments,\n segmentId: _segmentId,\n parallelRouteKeys,\n children,\n}: SegmentProviderProps) {\n const value = useMemo(\n () => ({ segments, parallelRouteKeys }),\n // segments and parallelRouteKeys are static per layout — they don't change\n // across navigations. The layout's position in the tree is fixed.\n // Intentionally using derived keys — segments/parallelRouteKeys are static per layout\n [segments.join('/'), parallelRouteKeys.join(',')]\n );\n return createElement(SegmentContext.Provider, { value }, children);\n}\n"],"mappings":";;;AAoEA,IAAM,SAAS,oFAAoF;CAHlF;CAAQ;CAAO;AAGmE,CAAA,CAAQ,KAAK,GAAG;AAEnH,SAAS,OAAO,MAAc,KAAa,MAAqB;CAC9D,MAAM,IAAI,MACR,2BAA2B,QAAQ,SAAS,mBAAmB,IAAI,2DACpB,OAAO,OAC/C,KAAK,iDAEd;AACF;AAEA,SAAS,SAAS,OAAuB;CACvC,OAAQ,MAA8C,aAAa,QAAQ;AAC7E;;;;;;;;AASA,SAAgB,oBAAoB,OAAgB,OAAO,IAAa;CACtE,OAAO,UAAU,OAAO,sBAAM,IAAI,IAAI,CAAC;AACzC;AAEA,SAAS,UAAU,OAAgB,MAAc,MAA4B;CAC3E,IAAI,UAAU,MAAM,OAAO;CAE3B,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,YAAY,SAAS,YAAY,SAAS,aAAa,SAAS,UAC3E,OAAO;CAET,IAAI,SAAS,aAAa,OAAO,KAAA;CACjC,IAAI,SAAS,YACX,OAAO,MAAM,cAAc,qDAAqD;CAElF,IAAI,SAAS,UACX,OAAO,MAAM,YAAY,gEAAgE;CAG3F,MAAM,SAAS;C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AI,OAAO,GAAG;AACnE;;;;;;;;;;;;;;;AC/JA,IAAM,iBAAiB,cAA0C,IAAI;;AAGrE,SAAgB,oBAAgD;CAC9D,OAAO,WAAW,cAAc;AAClC;;;;;AAqBA,SAAgB,gBAAgB,EAC9B,UACA,WAAW,YACX,mBACA,YACuB;CACvB,MAAM,QAAQ,eACL;EAAE;EAAU;CAAkB,IAIrC,CAAC,SAAS,KAAK,GAAG,GAAG,kBAAkB,KAAK,GAAG,CAAC,CAClD;CACA,OAAO,cAAc,eAAe,UAAU,EAAE,MAAM,GAAG,QAAQ;AACnE"}
1
+ {"version":3,"file":"segment-context-CjOlyB8Y.js","names":[],"sources":["../../src/shared/param-value.ts","../../src/client/segment-context.ts"],"sourcesContent":["/**\n * The canonical form of a segment param value.\n *\n * `getSegmentParams()` on the server and `useSegmentParams()` on the client\n * must return the same value — same prototype, same own properties. This\n * module is how that is guaranteed, and the mechanism matters:\n *\n * **Both sides are images of one normalizer.** A codec's output is deep-cloned\n * into a closed canonical domain at coercion time, and *that clone* is what the\n * server returns and what goes on the wire. Server and client agree by\n * construction, because neither holds the codec's original.\n *\n * That replaces predicting what React Flight would do to an arbitrary value.\n * Prediction is what the previous design attempted and it cannot be finished:\n * the question \"will Flight's decode output be observably identical to this\n * input?\" ranges over every way a JS object can carry state that is not in its\n * serialization — own keys, enumerability, symbols, holes, accessors,\n * subclassing, exotic objects — and a `Proxy` defeats it outright, since a\n * lying `getPrototypeOf` trap makes any static check unsound. Twelve review\n * findings on PR #992 were each one more case of that set, and the set does\n * not close.\n *\n * Normalizing closes it. The only remaining question is whether Flight\n * round-trips the normalizer's *output range* — a finite domain we defined,\n * covered by `tests/e2e/segment-params.test.ts` against the real serializer.\n *\n * ## The domain\n *\n * - `undefined`, `null`, `string`, `number`, `boolean`, `bigint`\n * - null-prototype objects, own enumerable string keys only\n * - dense arrays\n * - `Date`, `Map`, `Set` — rebuilt, never the codec's instance\n *\n * ...and it is a **tree**: no value appears twice, and nothing is cyclic.\n * That is not a simplification, it is the last prediction being removed.\n * Flight encodes a `Date` by value at each occurrence but tracks plain objects\n * for reference dedup, so preserving aliasing would carry it across for some\n * types and drop it for others — and knowing which is exactly the kind of\n * guess this design exists to stop making (codex, PR #992). A tree has no\n * sharing to preserve or lose, so what Flight does about it is unobservable.\n *\n * Anything else throws, naming the param and what it was. Note what is *not*\n * a rejection: a `Date` subclass normalizes to a `Date`, a decorated array to\n * a plain one, a sparse array to a dense one, a getter to the value it\n * returned. Those used to be twelve separate checks. They are not divergences\n * any more, because the normalization happens once and both sides see its\n * result — so they need no checks at all.\n *\n * Own properties that Flight would drop (non-enumerable, symbol-keyed) are\n * dropped here instead, symmetrically. Prototype pollution is handled by the\n * same pass: `__proto__` is never copied, and every object is\n * `Object.create(null)` (design/13-security.md #36b/#36c, TIM-873).\n *\n * ## The prototype flip\n *\n * Flight refuses to serialize a null-prototype object, so the canonical form\n * cannot go on the wire as-is. `toPlainRecord` and `toNullProtoRecord` flip\n * the prototype on the way out and back. They are exact inverses and both\n * total, because they only ever see canonical values — there is nothing to\n * validate and no shape to special-case.\n *\n * See design/41-global-params.md §\"Transport\".\n */\n\n// ─── Post-coercion param types ──────────────────────────────────────────\n\n/**\n * A single segment param value after codec coercion and normalization.\n *\n * Before coercion, every param is `string | string[]` (the raw URL part).\n * After `app/schema.ts` codecs run, a param can be any value in the\n * `normalizeParamValue` domain below. This type replaces the previous\n * `string | string[]` declaration, which was a lie whenever a codec\n * produced a non-string value (TIM-1347).\n *\n * The typed accessor `getSegmentParams(SEGMENT_PATH)` resolves through\n * the schema and returns the exact type the codec declares. This type\n * covers the untyped/no-argument form and internal plumbing.\n */\nexport type CoercedParamValue =\n | string\n | number\n | boolean\n | bigint\n | null\n | undefined\n | Date\n | Map<CoercedParamValue, CoercedParamValue>\n | Set<CoercedParamValue>\n | CoercedParamValue[]\n | { [key: string]: CoercedParamValue };\n\n/**\n * A record of coerced segment params, keyed by param name.\n *\n * This is the post-coercion type for `segmentParams` throughout the\n * framework. Before coercion (route matcher output, `rawSegmentParams`),\n * the type is `Record<string, string | string[]>`.\n */\nexport type CoercedParams = Record<string, CoercedParamValue>;\n\n/** Types the canonical form rebuilds rather than rejects. */\nconst REBUILT = ['Date', 'Map', 'Set'] as const;\n\n/** The domain, for error messages. Derived, never a second hand-written list. */\nconst DOMAIN = `a string, number, boolean, bigint, null, undefined, a plain object, an array, or ${REBUILT.join('/')}`;\n\nfunction reject(path: string, was: string, hint: string): never {\n throw new Error(\n `[timber] Segment param \"${path || '(root)'}\" was coerced to ${was}, which cannot ` +\n `cross to the client. A param value may be ${DOMAIN}.\\n` +\n ` ${hint}\\n` +\n ` See design/41-global-params.md §\"Transport\".`\n );\n}\n\nfunction describe(value: object): string {\n return (value as { constructor?: { name?: string } }).constructor?.name ?? 'an object';\n}\n\n/**\n * Deep-clone a codec's output into the canonical form, or throw.\n *\n * `seen` accumulates every object the walk has entered, and a second encounter\n * is rejected. That is one rule for two things — a shared reference and a cycle\n * are both \"this object again\" — and it is what keeps the result a tree.\n */\nexport function normalizeParamValue(value: unknown, path = ''): CoercedParamValue {\n return normalize(value, path, new Set());\n}\n\nfunction normalize(value: unknown, path: string, seen: Set<object>): CoercedParamValue {\n if (value === null) return null;\n\n const kind = typeof value;\n if (kind === 'string' || kind === 'number' || kind === 'boolean' || kind === 'bigint') {\n return value as string | number | boolean | bigint;\n }\n if (kind === 'undefined') return undefined;\n if (kind === 'function') {\n reject(path, 'a function', 'Return the data it would produce, not the function.');\n }\n if (kind === 'symbol') {\n reject(path, 'a symbol', 'Return a string instead — a symbol has no wire representation.');\n }\n\n const object = value as object;\n if (seen.has(object)) {\n throw new Error(\n `[timber] Segment param \"${path || '(root)'}\" is a value that already appears ` +\n `elsewhere in the same param — a shared reference or a cycle. A param value is a ` +\n `tree: React Flight carries a repeated \\`Date\\` by value and a repeated object by ` +\n `reference, so sharing would survive for some types and not others.\\n` +\n ` Return separate values, or move the shared part outside the params.\\n` +\n ` See design/41-global-params.md §\"Transport\".`\n );\n }\n seen.add(object);\n\n if (Array.isArray(object)) {\n // Read by index, so holes become `undefined` — on both sides, which is\n // the point. A subclass and any own properties are left behind for the\n // same reason: the clone is a plain, dense array either way.\n const out: CoercedParamValue[] = [];\n for (let index = 0; index < object.length; index++) {\n out.push(normalize((object as unknown[])[index], `${path}[${index}]`, seen));\n }\n return out;\n }\n\n if (object instanceof Date) {\n // A fresh Date, so a subclass or an attached property cannot travel half\n // way and be dropped by the wire.\n return new Date(object.getTime());\n }\n\n if (object instanceof Map) {\n const out = new Map<CoercedParamValue, CoercedParamValue>();\n for (const [key, entry] of object) {\n out.set(\n normalize(key, `${path}<key>`, seen),\n normalize(entry, `${path}.get(${keyLabel(key)})`, seen)\n );\n }\n return out;\n }\n\n if (object instanceof Set) {\n const out = new Set<CoercedParamValue>();\n let index = 0;\n for (const entry of object) out.add(normalize(entry, `${path}[${index++}]`, seen));\n return out;\n }\n\n // Everything else is judged by its prototype. A `Proxy` can lie here, and\n // that is fine: whatever it answers, the clone below reads through it once\n // and both sides see the same snapshot.\n const prototype = Object.getPrototypeOf(object);\n if (prototype !== null && prototype !== Object.prototype) {\n reject(\n path,\n `a ${describe(object)} instance`,\n 'Return a plain object with the fields you need.'\n );\n }\n\n // Own *enumerable string* keys only — the rest is what Flight would drop,\n // so dropping it here keeps the two sides identical. `__proto__` is skipped\n // rather than copied: it has a language-level setter that would change the\n // prototype chain of the copy (TIM-655, TIM-855, TIM-873).\n const out: Record<string, CoercedParamValue> = Object.create(null);\n for (const key of Object.keys(object)) {\n if (key === '__proto__') continue;\n out[key] = normalize(\n (object as Record<string, unknown>)[key],\n path ? `${path}.${key}` : key,\n seen\n );\n }\n return out;\n}\n\nfunction keyLabel(key: unknown): string {\n return typeof key === 'string' ? JSON.stringify(key) : String(key);\n}\n\n// ─── Prototype flip ──────────────────────────────────────────────\n\n/**\n * Canonical form → wire form. React Flight rejects a null prototype\n * (\"Classes or null prototypes are not supported\"), so objects cross as plain\n * ones and are restored on arrival.\n */\nexport function toPlainRecord<T>(value: T): T {\n return reproto(value, {}) as T;\n}\n\n/** Wire form → canonical form. The exact inverse of `toPlainRecord`. */\nexport function toNullProtoRecord<T>(value: T): T {\n return reproto(value, null) as T;\n}\n\n/**\n * Rebuild a canonical value with objects on `proto`.\n *\n * Total by construction: its input is always canonical, so the cases are the\n * domain and nothing else. No validation, no shape it might not have seen, and\n * no cycle to guard — a canonical value is a tree. That is what moving the\n * checking to `normalizeParamValue` bought.\n */\nfunction reproto(value: unknown, proto: object | null): unknown {\n if (value === null || typeof value !== 'object') return value;\n\n const object = value as object;\n\n // A Date carries no nested values, so it crosses as itself.\n if (object instanceof Date) return object;\n\n if (Array.isArray(object)) {\n return (object as unknown[]).map((item) => reproto(item, proto));\n }\n\n if (object instanceof Map) {\n const out = new Map<unknown, unknown>();\n for (const [key, entry] of object) out.set(reproto(key, proto), reproto(entry, proto));\n return out;\n }\n\n if (object instanceof Set) {\n const out = new Set<unknown>();\n for (const entry of object) out.add(reproto(entry, proto));\n return out;\n }\n\n const out: Record<string, unknown> = proto === null ? Object.create(null) : {};\n for (const key of Object.keys(object)) {\n if (key === '__proto__') continue;\n out[key] = reproto((object as Record<string, unknown>)[key], proto);\n }\n return out;\n}\n","/**\n * Segment Context — provides layout segment position for useSelectedLayoutSegment hooks.\n *\n * Each layout in the segment tree is wrapped with a SegmentProvider that stores\n * the URL segments from root to the current layout level. The hooks read this\n * context to determine which child segments are active below the calling layout.\n *\n * The context value is intentionally minimal: just the segment path array and\n * parallel route keys. No internal cache details are exposed.\n *\n * Design docs: design/19-client-navigation.md, design/14-ecosystem.md\n */\n\n'use client';\n\nimport { createContext, useContext, createElement, useMemo } from 'react';\n\n// ─── Types ───────────────────────────────────────────────────────\n\nexport interface SegmentContextValue {\n /** URL segments from root to this layout (e.g. ['', 'dashboard', 'settings']) */\n segments: string[];\n /** Parallel route slot keys available at this layout level (e.g. ['sidebar', 'modal']) */\n parallelRouteKeys: string[];\n}\n\n// ─── Context ─────────────────────────────────────────────────────\n\nconst SegmentContext = createContext<SegmentContextValue | null>(null);\n\n/** Read the segment context. Returns null if no provider is above this component. */\nexport function useSegmentContext(): SegmentContextValue | null {\n return useContext(SegmentContext);\n}\n\n// ─── Provider ────────────────────────────────────────────────────\n\ninterface SegmentProviderProps {\n segments: string[];\n /**\n * Unique identifier for this segment, used by the client-side segment\n * merger for element caching. For route groups this includes the group\n * name (e.g., \"/(marketing)\") since groups share their parent's urlPath.\n * Falls back to the reconstructed path from `segments` if not provided.\n */\n segmentId?: string;\n parallelRouteKeys: string[];\n children: React.ReactNode;\n}\n\n/**\n * Wraps each layout to provide segment position context.\n * Injected by rsc-entry.ts during element tree construction.\n */\nexport function SegmentProvider({\n segments,\n segmentId: _segmentId,\n parallelRouteKeys,\n children,\n}: SegmentProviderProps) {\n const value = useMemo(\n () => ({ segments, parallelRouteKeys }),\n // segments and parallelRouteKeys are static per layout — they don't change\n // across navigations. The layout's position in the tree is fixed.\n // Intentionally using derived keys — segments/parallelRouteKeys are static per layout\n [segments.join('/'), parallelRouteKeys.join(',')]\n );\n return createElement(SegmentContext.Provider, { value }, children);\n}\n"],"mappings":";;;AAyGA,IAAM,SAAS,oFAAoF;CAHlF;CAAQ;CAAO;AAGmE,CAAA,CAAQ,KAAK,GAAG;AAEnH,SAAS,OAAO,MAAc,KAAa,MAAqB;CAC9D,MAAM,IAAI,MACR,2BAA2B,QAAQ,SAAS,mBAAmB,IAAI,2DACpB,OAAO,OAC/C,KAAK,iDAEd;AACF;AAEA,SAAS,SAAS,OAAuB;CACvC,OAAQ,MAA8C,aAAa,QAAQ;AAC7E;;;;;;;;AASA,SAAgB,oBAAoB,OAAgB,OAAO,IAAuB;CAChF,OAAO,UAAU,OAAO,sBAAM,IAAI,IAAI,CAAC;AACzC;AAEA,SAAS,UAAU,OAAgB,MAAc,MAAsC;CACrF,IAAI,UAAU,MAAM,OAAO;CAE3B,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,YAAY,SAAS,Y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,QAAQ,aAAa;EACzB,IAAI,OAAO,UACR,OAAmC,MACpC,OAAO,GAAG,KAAK,GAAG,QAAQ,KAC1B,IACF;CACF;CACA,OAAO;AACT;AAEA,SAAS,SAAS,KAAsB;CACtC,OAAO,OAAO,QAAQ,WAAW,KAAK,UAAU,GAAG,IAAI,OAAO,GAAG;AACnE;;;;;;;;;;;;;;;ACpMA,IAAM,iBAAiB,cAA0C,IAAI;;AAGrE,SAAgB,oBAAgD;CAC9D,OAAO,WAAW,cAAc;AAClC;;;;;AAqBA,SAAgB,gBAAgB,EAC9B,UACA,WAAW,YACX,mBACA,YACuB;CACvB,MAAM,QAAQ,eACL;EAAE;EAAU;CAAkB,IAIrC,CAAC,SAAS,KAAK,GAAG,GAAG,kBAAkB,KAAK,GAAG,CAAC,CAClD;CACA,OAAO,cAAc,eAAe,UAAU,EAAE,MAAM,GAAG,QAAQ;AACnE"}
@@ -1 +1 @@
1
- {"version":3,"file":"segment-keys-BawYuNFO.js","names":[],"sources":["../../src/server/metadata-routes.ts","../../src/server/canonicalize.ts","../../src/routing/segment-keys.ts"],"sourcesContent":["/**\n * Metadata route classification for timber.js.\n *\n * Metadata routes are file-based endpoints that generate well-known URLs for\n * crawlers and browsers (sitemap.xml, robots.txt, OG images, etc.).\n *\n * These routes run through proxy.ts but NOT through middleware.ts or access.ts —\n * they are public endpoints by nature.\n *\n * See design/16-metadata.md §\"Metadata Routes\"\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HeadElement } from './metadata.js';\nimport type { Metadata } from './types.js';\nimport type { ManifestSegmentNode } from './route-matcher.js';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Classification of a metadata route file. */\nexport interface MetadataRouteInfo {\n /** The metadata route type. */\n type: MetadataRouteType;\n /** The content type to serve this route with. */\n contentType: string;\n /** Whether this route can appear in nested segments (not just app root). */\n nestable: boolean;\n}\n\nexport type MetadataRouteType =\n | 'sitemap'\n | 'robots'\n | 'manifest'\n | 'favicon'\n | 'icon'\n | 'opengraph-image'\n | 'apple-icon';\n\n// ─── Convention Table ────────────────────────────────────────────────────────\n\n/**\n * All recognized metadata route file conventions.\n *\n * Each entry maps a base file name (without extension) to its route info.\n * The extensions determine whether the file is static or dynamic.\n *\n * Static extensions: .xml, .txt, .json, .png, .jpg, .ico, .svg\n * Dynamic extensions: .ts, .tsx\n */\nexport const METADATA_ROUTE_CONVENTIONS: Record<\n string,\n {\n type: MetadataRouteType;\n contentType: string;\n nestable: boolean;\n staticExtensions: string[];\n dynamicExtensions: string[];\n /**\n * The URL path basename this file serves at (relative to segment).\n * For image routes, the full serve path includes an extension via\n * `resolveServePathForFile()`.\n */\n servePath: string;\n /**\n * When set, image routes append `.{serveExtension}` to the serve path.\n * Dynamic handlers (`.ts`/`.tsx`) use this as the default. Static files\n * use their own extension instead. Non-image routes leave this undefined.\n */\n serveExtension?: string;\n }\n> = {\n 'sitemap': {\n type: 'sitemap',\n contentType: 'application/xml',\n nestable: true,\n staticExtensions: ['xml'],\n dynamicExtensions: ['ts'],\n servePath: 'sitemap.xml',\n },\n 'robots': {\n type: 'robots',\n contentType: 'text/plain',\n nestable: false,\n staticExtensions: ['txt'],\n dynamicExtensions: ['ts'],\n servePath: 'robots.txt',\n },\n 'manifest': {\n type: 'manifest',\n contentType: 'application/manifest+json',\n nestable: false,\n staticExtensions: ['json'],\n dynamicExtensions: ['ts'],\n servePath: 'manifest.webmanifest',\n },\n 'favicon': {\n type: 'favicon',\n contentType: 'image/x-icon',\n nestable: false,\n staticExtensions: ['ico'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'favicon.ico',\n },\n 'icon': {\n type: 'icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg', 'svg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'icon',\n serveExtension: 'png',\n },\n 'opengraph-image': {\n type: 'opengraph-image',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'opengraph-image',\n serveExtension: 'png',\n },\n\n 'apple-icon': {\n type: 'apple-icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'apple-icon',\n serveExtension: 'png',\n },\n};\n\n// ─── MIME Type Resolution ─────────────────────────────────────────────────────\n\n/**\n * Map of file extensions to MIME types for static metadata route files.\n * Used to resolve the generic `image/*` content type for static image files.\n */\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n xml: 'application/xml',\n txt: 'text/plain',\n json: 'application/json',\n ico: 'image/x-icon',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n};\n\n/**\n * Resolve the concrete MIME type for a static metadata route file.\n *\n * For generic content types like `image/*`, this resolves to the actual\n * MIME type based on the file extension (e.g. `image/png` for `.png`).\n *\n * @param conventionContentType - The content type from the convention table (may be generic like `image/*`)\n * @param extension - The file extension without leading dot (e.g. \"png\", \"xml\")\n * @returns The resolved MIME type\n */\nexport function resolveStaticContentType(conventionContentType: string, extension: string): string {\n if (conventionContentType.includes('*')) {\n return EXTENSION_MIME_TYPES[extension] ?? 'application/octet-stream';\n }\n return conventionContentType;\n}\n\n/**\n * Check if a file extension represents a static (non-code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"xml\", \"png\", \"ts\")\n * @returns true if this is a static file, false if dynamic or unrecognized\n */\nexport function isStaticMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.staticExtensions.includes(extension);\n}\n\n/**\n * Check if a file extension represents a dynamic (code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"ts\", \"tsx\")\n * @returns true if this is a dynamic file, false if static or unrecognized\n */\nexport function isDynamicMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.dynamicExtensions.includes(extension);\n}\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\n/**\n * Classify a file name as a metadata route, or return null if it's not one.\n *\n * @param fileName - The full file name including extension (e.g. \"sitemap.xml\", \"icon.tsx\")\n * @returns Classification info, or null if not a metadata route\n */\nexport function classifyMetadataRoute(fileName: string): MetadataRouteInfo | null {\n const dotIndex = fileName.lastIndexOf('.');\n if (dotIndex === -1) return null;\n\n const baseName = fileName.slice(0, dotIndex);\n const ext = fileName.slice(dotIndex + 1);\n\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return null;\n\n const isStatic = convention.staticExtensions.includes(ext);\n const isDynamic = convention.dynamicExtensions.includes(ext);\n\n if (!isStatic && !isDynamic) return null;\n\n return {\n type: convention.type,\n contentType: convention.contentType,\n nestable: convention.nestable,\n };\n}\n\n/**\n * Resolve the serve path for a metadata route file.\n *\n * For image routes (icon, opengraph-image, apple-icon), the serve path includes\n * a file extension so CDNs cache correctly:\n * - Dynamic handlers (.ts/.tsx) use the convention's `serveExtension` (default: .png)\n * - Static files use their own extension (e.g., icon.svg → icon.svg)\n *\n * Non-image routes return the convention's `servePath` as-is (already includes\n * extension: sitemap.xml, robots.txt, etc.).\n */\nexport function resolveServePathForFile(baseName: string, filePath: string): string {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return baseName;\n\n if (!convention.serveExtension) return convention.servePath;\n\n const ext = filePath.slice(filePath.lastIndexOf('.') + 1);\n if (convention.staticExtensions.includes(ext)) {\n return `${convention.servePath}.${ext}`;\n }\n return `${convention.servePath}.${convention.serveExtension}`;\n}\n\n/**\n * Get the default serve path for a metadata route type (using default extension\n * for image routes). Used for auto-link generation when only the type is known.\n */\nexport function getMetadataRouteServePath(type: MetadataRouteType): string {\n for (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.type === type) {\n if (convention.serveExtension) {\n return `${convention.servePath}.${convention.serveExtension}`;\n }\n return convention.servePath;\n }\n }\n throw new Error(`[timber] Unknown metadata route type: ${type}`);\n}\n\n/**\n * All possible serve path segments for metadata routes (includes extension\n * variants for image routes).\n */\nconst METADATA_SERVE_PATHS = new Set<string>();\nfor (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.serveExtension) {\n for (const ext of [...convention.staticExtensions, convention.serveExtension]) {\n METADATA_SERVE_PATHS.add(`${convention.servePath}.${ext}`);\n }\n } else {\n METADATA_SERVE_PATHS.add(convention.servePath);\n }\n}\n\nexport function isMetadataRouteServePath(pathname: string): boolean {\n let lastSegment = pathname.slice(pathname.lastIndexOf('/') + 1);\n const qIdx = lastSegment.indexOf('?');\n let query = '';\n if (qIdx !== -1) {\n query = lastSegment.slice(qIdx + 1);\n lastSegment = lastSegment.slice(0, qIdx);\n }\n if (!METADATA_SERVE_PATHS.has(lastSegment)) return false;\n // Vite module requests (e.g., /src/icon.svg?import) use special query params.\n // These are source assets, not metadata routes.\n if (/(?:^|&)(?:import|url|raw|worker|inline)(?:&|$)/.test(query)) return false;\n return true;\n}\n\n/** A <link> auto-link tag. */\nexport interface AutoLinkLink {\n tag: 'link';\n rel: string;\n href: string;\n type?: string;\n}\n\n/** A <meta> auto-link tag. */\nexport interface AutoLinkMeta {\n tag: 'meta';\n property?: string;\n name?: string;\n content: string;\n}\n\nexport type AutoLinkTag = AutoLinkLink | AutoLinkMeta;\n\n/**\n * Get the auto-link tags to inject into <head> for metadata route files\n * discovered in a segment.\n *\n * Returns link tags for icon/apple-icon/manifest, and meta tags for\n * opengraph-image (emits both og:image and twitter:image). Returns null\n * for types that don't auto-link (favicon, sitemap, robots).\n *\n * @param type - The metadata route type\n * @param href - The resolved URL path to the metadata route\n * @returns Tag descriptor(s) for the <head>, or null if no auto-link\n */\nexport function getMetadataRouteAutoLink(type: MetadataRouteType, href: string): AutoLinkTag[] {\n switch (type) {\n case 'icon':\n return [{ tag: 'link', rel: 'icon', href }];\n case 'apple-icon':\n return [{ tag: 'link', rel: 'apple-touch-icon', href }];\n case 'manifest':\n return [{ tag: 'link', rel: 'manifest', href }];\n case 'opengraph-image':\n return [\n { tag: 'meta', property: 'og:image', content: href },\n { tag: 'meta', name: 'twitter:image', content: href },\n ];\n default:\n return [];\n }\n}\n\n// ─── Auto-Linking ──────────────────────────────────────────────────────────\n\n// In dev mode, use a per-startup nonce for metadata route cache busting\n// instead of per-file content hashes (avoids rehashing on every request).\nlet _devNonce: string | undefined;\nfunction getDevNonce(): string {\n _devNonce ??= randomUUID().slice(0, 8);\n return _devNonce;\n}\n\n/**\n * Collect auto-linked head elements from metadata route files in the segment chain.\n *\n * Walks each segment's metadataRoutes, resolves serve paths and URLs, and\n * emits HeadElement descriptors for <link> and <meta> tags that React Float\n * hoists into <head>.\n *\n * See design/16-metadata.md §\"Auto-Linking\"\n */\nexport function collectMetadataRouteHeadElements(\n segments: ManifestSegmentNode[],\n firstDeniedIndex: number,\n resolvedMetadata: Metadata,\n requestUrl: URL,\n metadataRouteHashes?: Record<string, string>\n): HeadElement[] {\n const elements: HeadElement[] = [];\n const hasUserOgImage = Boolean(resolvedMetadata.openGraph?.images);\n const hasUserTwitterImage = Boolean(resolvedMetadata.twitter?.images);\n const requestPathname = requestUrl.pathname;\n // In dev mode, use the request origin so OG URLs resolve to localhost.\n // In production, use metadataBase (the canonical domain).\n const ogBase =\n process.env.NODE_ENV !== 'production'\n ? new URL(requestUrl.origin)\n : resolvedMetadata.metadataBase;\n\n for (let si = 0; si < segments.length; si++) {\n const segment = segments[si];\n if (!segment.metadataRoutes) continue;\n if (si >= firstDeniedIndex) continue;\n for (const baseName of Object.keys(segment.metadataRoutes)) {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) continue;\n if (!convention.nestable && segment.urlPath !== '/') continue;\n if (convention.type === 'opengraph-image' && hasUserOgImage) continue;\n const resolvedPrefix = convention.nestable\n ? requestPathname === '/'\n ? ''\n : requestPathname\n : '';\n const metaFile = segment.metadataRoutes[baseName];\n const fileServePath = metaFile?.filePath\n ? resolveServePathForFile(baseName, metaFile.filePath)\n : convention.serveExtension\n ? `${convention.servePath}.${convention.serveExtension}`\n : convention.servePath;\n let href = `${resolvedPrefix}/${fileServePath}`;\n if (convention.type === 'opengraph-image') {\n const fileHash = metaFile?.filePath ? metadataRouteHashes?.[metaFile.filePath] : undefined;\n const cacheBust = fileHash ?? getDevNonce();\n href = `${href}?${cacheBust}`;\n }\n if (ogBase && convention.type === 'opengraph-image') {\n href = new URL(href, ogBase).toString();\n }\n for (const autoLink of getMetadataRouteAutoLink(convention.type, href)) {\n if (\n hasUserTwitterImage &&\n autoLink.tag === 'meta' &&\n 'name' in autoLink &&\n autoLink.name === 'twitter:image'\n )\n continue;\n if (autoLink.tag === 'link') {\n const attrs: Record<string, string> = { rel: autoLink.rel, href: autoLink.href };\n if (autoLink.type) attrs.type = autoLink.type;\n elements.push({ tag: 'link', attrs });\n } else {\n const attrs: Record<string, string> = { content: autoLink.content };\n if (autoLink.property) attrs.property = autoLink.property;\n if (autoLink.name) attrs.name = autoLink.name;\n elements.push({ tag: 'meta', attrs });\n }\n }\n }\n }\n return elements;\n}\n","/**\n * URL canonicalization — runs once at the request boundary.\n *\n * Every layer (proxy.ts, middleware.ts, access.ts, components) sees the same\n * canonical path. No re-decoding occurs at any later stage.\n *\n * See design/07-routing.md §\"URL Canonicalization & Security\"\n */\n\n/** Result of canonicalization — either a clean path or a rejection. */\nexport type CanonicalizeResult = { ok: true; pathname: string } | { ok: false; status: 400 };\n\n/**\n * Encoded separators that produce a 400 rejection.\n * %2f (/) and %5c (\\) cause path-confusion attacks.\n *\n * Shared between the runtime canonicalizer and the build-time route scanner\n * to ensure both enforce identical security rules. See design/13-security.md.\n */\nexport const ENCODED_SEPARATOR_RE = /%2f|%5c/i;\n\n/** Null byte — rejected. Shared with the route scanner. */\nexport const NULL_BYTE_RE = /%00/i;\n\n/**\n * Canonicalize a URL pathname.\n *\n * 1. Reject encoded separators (%2f, %5c) and null bytes (%00)\n * 2. Single percent-decode\n * 3. Collapse // → /\n * 4. Resolve .. segments (reject if escaping root)\n * 5. Strip trailing slash (except root \"/\")\n *\n * @param rawPathname - The raw pathname from the request URL (percent-encoded)\n * @param stripTrailingSlash - Whether to strip trailing slashes. Default: true.\n */\nexport function canonicalize(rawPathname: string, stripTrailingSlash = true): CanonicalizeResult {\n // Step 1: Reject dangerous encoded sequences BEFORE decoding.\n // This must happen on the raw input so %252f doesn't bypass after a single decode.\n if (ENCODED_SEPARATOR_RE.test(rawPathname)) {\n return { ok: false, status: 400 };\n }\n if (NULL_BYTE_RE.test(rawPathname)) {\n return { ok: false, status: 400 };\n }\n\n // Step 2: Single percent-decode.\n // Double-encoded input (%2561 → %61) stays as %61 — not decoded again.\n let decoded: string;\n try {\n decoded = decodeURIComponent(rawPathname);\n } catch {\n // Malformed percent-encoding → 400\n return { ok: false, status: 400 };\n }\n\n // Reject null bytes that appeared after decoding (from valid %00-like sequences\n // that weren't caught above — belt and suspenders).\n if (decoded.includes('\\0')) {\n return { ok: false, status: 400 };\n }\n\n // Backslash is NOT a path separator — keep as literal character.\n // But reject if it would create // after normalization (e.g., /\\evil.com).\n // We do NOT convert \\ to / — it stays as a literal.\n\n // Step 3: Collapse consecutive slashes.\n let pathname = decoded.replace(/\\/\\/+/g, '/');\n\n // Step 4: Resolve .. and . segments.\n const segments = pathname.split('/');\n const resolved: string[] = [];\n for (const seg of segments) {\n if (seg === '..') {\n if (resolved.length <= 1) {\n // Trying to escape root — 400\n return { ok: false, status: 400 };\n }\n resolved.pop();\n } else if (seg !== '.') {\n resolved.push(seg);\n }\n }\n\n pathname = resolved.join('/') || '/';\n\n // Step 5: Strip trailing slash (except root \"/\").\n if (stripTrailingSlash && pathname.length > 1 && pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n\n return { ok: true, pathname };\n}\n","/**\n * Segment key computation — the stable identity of a segment in the route tree.\n *\n * A segment key is the string that names a segment across the RSC/SSR/client\n * boundary: it appears in the X-Timber-State-Tree header, the X-Timber-Segments\n * header, SegmentOutlet props, the client segment cache, and (since TIM-1279)\n * interception scoping.\n *\n * This module lives in `routing/` rather than `server/` because the keys are a\n * property of the route tree itself — both the build-time scanner tree and the\n * runtime manifest tree produce identical keys for the same directory, which is\n * what lets a build-time value (an interception scope) be compared against a\n * request-time matched chain.\n *\n * See design/19-client-navigation.md §\"X-Timber-State-Tree Header\"\n */\n\n/**\n * Segment node shape expected by computeSegmentKeys.\n *\n * Structurally satisfied by both `SegmentNode` (build time) and\n * `ManifestSegmentNode` (request time) — keys depend only on the\n * URL path and the segment classification, never on file payloads.\n */\nexport interface SegmentKeyInput {\n urlPath: string;\n segmentName?: string;\n segmentType?: string;\n}\n\n/**\n * Compute state-tree keys for a segment chain.\n *\n * Non-group segments use their urlPath as-is. Route groups accumulate\n * ancestor group names to produce globally unique keys:\n * app/(a)/(shared)/dashboard → keys: ['/', '/(a)', '/(a)/(shared)', '/dashboard']\n *\n * **An intercepting segment switches the chain to name accumulation for good.**\n * A children-path interception (TIM-1280) puts an intercepting node and its\n * descendants into the *main* rendered chain, and their `urlPath`s are not\n * URLs: interception adds no URL depth, so `app/(browse)/(...)[artistSlug]/[year]`\n * carries `/` and `/[year]`. Keyed by urlPath the intercepting node would\n * collide with its own owner, and `[year]` with any top-level `[year]` route —\n * so a client that had one mounted would reuse the wrong cached layout. The\n * switch is sticky rather than per-node because the *descendants* are where\n * the false URLs are; the intercepting node alone is not the problem.\n *\n * This is the single source of truth for segment keys — used by the\n * element builder (skip decisions, SegmentOutlet props), segment info\n * (X-Timber-Segments header), the client cache/state tree, and\n * interception scoping (`routing/interception.ts`).\n */\nexport function computeSegmentKeys(segments: SegmentKeyInput[]): string[] {\n const keys: string[] = [];\n let prevKey = '';\n let insideIntercepting = false;\n\n for (const segment of segments) {\n if (segment.segmentType === 'intercepting') insideIntercepting = true;\n if (segment.segmentType === 'group' || insideIntercepting) {\n const base = prevKey === '/' ? '' : prevKey;\n const key = `${base}/${segment.segmentName}`;\n keys.push(key);\n prevKey = key;\n } else {\n keys.push(segment.urlPath);\n prevKey = segment.urlPath;\n }\n }\n\n return keys;\n}\n\n/**\n * Compute tree paths for a segment chain — the directory path of each segment\n * with slots elided, e.g. `app/(browse)/feed` → `/(browse)/feed`.\n *\n * This is `computeSegmentKeys` with the group branch applied to *every*\n * segment rather than only to groups. That one difference is the whole point:\n * `computeSegmentKeys` resets to `urlPath` at each URL-visible segment, so\n * `(browse)/feed` and `(landing)/feed` both key as `/feed`. Two directories\n * that render different layouts must not share an identity.\n *\n * Used for interception scoping (`routing/interception.ts`), where the\n * question is \"does this route pass through *that* directory?\" — not \"does it\n * render this URL?\". Not interchangeable with `computeSegmentKeys`: the state\n * tree is keyed by URL on purpose, because the client caches by URL.\n */\nexport function computeSegmentTreePaths(segments: SegmentKeyInput[]): string[] {\n const paths: string[] = [];\n let prev = '';\n\n for (const segment of segments) {\n const name = segment.segmentName ?? '';\n if (!name) {\n // The app root — no directory name of its own.\n paths.push('/');\n prev = '/';\n continue;\n }\n const base = prev === '/' ? '' : prev;\n const path = `${base}/${name}`;\n paths.push(path);\n prev = path;\n }\n\n return paths;\n}\n\n/**\n * The directory names a tree path is built from — `/` is none, `/feed/(a)` is\n * `['feed', '(a)']`.\n *\n * The inverse of the walk above, and it lives beside it so the format is\n * stated once: `findChainByTreePath` (`server/children-interception.ts`) walks\n * these names back down the tree to the directory the path addresses, and\n * `treePathDepth` counts them. Both are readings of the same string, and a\n * reader that disagreed with the producer about what separates two names\n * resolves an interception to the wrong node or to none.\n */\nexport function treePathNames(treePath: string): string[] {\n return treePath === '/' ? [] : treePath.slice(1).split('/');\n}\n\n/**\n * How many directories a tree path names — `/` is 0, `/feed` is 1,\n * `/feed/(a)` is 2.\n *\n * Two tree paths on a single rendered chain are strictly nested, so on that\n * chain depth orders them totally — which is what makes it usable as \"the\n * deeper of these two directories\" wherever a route passes through both\n * (`routing/interception.ts`).\n */\nexport function treePathDepth(treePath: string): number {\n return treePathNames(treePath).length;\n}\n\n/**\n * Compute a unique key for a parallel route slot.\n * Format: `{parentSegmentId}/@{slotName}`, e.g. `/@sidebar` or `/dashboard/@modal`.\n */\nexport function computeSlotKey(parentSegmentId: string, slotName: string): string {\n const name = slotName.startsWith('@') ? slotName : `@${slotName}`;\n const prefix = parentSegmentId === '/' ? '' : parentSegmentId;\n return `${prefix}/${name}`;\n}\n\n/**\n * Compute a content key for a parallel route slot.\n *\n * The content key encodes everything that determines the slot's rendered\n * output for a given navigation: the slot key (which includes the owning\n * segment's identity and the slot name), the URL parts consumed by the\n * owning segment (which determine parent params the slot page might\n * read), the matched page file (or a sentinel for `default.tsx`), and\n * the slot's own extracted params.\n *\n * The slot key prevents cross-group collisions: two route groups at the\n * same URL level each owning a `@sidebar` slot produce different keys\n * even when both fall back to `default.tsx`.\n *\n * The key is opaque to the client — it stores whatever the server sent\n * and advertises it back. The server computes the destination key and\n * checks membership. This eliminates the need for the server to\n * reconstruct the client's state from a departing URL.\n *\n * See design/07-routing.md §\"Segment Tree Diffing on Navigation\"\n */\nexport function computeSlotContentKey(\n slotKey: string,\n ownerParts: string[],\n entryFile: string | null,\n slotParams: Record<string, string | string[]>\n): string {\n const owner = ownerParts.join('/');\n const entry = entryFile ?? '\\x01';\n const paramKeys = Object.keys(slotParams).sort();\n const paramParts = paramKeys.map((k) => {\n const v = slotParams[k];\n return Array.isArray(v) ? `${k}=${v.join('\\x02')}` : `${k}=${v}`;\n });\n return [slotKey, owner, entry, ...paramParts].join('\\0');\n}\n"],"mappings":";;;;;;;;;;;AAiDA,IAAa,6BAqBT;CACF,WAAW;EACT,MAAM;EACN,aAAa;EACb,UAAU;EACV,kBAAkB,CAAC,KAAK;EACxB,mBAAmB,CAAC,IAAI;EACxB,WAAW;CACb;CACA,UAAU;EACR,MAAM;EACN,aAAa;EACb,UAAU;EACV,kBAAkB,CAAC,KAAK;E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pC,IAAI,CAAC,MAAM;GAET,MAAM,KAAK,GAAG;GACd,OAAO;GACP;EACF;EAEA,MAAM,OAAO,GADA,SAAS,MAAM,KAAK,KACZ,GAAG;EACxB,MAAM,KAAK,IAAI;EACf,OAAO;CACT;CAEA,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,cAAc,UAA4B;CACxD,OAAO,aAAa,MAAM,CAAC,IAAI,SAAS,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG;AAC5D;;;;;;;;;;AAWA,SAAgB,cAAc,UAA0B;CACtD,OAAO,cAAc,QAAQ,CAAC,CAAC;AACjC"}
1
+ {"version":3,"file":"segment-keys-BawYuNFO.js","names":[],"sources":["../../src/server/metadata-routes.ts","../../src/server/canonicalize.ts","../../src/routing/segment-keys.ts"],"sourcesContent":["/**\n * Metadata route classification for timber.js.\n *\n * Metadata routes are file-based endpoints that generate well-known URLs for\n * crawlers and browsers (sitemap.xml, robots.txt, OG images, etc.).\n *\n * These routes run through proxy.ts but NOT through middleware.ts or access.ts —\n * they are public endpoints by nature.\n *\n * See design/16-metadata.md §\"Metadata Routes\"\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { HeadElement } from './metadata.js';\nimport type { Metadata } from './types.js';\nimport type { ManifestSegmentNode } from './route-matcher.js';\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Classification of a metadata route file. */\nexport interface MetadataRouteInfo {\n /** The metadata route type. */\n type: MetadataRouteType;\n /** The content type to serve this route with. */\n contentType: string;\n /** Whether this route can appear in nested segments (not just app root). */\n nestable: boolean;\n}\n\nexport type MetadataRouteType =\n | 'sitemap'\n | 'robots'\n | 'manifest'\n | 'favicon'\n | 'icon'\n | 'opengraph-image'\n | 'apple-icon';\n\n// ─── Convention Table ────────────────────────────────────────────────────────\n\n/**\n * All recognized metadata route file conventions.\n *\n * Each entry maps a base file name (without extension) to its route info.\n * The extensions determine whether the file is static or dynamic.\n *\n * Static extensions: .xml, .txt, .json, .png, .jpg, .ico, .svg\n * Dynamic extensions: .ts, .tsx\n */\nexport const METADATA_ROUTE_CONVENTIONS: Record<\n string,\n {\n type: MetadataRouteType;\n contentType: string;\n nestable: boolean;\n staticExtensions: string[];\n dynamicExtensions: string[];\n /**\n * The URL path basename this file serves at (relative to segment).\n * For image routes, the full serve path includes an extension via\n * `resolveServePathForFile()`.\n */\n servePath: string;\n /**\n * When set, image routes append `.{serveExtension}` to the serve path.\n * Dynamic handlers (`.ts`/`.tsx`) use this as the default. Static files\n * use their own extension instead. Non-image routes leave this undefined.\n */\n serveExtension?: string;\n }\n> = {\n 'sitemap': {\n type: 'sitemap',\n contentType: 'application/xml',\n nestable: true,\n staticExtensions: ['xml'],\n dynamicExtensions: ['ts'],\n servePath: 'sitemap.xml',\n },\n 'robots': {\n type: 'robots',\n contentType: 'text/plain',\n nestable: false,\n staticExtensions: ['txt'],\n dynamicExtensions: ['ts'],\n servePath: 'robots.txt',\n },\n 'manifest': {\n type: 'manifest',\n contentType: 'application/manifest+json',\n nestable: false,\n staticExtensions: ['json'],\n dynamicExtensions: ['ts'],\n servePath: 'manifest.webmanifest',\n },\n 'favicon': {\n type: 'favicon',\n contentType: 'image/x-icon',\n nestable: false,\n staticExtensions: ['ico'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'favicon.ico',\n },\n 'icon': {\n type: 'icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg', 'svg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'icon',\n serveExtension: 'png',\n },\n 'opengraph-image': {\n type: 'opengraph-image',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png', 'jpg'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'opengraph-image',\n serveExtension: 'png',\n },\n\n 'apple-icon': {\n type: 'apple-icon',\n contentType: 'image/*',\n nestable: true,\n staticExtensions: ['png'],\n dynamicExtensions: ['ts', 'tsx'],\n servePath: 'apple-icon',\n serveExtension: 'png',\n },\n};\n\n// ─── MIME Type Resolution ─────────────────────────────────────────────────────\n\n/**\n * Map of file extensions to MIME types for static metadata route files.\n * Used to resolve the generic `image/*` content type for static image files.\n */\nconst EXTENSION_MIME_TYPES: Record<string, string> = {\n xml: 'application/xml',\n txt: 'text/plain',\n json: 'application/json',\n ico: 'image/x-icon',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n};\n\n/**\n * Resolve the concrete MIME type for a static metadata route file.\n *\n * For generic content types like `image/*`, this resolves to the actual\n * MIME type based on the file extension (e.g. `image/png` for `.png`).\n *\n * @param conventionContentType - The content type from the convention table (may be generic like `image/*`)\n * @param extension - The file extension without leading dot (e.g. \"png\", \"xml\")\n * @returns The resolved MIME type\n */\nexport function resolveStaticContentType(conventionContentType: string, extension: string): string {\n if (conventionContentType.includes('*')) {\n return EXTENSION_MIME_TYPES[extension] ?? 'application/octet-stream';\n }\n return conventionContentType;\n}\n\n/**\n * Check if a file extension represents a static (non-code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"xml\", \"png\", \"ts\")\n * @returns true if this is a static file, false if dynamic or unrecognized\n */\nexport function isStaticMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.staticExtensions.includes(extension);\n}\n\n/**\n * Check if a file extension represents a dynamic (code) metadata route file.\n *\n * @param baseName - The base file name without extension (e.g. \"sitemap\", \"icon\")\n * @param extension - The file extension without leading dot (e.g. \"ts\", \"tsx\")\n * @returns true if this is a dynamic file, false if static or unrecognized\n */\nexport function isDynamicMetadataExtension(baseName: string, extension: string): boolean {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return false;\n return convention.dynamicExtensions.includes(extension);\n}\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\n/**\n * Classify a file name as a metadata route, or return null if it's not one.\n *\n * @param fileName - The full file name including extension (e.g. \"sitemap.xml\", \"icon.tsx\")\n * @returns Classification info, or null if not a metadata route\n */\nexport function classifyMetadataRoute(fileName: string): MetadataRouteInfo | null {\n const dotIndex = fileName.lastIndexOf('.');\n if (dotIndex === -1) return null;\n\n const baseName = fileName.slice(0, dotIndex);\n const ext = fileName.slice(dotIndex + 1);\n\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return null;\n\n const isStatic = convention.staticExtensions.includes(ext);\n const isDynamic = convention.dynamicExtensions.includes(ext);\n\n if (!isStatic && !isDynamic) return null;\n\n return {\n type: convention.type,\n contentType: convention.contentType,\n nestable: convention.nestable,\n };\n}\n\n/**\n * Resolve the serve path for a metadata route file.\n *\n * For image routes (icon, opengraph-image, apple-icon), the serve path includes\n * a file extension so CDNs cache correctly:\n * - Dynamic handlers (.ts/.tsx) use the convention's `serveExtension` (default: .png)\n * - Static files use their own extension (e.g., icon.svg → icon.svg)\n *\n * Non-image routes return the convention's `servePath` as-is (already includes\n * extension: sitemap.xml, robots.txt, etc.).\n */\nexport function resolveServePathForFile(baseName: string, filePath: string): string {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) return baseName;\n\n if (!convention.serveExtension) return convention.servePath;\n\n const ext = filePath.slice(filePath.lastIndexOf('.') + 1);\n if (convention.staticExtensions.includes(ext)) {\n return `${convention.servePath}.${ext}`;\n }\n return `${convention.servePath}.${convention.serveExtension}`;\n}\n\n/**\n * Get the default serve path for a metadata route type (using default extension\n * for image routes). Used for auto-link generation when only the type is known.\n */\nexport function getMetadataRouteServePath(type: MetadataRouteType): string {\n for (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.type === type) {\n if (convention.serveExtension) {\n return `${convention.servePath}.${convention.serveExtension}`;\n }\n return convention.servePath;\n }\n }\n throw new Error(`[timber] Unknown metadata route type: ${type}`);\n}\n\n/**\n * All possible serve path segments for metadata routes (includes extension\n * variants for image routes).\n */\nconst METADATA_SERVE_PATHS = new Set<string>();\nfor (const convention of Object.values(METADATA_ROUTE_CONVENTIONS)) {\n if (convention.serveExtension) {\n for (const ext of [...convention.staticExtensions, convention.serveExtension]) {\n METADATA_SERVE_PATHS.add(`${convention.servePath}.${ext}`);\n }\n } else {\n METADATA_SERVE_PATHS.add(convention.servePath);\n }\n}\n\nexport function isMetadataRouteServePath(pathname: string): boolean {\n let lastSegment = pathname.slice(pathname.lastIndexOf('/') + 1);\n const qIdx = lastSegment.indexOf('?');\n let query = '';\n if (qIdx !== -1) {\n query = lastSegment.slice(qIdx + 1);\n lastSegment = lastSegment.slice(0, qIdx);\n }\n if (!METADATA_SERVE_PATHS.has(lastSegment)) return false;\n // Vite module requests (e.g., /src/icon.svg?import) use special query params.\n // These are source assets, not metadata routes.\n if (/(?:^|&)(?:import|url|raw|worker|inline)(?:&|$)/.test(query)) return false;\n return true;\n}\n\n/** A <link> auto-link tag. */\nexport interface AutoLinkLink {\n tag: 'link';\n rel: string;\n href: string;\n type?: string;\n}\n\n/** A <meta> auto-link tag. */\nexport interface AutoLinkMeta {\n tag: 'meta';\n property?: string;\n name?: string;\n content: string;\n}\n\nexport type AutoLinkTag = AutoLinkLink | AutoLinkMeta;\n\n/**\n * Get the auto-link tags to inject into <head> for metadata route files\n * discovered in a segment.\n *\n * Returns link tags for icon/apple-icon/manifest, and meta tags for\n * opengraph-image (emits both og:image and twitter:image). Returns null\n * for types that don't auto-link (favicon, sitemap, robots).\n *\n * @param type - The metadata route type\n * @param href - The resolved URL path to the metadata route\n * @returns Tag descriptor(s) for the <head>, or null if no auto-link\n */\nexport function getMetadataRouteAutoLink(type: MetadataRouteType, href: string): AutoLinkTag[] {\n switch (type) {\n case 'icon':\n return [{ tag: 'link', rel: 'icon', href }];\n case 'apple-icon':\n return [{ tag: 'link', rel: 'apple-touch-icon', href }];\n case 'manifest':\n return [{ tag: 'link', rel: 'manifest', href }];\n case 'opengraph-image':\n return [\n { tag: 'meta', property: 'og:image', content: href },\n { tag: 'meta', name: 'twitter:image', content: href },\n ];\n default:\n return [];\n }\n}\n\n// ─── Auto-Linking ──────────────────────────────────────────────────────────\n\n// In dev mode, use a per-startup nonce for metadata route cache busting\n// instead of per-file content hashes (avoids rehashing on every request).\nlet _devNonce: string | undefined;\nfunction getDevNonce(): string {\n _devNonce ??= randomUUID().slice(0, 8);\n return _devNonce;\n}\n\n/**\n * Collect auto-linked head elements from metadata route files in the segment chain.\n *\n * Walks each segment's metadataRoutes, resolves serve paths and URLs, and\n * emits HeadElement descriptors for <link> and <meta> tags that React Float\n * hoists into <head>.\n *\n * See design/16-metadata.md §\"Auto-Linking\"\n */\nexport function collectMetadataRouteHeadElements(\n segments: ManifestSegmentNode[],\n firstDeniedIndex: number,\n resolvedMetadata: Metadata,\n requestUrl: URL,\n metadataRouteHashes?: Record<string, string>\n): HeadElement[] {\n const elements: HeadElement[] = [];\n const hasUserOgImage = Boolean(resolvedMetadata.openGraph?.images);\n const hasUserTwitterImage = Boolean(resolvedMetadata.twitter?.images);\n const requestPathname = requestUrl.pathname;\n // In dev mode, use the request origin so OG URLs resolve to localhost.\n // In production, use metadataBase (the canonical domain).\n const ogBase =\n process.env.NODE_ENV !== 'production'\n ? new URL(requestUrl.origin)\n : resolvedMetadata.metadataBase;\n\n for (let si = 0; si < segments.length; si++) {\n const segment = segments[si];\n if (!segment.metadataRoutes) continue;\n if (si >= firstDeniedIndex) continue;\n for (const baseName of Object.keys(segment.metadataRoutes)) {\n const convention = METADATA_ROUTE_CONVENTIONS[baseName];\n if (!convention) continue;\n if (!convention.nestable && segment.urlPath !== '/') continue;\n if (convention.type === 'opengraph-image' && hasUserOgImage) continue;\n const resolvedPrefix = convention.nestable\n ? requestPathname === '/'\n ? ''\n : requestPathname\n : '';\n const metaFile = segment.metadataRoutes[baseName];\n const fileServePath = metaFile?.filePath\n ? resolveServePathForFile(baseName, metaFile.filePath)\n : convention.serveExtension\n ? `${convention.servePath}.${convention.serveExtension}`\n : convention.servePath;\n let href = `${resolvedPrefix}/${fileServePath}`;\n if (convention.type === 'opengraph-image') {\n const fileHash = metaFile?.filePath ? metadataRouteHashes?.[metaFile.filePath] : undefined;\n const cacheBust = fileHash ?? getDevNonce();\n href = `${href}?${cacheBust}`;\n }\n if (ogBase && convention.type === 'opengraph-image') {\n href = new URL(href, ogBase).toString();\n }\n for (const autoLink of getMetadataRouteAutoLink(convention.type, href)) {\n if (\n hasUserTwitterImage &&\n autoLink.tag === 'meta' &&\n 'name' in autoLink &&\n autoLink.name === 'twitter:image'\n )\n continue;\n if (autoLink.tag === 'link') {\n const attrs: Record<string, string> = { rel: autoLink.rel, href: autoLink.href };\n if (autoLink.type) attrs.type = autoLink.type;\n elements.push({ tag: 'link', attrs });\n } else {\n const attrs: Record<string, string> = { content: autoLink.content };\n if (autoLink.property) attrs.property = autoLink.property;\n if (autoLink.name) attrs.name = autoLink.name;\n elements.push({ tag: 'meta', attrs });\n }\n }\n }\n }\n return elements;\n}\n","/**\n * URL canonicalization — runs once at the request boundary.\n *\n * Every layer (proxy.ts, middleware.ts, access.ts, components) sees the same\n * canonical path. No re-decoding occurs at any later stage.\n *\n * See design/07-routing.md §\"URL Canonicalization & Security\"\n */\n\n/** Result of canonicalization — either a clean path or a rejection. */\nexport type CanonicalizeResult = { ok: true; pathname: string } | { ok: false; status: 400 };\n\n/**\n * Encoded separators that produce a 400 rejection.\n * %2f (/) and %5c (\\) cause path-confusion attacks.\n *\n * Shared between the runtime canonicalizer and the build-time route scanner\n * to ensure both enforce identical security rules. See design/13-security.md.\n */\nexport const ENCODED_SEPARATOR_RE = /%2f|%5c/i;\n\n/** Null byte — rejected. Shared with the route scanner. */\nexport const NULL_BYTE_RE = /%00/i;\n\n/**\n * Canonicalize a URL pathname.\n *\n * 1. Reject encoded separators (%2f, %5c) and null bytes (%00)\n * 2. Single percent-decode\n * 3. Collapse // → /\n * 4. Resolve .. segments (reject if escaping root)\n * 5. Strip trailing slash (except root \"/\")\n *\n * @param rawPathname - The raw pathname from the request URL (percent-encoded)\n * @param stripTrailingSlash - Whether to strip trailing slashes. Default: true.\n */\nexport function canonicalize(rawPathname: string, stripTrailingSlash = true): CanonicalizeResult {\n // Step 1: Reject dangerous encoded sequences BEFORE decoding.\n // This must happen on the raw input so %252f doesn't bypass after a single decode.\n if (ENCODED_SEPARATOR_RE.test(rawPathname)) {\n return { ok: false, status: 400 };\n }\n if (NULL_BYTE_RE.test(rawPathname)) {\n return { ok: false, status: 400 };\n }\n\n // Step 2: Single percent-decode.\n // Double-encoded input (%2561 → %61) stays as %61 — not decoded again.\n let decoded: string;\n try {\n decoded = decodeURIComponent(rawPathname);\n } catch {\n // Malformed percent-encoding → 400\n return { ok: false, status: 400 };\n }\n\n // Reject null bytes that appeared after decoding (from valid %00-like sequences\n // that weren't caught above — belt and suspenders).\n if (decoded.includes('\\0')) {\n return { ok: false, status: 400 };\n }\n\n // Backslash is NOT a path separator — keep as literal character.\n // But reject if it would create // after normalization (e.g., /\\evil.com).\n // We do NOT convert \\ to / — it stays as a literal.\n\n // Step 3: Collapse consecutive slashes.\n let pathname = decoded.replace(/\\/\\/+/g, '/');\n\n // Step 4: Resolve .. and . segments.\n const segments = pathname.split('/');\n const resolved: string[] = [];\n for (const seg of segments) {\n if (seg === '..') {\n if (resolved.length <= 1) {\n // Trying to escape root — 400\n return { ok: false, status: 400 };\n }\n resolved.pop();\n } else if (seg !== '.') {\n resolved.push(seg);\n }\n }\n\n pathname = resolved.join('/') || '/';\n\n // Step 5: Strip trailing slash (except root \"/\").\n if (stripTrailingSlash && pathname.length > 1 && pathname.endsWith('/')) {\n pathname = pathname.slice(0, -1);\n }\n\n return { ok: true, pathname };\n}\n","/**\n * Segment key computation — the stable identity of a segment in the route tree.\n *\n * A segment key is the string that names a segment across the RSC/SSR/client\n * boundary: it appears in the X-Timber-State-Tree header, the X-Timber-Segments\n * header, SegmentOutlet props, the client segment cache, and (since TIM-1279)\n * interception scoping.\n *\n * This module lives in `routing/` rather than `server/` because the keys are a\n * property of the route tree itself — both the build-time scanner tree and the\n * runtime manifest tree produce identical keys for the same directory, which is\n * what lets a build-time value (an interception scope) be compared against a\n * request-time matched chain.\n *\n * See design/19-client-navigation.md §\"X-Timber-State-Tree Header\"\n */\n\n/**\n * Segment node shape expected by computeSegmentKeys.\n *\n * Structurally satisfied by both `SegmentNode` (build time) and\n * `ManifestSegmentNode` (request time) — keys depend only on the\n * URL path and the segment classification, never on file payloads.\n */\n\nimport type { CoercedParams } from '../shared/param-value.js';\n\nexport interface SegmentKeyInput {\n urlPath: string;\n segmentName?: string;\n segmentType?: string;\n}\n\n/**\n * Compute state-tree keys for a segment chain.\n *\n * Non-group segments use their urlPath as-is. Route groups accumulate\n * ancestor group names to produce globally unique keys:\n * app/(a)/(shared)/dashboard → keys: ['/', '/(a)', '/(a)/(shared)', '/dashboard']\n *\n * **An intercepting segment switches the chain to name accumulation for good.**\n * A children-path interception (TIM-1280) puts an intercepting node and its\n * descendants into the *main* rendered chain, and their `urlPath`s are not\n * URLs: interception adds no URL depth, so `app/(browse)/(...)[artistSlug]/[year]`\n * carries `/` and `/[year]`. Keyed by urlPath the intercepting node would\n * collide with its own owner, and `[year]` with any top-level `[year]` route —\n * so a client that had one mounted would reuse the wrong cached layout. The\n * switch is sticky rather than per-node because the *descendants* are where\n * the false URLs are; the intercepting node alone is not the problem.\n *\n * This is the single source of truth for segment keys — used by the\n * element builder (skip decisions, SegmentOutlet props), segment info\n * (X-Timber-Segments header), the client cache/state tree, and\n * interception scoping (`routing/interception.ts`).\n */\nexport function computeSegmentKeys(segments: SegmentKeyInput[]): string[] {\n const keys: string[] = [];\n let prevKey = '';\n let insideIntercepting = false;\n\n for (const segment of segments) {\n if (segment.segmentType === 'intercepting') insideIntercepting = true;\n if (segment.segmentType === 'group' || insideIntercepting) {\n const base = prevKey === '/' ? '' : prevKey;\n const key = `${base}/${segment.segmentName}`;\n keys.push(key);\n prevKey = key;\n } else {\n keys.push(segment.urlPath);\n prevKey = segment.urlPath;\n }\n }\n\n return keys;\n}\n\n/**\n * Compute tree paths for a segment chain — the directory path of each segment\n * with slots elided, e.g. `app/(browse)/feed` → `/(browse)/feed`.\n *\n * This is `computeSegmentKeys` with the group branch applied to *every*\n * segment rather than only to groups. That one difference is the whole point:\n * `computeSegmentKeys` resets to `urlPath` at each URL-visible segment, so\n * `(browse)/feed` and `(landing)/feed` both key as `/feed`. Two directories\n * that render different layouts must not share an identity.\n *\n * Used for interception scoping (`routing/interception.ts`), where the\n * question is \"does this route pass through *that* directory?\" — not \"does it\n * render this URL?\". Not interchangeable with `computeSegmentKeys`: the state\n * tree is keyed by URL on purpose, because the client caches by URL.\n */\nexport function computeSegmentTreePaths(segments: SegmentKeyInput[]): string[] {\n const paths: string[] = [];\n let prev = '';\n\n for (const segment of segments) {\n const name = segment.segmentName ?? '';\n if (!name) {\n // The app root — no directory name of its own.\n paths.push('/');\n prev = '/';\n continue;\n }\n const base = prev === '/' ? '' : prev;\n const path = `${base}/${name}`;\n paths.push(path);\n prev = path;\n }\n\n return paths;\n}\n\n/**\n * The directory names a tree path is built from — `/` is none, `/feed/(a)` is\n * `['feed', '(a)']`.\n *\n * The inverse of the walk above, and it lives beside it so the format is\n * stated once: `findChainByTreePath` (`server/children-interception.ts`) walks\n * these names back down the tree to the directory the path addresses, and\n * `treePathDepth` counts them. Both are readings of the same string, and a\n * reader that disagreed with the producer about what separates two names\n * resolves an interception to the wrong node or to none.\n */\nexport function treePathNames(treePath: string): string[] {\n return treePath === '/' ? [] : treePath.slice(1).split('/');\n}\n\n/**\n * How many directories a tree path names — `/` is 0, `/feed` is 1,\n * `/feed/(a)` is 2.\n *\n * Two tree paths on a single rendered chain are strictly nested, so on that\n * chain depth orders them totally — which is what makes it usable as \"the\n * deeper of these two directories\" wherever a route passes through both\n * (`routing/interception.ts`).\n */\nexport function treePathDepth(treePath: string): number {\n return treePathNames(treePath).length;\n}\n\n/**\n * Compute a unique key for a parallel route slot.\n * Format: `{parentSegmentId}/@{slotName}`, e.g. `/@sidebar` or `/dashboard/@modal`.\n */\nexport function computeSlotKey(parentSegmentId: string, slotName: string): string {\n const name = slotName.startsWith('@') ? slotName : `@${slotName}`;\n const prefix = parentSegmentId === '/' ? '' : parentSegmentId;\n return `${prefix}/${name}`;\n}\n\n/**\n * Compute a content key for a parallel route slot.\n *\n * The content key encodes everything that determines the slot's rendered\n * output for a given navigation: the slot key (which includes the owning\n * segment's identity and the slot name), the URL parts consumed by the\n * owning segment (which determine parent params the slot page might\n * read), the matched page file (or a sentinel for `default.tsx`), and\n * the slot's own extracted params.\n *\n * The slot key prevents cross-group collisions: two route groups at the\n * same URL level each owning a `@sidebar` slot produce different keys\n * even when both fall back to `default.tsx`.\n *\n * The key is opaque to the client — it stores whatever the server sent\n * and advertises it back. The server computes the destination key and\n * checks membership. This eliminates the need for the server to\n * reconstruct the client's state from a departing URL.\n *\n * See design/07-routing.md §\"Segment Tree Diffing on Navigation\"\n */\nexport function computeSlotContentKey(\n slotKey: string,\n ownerParts: string[],\n entryFile: string | null,\n slotParams: CoercedParams\n): string {\n const owner = ownerParts.join('/');\n const entry = entryFile ?? '\\x01';\n const paramKeys = Object.keys(slotParams).sort();\n const paramParts = paramKeys.map((k) => {\n const v = slotParams[k];\n return Array.isArray(v) ? `${k}=${v.map(String).join('\\x02')}` : `${k}=${String(v)}`;\n });\n return [slotKey, owner, entry, ...paramParts].join('\\0');\n}\n"],"mappings":";;;;;;;;;;;AAiDA,IAAa,6BAqBT;CACF,WAAW;EACT,MAAM;EACN,aAAa;EACb,UAAU;EACV,kBAAkB,CAAC,KAAK;EACxB,mBAAmB,CAAC,IAAI;EACxB,WAAW;CACb;CACA,UAAU;EACR,MAAM;EACN,aAAa;EACb,UAAU;EACV,kBAAkB,CAAC,KAAK;EACxB,mBAAmB,CAAC,IAAI;EACxB,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,aAAa;EACb,UAAU;EACV,kBAAkB,CAAC,MAAM;EACzB,mBAAmB,CAAC,IAAI;EACxB,WAAW;CAC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;CACT;CAEA,OAAO;AACT;;;;;;;;;;;;AAaA,SAAgB,cAAc,UAA4B;CACxD,OAAO,aAAa,MAAM,CAAC,IAAI,SAAS,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG;AAC5D;;;;;;;;;;AAWA,SAAgB,cAAc,UAA0B;CACtD,OAAO,cAAc,QAAQ,CAAC,CAAC;AACjC"}
@@ -1 +1 @@
1
- {"version":3,"file":"slot-params-BCTmZkQB.js","names":[],"sources":["../../src/shared/slot-params.ts"],"sourcesContent":["/**\n * Per-slot segment params — the one definition both halves of the API read.\n *\n * A parallel slot matches the URL through its *own* sub-tree, so it can derive\n * a param the main route never had, or derive the same name with a different\n * type (`[...year]` → `string[]` where the main route's `[year]` gave\n * `string`). The server answers `getSegmentParams(slotPath)` from a per-slot\n * map; the client answers `useSegmentParams(slotPath)` from the same map,\n * published on the RSC payload (TIM-1285).\n *\n * The merge lives here rather than in either half because the two must agree\n * about what \"the slot's params\" are — a divergence is invisible until\n * somebody reads a param of the wrong type, which is exactly the class of bug\n * this module closes.\n *\n * Isomorphic: no server or client imports.\n *\n * See design/41-global-params.md §\"Params in a parallel slot\".\n */\n\n/** Slot tree path → that slot's own coerced params. */\nexport type SlotParamsRecord = Record<string, Record<string, string | string[]>>;\n\n/**\n * The params a slot sees: the main route's as a base, the slot's own on top.\n *\n * Params from segments *above* the slot are not re-derived by the slot's own\n * chain, so they have to come from the main route; params the slot does\n * re-derive may have a different type than the main route gave them, so the\n * slot's win.\n *\n * Null-prototype, like every other param record the framework hands out\n * (`coerceSegmentParams` installs one unconditionally). A spread literal would\n * inherit `Object.prototype`, so a lookup for a param the route does not\n * define would resolve to an inherited member — `params.constructor` returning\n * a function instead of `undefined` — in the one param record that was built\n * by merging. See design/13-security.md #36c.\n */\nexport function mergeSlotParams(\n mainParams: Record<string, string | string[]>,\n slotParams: Record<string, string | string[]>\n): Record<string, string | string[]> {\n return Object.assign(Object.create(null), mainParams, slotParams);\n}\n\n/**\n * Resolve the params for a segment path against a published slot map.\n *\n * Returns the merge when `segmentPath` names a slot that published params,\n * and the main route's record otherwise — an ordinary (non-slot) segment\n * path, an unknown path, or a request with no slots at all. Mirrors the\n * server's `getSegmentParams(segmentPath)` branch exactly.\n *\n * `Object.hasOwn` rather than `in` or a truthiness test: the map arrives from\n * JSON, so a segment path of `constructor` or `toString` would otherwise\n * resolve to an inherited member of `Object.prototype`.\n */\nexport function resolveSegmentParams(\n mainParams: Record<string, string | string[]>,\n slotParams: SlotParamsRecord | null | undefined,\n segmentPath: string | undefined\n): Record<string, string | string[]> {\n if (!segmentPath || !slotParams || !Object.hasOwn(slotParams, segmentPath)) return mainParams;\n return cachedMerge(mainParams, slotParams, segmentPath);\n}\n\n/**\n * The merged record for one (main record, slot map, path) triple, reused until\n * one of the three changes.\n *\n * `useSegmentParams(slotPath)` calls this on every render. Returning a fresh\n * object each time makes the hook's result change by reference on renders where\n * nothing navigated, so a component using it as a `useEffect` dependency\n * re-runs the effect — and re-renders in a loop if that effect sets state —\n * while memoized children below it lose their memoization.\n *\n * Keyed on the *identities* of the two records, not their contents: both are\n * replaced rather than mutated on every navigation (`setCurrentParams`,\n * `setCurrentSlotParams`, and the server's per-request store), so identity is\n * the correct equality here and a deep comparison would be slower and no more\n * accurate.\n *\n * A `WeakMap` chain rather than a `Map`, so a superseded navigation's records\n * and their merges become collectable as soon as nothing else holds them.\n */\nconst mergeCache = new WeakMap<\n object,\n WeakMap<object, Map<string, Record<string, string | string[]>>>\n>();\n\nfunction cachedMerge(\n mainParams: Record<string, string | string[]>,\n slotParams: SlotParamsRecord,\n segmentPath: string\n): Record<string, string | string[]> {\n let bySlotMap = mergeCache.get(mainParams);\n if (!bySlotMap) {\n bySlotMap = new WeakMap();\n mergeCache.set(mainParams, bySlotMap);\n }\n let byPath = bySlotMap.get(slotParams);\n if (!byPath) {\n byPath = new Map();\n bySlotMap.set(slotParams, byPath);\n }\n const cached = byPath.get(segmentPath);\n if (cached) return cached;\n const merged = mergeSlotParams(mainParams, slotParams[segmentPath]);\n byPath.set(segmentPath, merged);\n return merged;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsCA,SAAgB,gBACd,YACA,YACmC;CACnC,OAAO,OAAO,OAAO,OAAO,OAAO,IAAI,GAAG,YAAY,UAAU;AAClE;;;;;;;;;;;;;AAcA,SAAgB,qBACd,YACA,YACA,aACmC;CACnC,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,OAAO,OAAO,YAAY,WAAW,GAAG,OAAO;CACnF,OAAO,YAAY,YAAY,YAAY,WAAW;AACxD;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,6BAAa,IAAI,QAGrB;AAEF,SAAS,YACP,YACA,YACA,aACmC;CACnC,IAAI,YAAY,WAAW,IAAI,UAAU;CACzC,IAAI,CAAC,WAAW;EACd,4BAAY,IAAI,QAAQ;EACxB,WAAW,IAAI,YAAY,SAAS;CACtC;CACA,IAAI,SAAS,UAAU,IAAI,UAAU;CACrC,IAAI,CAAC,QAAQ;EACX,yBAAS,IAAI,IAAI;EACjB,UAAU,IAAI,YAAY,MAAM;CAClC;CACA,MAAM,SAAS,OAAO,IAAI,WAAW;CACrC,IAAI,QAAQ,OAAO;CACnB,MAAM,SAAS,gBAAgB,YAAY,WAAW,YAAY;CAClE,OAAO,IAAI,aAAa,MAAM;CAC9B,OAAO;AACT"}
1
+ {"version":3,"file":"slot-params-BCTmZkQB.js","names":[],"sources":["../../src/shared/slot-params.ts"],"sourcesContent":["/**\n * Per-slot segment params — the one definition both halves of the API read.\n *\n * A parallel slot matches the URL through its *own* sub-tree, so it can derive\n * a param the main route never had, or derive the same name with a different\n * type (`[...year]` → `string[]` where the main route's `[year]` gave\n * `string`). The server answers `getSegmentParams(slotPath)` from a per-slot\n * map; the client answers `useSegmentParams(slotPath)` from the same map,\n * published on the RSC payload (TIM-1285).\n *\n * The merge lives here rather than in either half because the two must agree\n * about what \"the slot's params\" are — a divergence is invisible until\n * somebody reads a param of the wrong type, which is exactly the class of bug\n * this module closes.\n *\n * Isomorphic: no server or client imports.\n *\n * See design/41-global-params.md §\"Params in a parallel slot\".\n */\n\nimport type { CoercedParams } from './param-value.js';\n\n/** Slot tree path → that slot's own coerced params. */\nexport type SlotParamsRecord = Record<string, CoercedParams>;\n\n/**\n * The params a slot sees: the main route's as a base, the slot's own on top.\n *\n * Params from segments *above* the slot are not re-derived by the slot's own\n * chain, so they have to come from the main route; params the slot does\n * re-derive may have a different type than the main route gave them, so the\n * slot's win.\n *\n * Null-prototype, like every other param record the framework hands out\n * (`coerceSegmentParams` installs one unconditionally). A spread literal would\n * inherit `Object.prototype`, so a lookup for a param the route does not\n * define would resolve to an inherited member — `params.constructor` returning\n * a function instead of `undefined` — in the one param record that was built\n * by merging. See design/13-security.md #36c.\n */\nexport function mergeSlotParams(\n mainParams: CoercedParams,\n slotParams: CoercedParams\n): CoercedParams {\n return Object.assign(Object.create(null), mainParams, slotParams);\n}\n\n/**\n * Resolve the params for a segment path against a published slot map.\n *\n * Returns the merge when `segmentPath` names a slot that published params,\n * and the main route's record otherwise — an ordinary (non-slot) segment\n * path, an unknown path, or a request with no slots at all. Mirrors the\n * server's `getSegmentParams(segmentPath)` branch exactly.\n *\n * `Object.hasOwn` rather than `in` or a truthiness test: the map arrives from\n * JSON, so a segment path of `constructor` or `toString` would otherwise\n * resolve to an inherited member of `Object.prototype`.\n */\nexport function resolveSegmentParams(\n mainParams: CoercedParams,\n slotParams: SlotParamsRecord | null | undefined,\n segmentPath: string | undefined\n): CoercedParams {\n if (!segmentPath || !slotParams || !Object.hasOwn(slotParams, segmentPath)) return mainParams;\n return cachedMerge(mainParams, slotParams, segmentPath);\n}\n\n/**\n * The merged record for one (main record, slot map, path) triple, reused until\n * one of the three changes.\n *\n * `useSegmentParams(slotPath)` calls this on every render. Returning a fresh\n * object each time makes the hook's result change by reference on renders where\n * nothing navigated, so a component using it as a `useEffect` dependency\n * re-runs the effect — and re-renders in a loop if that effect sets state —\n * while memoized children below it lose their memoization.\n *\n * Keyed on the *identities* of the two records, not their contents: both are\n * replaced rather than mutated on every navigation (`setCurrentParams`,\n * `setCurrentSlotParams`, and the server's per-request store), so identity is\n * the correct equality here and a deep comparison would be slower and no more\n * accurate.\n *\n * A `WeakMap` chain rather than a `Map`, so a superseded navigation's records\n * and their merges become collectable as soon as nothing else holds them.\n */\nconst mergeCache = new WeakMap<object, WeakMap<object, Map<string, CoercedParams>>>();\n\nfunction cachedMerge(\n mainParams: CoercedParams,\n slotParams: SlotParamsRecord,\n segmentPath: string\n): CoercedParams {\n let bySlotMap = mergeCache.get(mainParams);\n if (!bySlotMap) {\n bySlotMap = new WeakMap();\n mergeCache.set(mainParams, bySlotMap);\n }\n let byPath = bySlotMap.get(slotParams);\n if (!byPath) {\n byPath = new Map();\n bySlotMap.set(slotParams, byPath);\n }\n const cached = byPath.get(segmentPath);\n if (cached) return cached;\n const merged = mergeSlotParams(mainParams, slotParams[segmentPath]);\n byPath.set(segmentPath, merged);\n return merged;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAwCA,SAAgB,gBACd,YACA,YACe;CACf,OAAO,OAAO,OAAO,OAAO,OAAO,IAAI,GAAG,YAAY,UAAU;AAClE;;;;;;;;;;;;;AAcA,SAAgB,qBACd,YACA,YACA,aACe;CACf,IAAI,CAAC,eAAe,CAAC,cAAc,CAAC,OAAO,OAAO,YAAY,WAAW,GAAG,OAAO;CACnF,OAAO,YAAY,YAAY,YAAY,WAAW;AACxD;;;;;;;;;;;;;;;;;;;;AAqBA,IAAM,6BAAa,IAAI,QAA6D;AAEpF,SAAS,YACP,YACA,YACA,aACe;CACf,IAAI,YAAY,WAAW,IAAI,UAAU;CACzC,IAAI,CAAC,WAAW;EACd,4BAAY,IAAI,QAAQ;EACxB,WAAW,IAAI,YAAY,SAAS;CACtC;CACA,IAAI,SAAS,UAAU,IAAI,UAAU;CACrC,IAAI,CAAC,QAAQ;EACX,yBAAS,IAAI,IAAI;EACjB,UAAU,IAAI,YAAY,MAAM;CAClC;CACA,MAAM,SAAS,OAAO,IAAI,WAAW;CACrC,IAAI,QAAQ,OAAO;CACnB,MAAM,SAAS,gBAAgB,YAAY,WAAW,YAAY;CAClE,OAAO,IAAI,aAAa,MAAM;CAC9B,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"ssr-data-14MXm7Pj.js","names":[],"sources":["../../src/client/state.ts","../../src/client/ssr-data.ts"],"sourcesContent":["/**\n * Centralized client singleton state registry.\n *\n * ALL mutable module-level state that must have singleton semantics across\n * the client bundle lives here. Individual modules (router-ref.ts, ssr-data.ts,\n * use-segment-params.ts, use-search-params.ts, unload-guard.ts) import from this file\n * and re-export thin wrapper functions.\n *\n * Why: In Vite dev, a module is instantiated separately if reached via different\n * import paths (e.g., relative `./foo.js` vs barrel `@timber-js/app/client`).\n * By centralizing all mutable state in a single module that is always reached\n * through the same dependency chain (barrel → wrapper → state.ts), we guarantee\n * a single instance of every piece of shared state.\n *\n * DO NOT import this file from outside client/. Server code must never depend\n * on client state. The barrel (client/index.ts) is the public entry point.\n *\n * See design/18-build-system.md §\"Module Singleton Strategy\" and\n * §\"Singleton State Registry\".\n */\n\nimport type { SlotParamsRecord } from '../shared/slot-params.js';\nimport type { RouterInstance } from './router-types.js';\nimport type { SsrData } from './ssr-data.js';\n\n// ─── Router (from router-ref.ts) ──────────────────────────────────────────\n\n/** The global router singleton — set once during bootstrap. */\nexport let globalRouter: RouterInstance | null = null;\n\nexport function _setGlobalRouter(router: RouterInstance | null): void {\n globalRouter = router;\n}\n\n// ─── SSR Data Provider (from ssr-data.ts) ──────────────────────────────────\n\n/**\n * ALS-backed SSR data provider. When registered, getSsrData() reads from\n * this function (ALS store) instead of module-level currentSsrData.\n */\nexport let ssrDataProvider: (() => SsrData | undefined) | undefined;\n\nexport function _setSsrDataProvider(provider: (() => SsrData | undefined) | undefined): void {\n ssrDataProvider = provider;\n}\n\n/** Fallback SSR data for tests and environments without ALS. */\nexport let currentSsrData: SsrData | undefined;\n\nexport function _setCurrentSsrData(data: SsrData | undefined): void {\n currentSsrData = data;\n}\n\n// ─── Route Params (from use-segment-params.ts) ──────────────────────────────────────\n\n/** Current route params snapshot — replaced (not mutated) on each navigation. */\nexport let currentParams: Record<string, string | string[]> = {};\n\nexport function _setCurrentParams(params: Record<string, string | string[]>): void {\n currentParams = params;\n}\n\n/**\n * Per-slot params snapshot, keyed by slot tree path — the module-level\n * fallback behind `useSegmentParams(slotPath)` when no NavigationContext is\n * mounted (tests, calls outside a component). Replaced, never mutated, on\n * each navigation. See TIM-1285.\n */\nexport let currentSlotParams: SlotParamsRecord | null = null;\n\nexport function _setCurrentSlotParams(slotParams: SlotParamsRecord | null): void {\n currentSlotParams = slotParams;\n}\n\n/** Listeners notified when currentParams changes. */\nexport const paramsListeners = new Set<() => void>();\n\n// ─── Search Params Cache (from use-search-params.ts) ────────────────────────\n\n/** Cached search string — avoids reparsing when URL hasn't changed. */\nexport let cachedSearch = '';\nexport let cachedSearchParams = new URLSearchParams();\n\nexport function _setCachedSearch(search: string, params: URLSearchParams): void {\n cachedSearch = search;\n cachedSearchParams = params;\n}\n\n// ─── Unload Guard (from unload-guard.ts) ─────────────────────────────────────\n\n/** Whether the page is currently being unloaded. */\nexport let unloading = false;\n\nexport function _setUnloading(value: boolean): void {\n unloading = value;\n}\n","/**\n * SSR Data — per-request state for client hooks during server-side rendering.\n *\n * RSC and SSR are separate Vite module graphs (see design/18-build-system.md),\n * so the RSC environment's request-context ALS is not visible to SSR modules.\n * This module provides getter/setter functions that ssr-entry.ts uses to\n * populate per-request data for React's render.\n *\n * Request isolation: On the server, ssr-entry.ts registers an ALS-backed\n * provider via registerSsrDataProvider(). getSsrData() reads from the ALS\n * store, ensuring correct per-request data even when Suspense boundaries\n * resolve asynchronously across concurrent requests. The module-level\n * setSsrData/clearSsrData functions are kept as a fallback for tests\n * and environments without ALS.\n *\n * IMPORTANT: This module must NOT import node:async_hooks or any Node.js-only\n * APIs, as it's imported by 'use client' hooks that are bundled for the browser.\n * The ALS instance lives in ssr-entry.ts (server-only); this module only holds\n * a reference to the provider function.\n *\n * All mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n */\n\nimport {\n ssrDataProvider,\n currentSsrData,\n _setSsrDataProvider,\n _setCurrentSsrData,\n} from './state.js';\nimport type { SlotParamsRecord } from '../shared/slot-params.js';\n\n// ─── Types ────────────────────────────────────────────────────────\n\nexport interface SsrData {\n /** The request's URL pathname (e.g. '/dashboard/settings') */\n pathname: string;\n /** The request's search params as a plain record */\n searchParams: Record<string, string>;\n /** The request's cookies as name→value pairs */\n cookies: Map<string, string>;\n /** The request's route params (e.g. { id: '123' }) */\n params: Record<string, string | string[]>;\n /**\n * Per-slot params keyed by slot tree path, absent when the request rendered\n * no slot with params of its own (TIM-1285).\n */\n slotParams?: SlotParamsRecord;\n /**\n * Mutable reference to NavContext for error boundary → pipeline communication.\n *\n * When TimberErrorBoundary catches a DenySignal during SSR, it:\n * 1. Sets `statusCode` to the deny status (e.g., 403) — so the HTTP\n * Response has the correct status code without a re-render.\n * 2. Sets `_denyHandledByBoundary = true` — so the pipeline skips\n * the redundant renderDenyPage() re-render.\n *\n * This runs synchronously during Fizz rendering, BEFORE onShellReady,\n * so the status code is committed before any bytes are sent.\n *\n * See TIM-664, design/04-authorization.md §\"React.cache Scope in Deny/Error Re-renders\"\n */\n _navContext?: { statusCode?: number; _denyHandledByBoundary?: boolean };\n}\n\n// ─── ALS-Backed Provider ─────────────────────────────────────────\n//\n// Server-side code (ssr-entry.ts) registers a provider that reads\n// from AsyncLocalStorage. This avoids importing node:async_hooks\n// in this browser-bundled module.\n//\n// Module singleton guarantee: In Vite's SSR environment, both\n// ssr-entry.ts (via #/client/ssr-data.js) and client component hooks\n// (via @timber-js/app/client) must resolve to the SAME module instance\n// of this file. The timber-shims plugin ensures this by remapping\n// @timber-js/app/client → src/client/index.ts in the SSR environment.\n// Without this remap, @timber-js/app/client resolves to dist/ (via\n// package.json exports), creating a split where registerSsrDataProvider\n// writes to one instance but getSsrData reads from another.\n// See timber-shims plugin resolveId for details.\n\n/**\n * Register an ALS-backed SSR data provider. Called once at module load\n * by ssr-entry.ts to wire up per-request data via AsyncLocalStorage.\n *\n * When registered, getSsrData() reads from the provider (ALS store)\n * instead of module-level state, ensuring correct isolation for\n * concurrent requests with streaming Suspense.\n */\nexport function registerSsrDataProvider(provider: () => SsrData | undefined): void {\n _setSsrDataProvider(provider);\n}\n\n// ─── Module-Level Fallback ────────────────────────────────────────\n//\n// Used by tests and as a fallback when no ALS provider is registered.\n\n/**\n * Set the SSR data for the current request via module-level state.\n *\n * In production, ssr-entry.ts uses ALS (runWithSsrData) instead.\n * This function is retained for tests and as a fallback.\n */\nexport function setSsrData(data: SsrData): void {\n _setCurrentSsrData(data);\n}\n\n/**\n * Clear the SSR data after rendering completes.\n *\n * In production, ALS scope handles cleanup automatically.\n * This function is retained for tests and as a fallback.\n */\nexport function clearSsrData(): void {\n _setCurrentSsrData(undefined);\n}\n\n/**\n * Read the current request's SSR data. Returns undefined when called\n * outside an SSR render (i.e. on the client after hydration).\n *\n * Prefers the ALS-backed provider when registered (server-side),\n * falling back to module-level state (tests, legacy).\n *\n * Used by client hooks' server snapshot functions.\n */\nexport function getSsrData(): SsrData | undefined {\n if (ssrDataProvider) {\n return ssrDataProvider();\n }\n return currentSsrData;\n}\n"],"mappings":";;AA4BA,IAAW,eAAsC;AAEjD,SAAgB,iBAAiB,QAAqC;CACpE,eAAe;AACjB;;;;;AAQA,IAAW;;AAOX,IAAW;AAEX,SAAgB,mBAAmB,MAAiC;CAClE,iBAAiB;AACnB;;AAKA,IAAW,gBAAmD,CAAC;AAE/D,SAAgB,kBAAkB,QAAiD;CACjF,gBAAgB;AAClB;;;;;;;AAQA,IAAW,oBAA6C;AAExD,SAAgB,sBAAsB,YAA2C;CAC/E,oBAAoB;AACtB;;AAQA,IAAW,eAAe;AAC1B,IAAW,qBAAqB,IAAI,gBAAgB;AAEpD,SAAgB,iBAAiB,QAAgB,QAA+B;CAC9E,eAAe;CACf,qBAAqB;AACvB;;AAKA,IAAW,YAAY;AAEvB,SAAgB,cAAc,OAAsB;CAClD,YAAY;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACQA,SAAgB,WAAW,MAAqB;CAC9C,mBAAmB,IAAI;AACzB;;;;;;;AAQA,SAAgB,eAAqB;CACnC,mBAAmB,KAAA,CAAS;AAC9B;;;;;;;;;;AAWA,SAAgB,aAAkC;CAChD,IAAI,iBACF,OAAO,gBAAgB;CAEzB,OAAO;AACT"}
1
+ {"version":3,"file":"ssr-data-14MXm7Pj.js","names":[],"sources":["../../src/client/state.ts","../../src/client/ssr-data.ts"],"sourcesContent":["/**\n * Centralized client singleton state registry.\n *\n * ALL mutable module-level state that must have singleton semantics across\n * the client bundle lives here. Individual modules (router-ref.ts, ssr-data.ts,\n * use-segment-params.ts, use-search-params.ts, unload-guard.ts) import from this file\n * and re-export thin wrapper functions.\n *\n * Why: In Vite dev, a module is instantiated separately if reached via different\n * import paths (e.g., relative `./foo.js` vs barrel `@timber-js/app/client`).\n * By centralizing all mutable state in a single module that is always reached\n * through the same dependency chain (barrel → wrapper → state.ts), we guarantee\n * a single instance of every piece of shared state.\n *\n * DO NOT import this file from outside client/. Server code must never depend\n * on client state. The barrel (client/index.ts) is the public entry point.\n *\n * See design/18-build-system.md §\"Module Singleton Strategy\" and\n * §\"Singleton State Registry\".\n */\n\nimport type { CoercedParams } from '../shared/param-value.js';\nimport type { SlotParamsRecord } from '../shared/slot-params.js';\nimport type { RouterInstance } from './router-types.js';\nimport type { SsrData } from './ssr-data.js';\n\n// ─── Router (from router-ref.ts) ──────────────────────────────────────────\n\n/** The global router singleton — set once during bootstrap. */\nexport let globalRouter: RouterInstance | null = null;\n\nexport function _setGlobalRouter(router: RouterInstance | null): void {\n globalRouter = router;\n}\n\n// ─── SSR Data Provider (from ssr-data.ts) ──────────────────────────────────\n\n/**\n * ALS-backed SSR data provider. When registered, getSsrData() reads from\n * this function (ALS store) instead of module-level currentSsrData.\n */\nexport let ssrDataProvider: (() => SsrData | undefined) | undefined;\n\nexport function _setSsrDataProvider(provider: (() => SsrData | undefined) | undefined): void {\n ssrDataProvider = provider;\n}\n\n/** Fallback SSR data for tests and environments without ALS. */\nexport let currentSsrData: SsrData | undefined;\n\nexport function _setCurrentSsrData(data: SsrData | undefined): void {\n currentSsrData = data;\n}\n\n// ─── Route Params (from use-segment-params.ts) ──────────────────────────────────────\n\n/** Current route params snapshot — replaced (not mutated) on each navigation. */\nexport let currentParams: CoercedParams = {};\n\nexport function _setCurrentParams(params: CoercedParams): void {\n currentParams = params;\n}\n\n/**\n * Per-slot params snapshot, keyed by slot tree path — the module-level\n * fallback behind `useSegmentParams(slotPath)` when no NavigationContext is\n * mounted (tests, calls outside a component). Replaced, never mutated, on\n * each navigation. See TIM-1285.\n */\nexport let currentSlotParams: SlotParamsRecord | null = null;\n\nexport function _setCurrentSlotParams(slotParams: SlotParamsRecord | null): void {\n currentSlotParams = slotParams;\n}\n\n/** Listeners notified when currentParams changes. */\nexport const paramsListeners = new Set<() => void>();\n\n// ─── Search Params Cache (from use-search-params.ts) ────────────────────────\n\n/** Cached search string — avoids reparsing when URL hasn't changed. */\nexport let cachedSearch = '';\nexport let cachedSearchParams = new URLSearchParams();\n\nexport function _setCachedSearch(search: string, params: URLSearchParams): void {\n cachedSearch = search;\n cachedSearchParams = params;\n}\n\n// ─── Unload Guard (from unload-guard.ts) ─────────────────────────────────────\n\n/** Whether the page is currently being unloaded. */\nexport let unloading = false;\n\nexport function _setUnloading(value: boolean): void {\n unloading = value;\n}\n","/**\n * SSR Data — per-request state for client hooks during server-side rendering.\n *\n * RSC and SSR are separate Vite module graphs (see design/18-build-system.md),\n * so the RSC environment's request-context ALS is not visible to SSR modules.\n * This module provides getter/setter functions that ssr-entry.ts uses to\n * populate per-request data for React's render.\n *\n * Request isolation: On the server, ssr-entry.ts registers an ALS-backed\n * provider via registerSsrDataProvider(). getSsrData() reads from the ALS\n * store, ensuring correct per-request data even when Suspense boundaries\n * resolve asynchronously across concurrent requests. The module-level\n * setSsrData/clearSsrData functions are kept as a fallback for tests\n * and environments without ALS.\n *\n * IMPORTANT: This module must NOT import node:async_hooks or any Node.js-only\n * APIs, as it's imported by 'use client' hooks that are bundled for the browser.\n * The ALS instance lives in ssr-entry.ts (server-only); this module only holds\n * a reference to the provider function.\n *\n * All mutable state is delegated to client/state.ts for singleton guarantees.\n * See design/18-build-system.md §\"Singleton State Registry\"\n */\n\nimport {\n ssrDataProvider,\n currentSsrData,\n _setSsrDataProvider,\n _setCurrentSsrData,\n} from './state.js';\nimport type { CoercedParams } from '../shared/param-value.js';\nimport type { SlotParamsRecord } from '../shared/slot-params.js';\n\n// ─── Types ────────────────────────────────────────────────────────\n\nexport interface SsrData {\n /** The request's URL pathname (e.g. '/dashboard/settings') */\n pathname: string;\n /** The request's search params as a plain record */\n searchParams: Record<string, string>;\n /** The request's cookies as name→value pairs */\n cookies: Map<string, string>;\n /** The request's route params (e.g. { id: '123' }) */\n params: CoercedParams;\n /**\n * Per-slot params keyed by slot tree path, absent when the request rendered\n * no slot with params of its own (TIM-1285).\n */\n slotParams?: SlotParamsRecord;\n /**\n * Mutable reference to NavContext for error boundary → pipeline communication.\n *\n * When TimberErrorBoundary catches a DenySignal during SSR, it:\n * 1. Sets `statusCode` to the deny status (e.g., 403) — so the HTTP\n * Response has the correct status code without a re-render.\n * 2. Sets `_denyHandledByBoundary = true` — so the pipeline skips\n * the redundant renderDenyPage() re-render.\n *\n * This runs synchronously during Fizz rendering, BEFORE onShellReady,\n * so the status code is committed before any bytes are sent.\n *\n * See TIM-664, design/04-authorization.md §\"React.cache Scope in Deny/Error Re-renders\"\n */\n _navContext?: { statusCode?: number; _denyHandledByBoundary?: boolean };\n}\n\n// ─── ALS-Backed Provider ─────────────────────────────────────────\n//\n// Server-side code (ssr-entry.ts) registers a provider that reads\n// from AsyncLocalStorage. This avoids importing node:async_hooks\n// in this browser-bundled module.\n//\n// Module singleton guarantee: In Vite's SSR environment, both\n// ssr-entry.ts (via #/client/ssr-data.js) and client component hooks\n// (via @timber-js/app/client) must resolve to the SAME module instance\n// of this file. The timber-shims plugin ensures this by remapping\n// @timber-js/app/client → src/client/index.ts in the SSR environment.\n// Without this remap, @timber-js/app/client resolves to dist/ (via\n// package.json exports), creating a split where registerSsrDataProvider\n// writes to one instance but getSsrData reads from another.\n// See timber-shims plugin resolveId for details.\n\n/**\n * Register an ALS-backed SSR data provider. Called once at module load\n * by ssr-entry.ts to wire up per-request data via AsyncLocalStorage.\n *\n * When registered, getSsrData() reads from the provider (ALS store)\n * instead of module-level state, ensuring correct isolation for\n * concurrent requests with streaming Suspense.\n */\nexport function registerSsrDataProvider(provider: () => SsrData | undefined): void {\n _setSsrDataProvider(provider);\n}\n\n// ─── Module-Level Fallback ────────────────────────────────────────\n//\n// Used by tests and as a fallback when no ALS provider is registered.\n\n/**\n * Set the SSR data for the current request via module-level state.\n *\n * In production, ssr-entry.ts uses ALS (runWithSsrData) instead.\n * This function is retained for tests and as a fallback.\n */\nexport function setSsrData(data: SsrData): void {\n _setCurrentSsrData(data);\n}\n\n/**\n * Clear the SSR data after rendering completes.\n *\n * In production, ALS scope handles cleanup automatically.\n * This function is retained for tests and as a fallback.\n */\nexport function clearSsrData(): void {\n _setCurrentSsrData(undefined);\n}\n\n/**\n * Read the current request's SSR data. Returns undefined when called\n * outside an SSR render (i.e. on the client after hydration).\n *\n * Prefers the ALS-backed provider when registered (server-side),\n * falling back to module-level state (tests, legacy).\n *\n * Used by client hooks' server snapshot functions.\n */\nexport function getSsrData(): SsrData | undefined {\n if (ssrDataProvider) {\n return ssrDataProvider();\n }\n return currentSsrData;\n}\n"],"mappings":";;AA6BA,IAAW,eAAsC;AAEjD,SAAgB,iBAAiB,QAAqC;CACpE,eAAe;AACjB;;;;;AAQA,IAAW;;AAOX,IAAW;AAEX,SAAgB,mBAAmB,MAAiC;CAClE,iBAAiB;AACnB;;AAKA,IAAW,gBAA+B,CAAC;AAE3C,SAAgB,kBAAkB,QAA6B;CAC7D,gBAAgB;AAClB;;;;;;;AAQA,IAAW,oBAA6C;AAExD,SAAgB,sBAAsB,YAA2C;CAC/E,oBAAoB;AACtB;;AAQA,IAAW,eAAe;AAC1B,IAAW,qBAAqB,IAAI,gBAAgB;AAEpD,SAAgB,iBAAiB,QAAgB,QAA+B;CAC9E,eAAe;CACf,qBAAqB;AACvB;;AAKA,IAAW,YAAY;AAEvB,SAAgB,cAAc,OAAsB;CAClD,YAAY;AACd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACQA,SAAgB,WAAW,MAAqB;CAC9C,mBAAmB,IAAI;AACzB;;;;;;;AAQA,SAAgB,eAAqB;CACnC,mBAAmB,KAAA,CAAS;AAC9B;;;;;;;;;;AAWA,SAAgB,aAAkC;CAChD,IAAI,iBACF,OAAO,gBAAgB;CAEzB,OAAO;AACT"}