ai-agent-router 0.2.2 → 0.2.4

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 (700) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +4 -1
  3. package/.next/build/chunks/{[root-of-the-server]__6d51cb5d._.js → [root-of-the-server]__0iv9ksq._.js} +1 -1
  4. package/.next/build/chunks/[root-of-the-server]__0iv9ksq._.js.map +8 -0
  5. package/.next/build/chunks/{[root-of-the-server]__44695d76._.js → [root-of-the-server]__0rua-~2._.js} +30 -30
  6. package/.next/build/chunks/[root-of-the-server]__0rua-~2._.js.map +11 -0
  7. package/.next/build/chunks/{[turbopack-node]_transforms_postcss_ts_df7a5b11._.js → [turbopack-node]_transforms_postcss_ts_0nnejqq._.js} +2 -2
  8. package/.next/build/chunks/[turbopack]_runtime.js +155 -60
  9. package/.next/build/chunks/[turbopack]_runtime.js.map +6 -5
  10. package/.next/build/chunks/{node_modules_fe693df6._.js → node_modules_13sb.px._.js} +1 -1
  11. package/.next/build/chunks/{node_modules_fe693df6._.js.map → node_modules_13sb.px._.js.map} +42 -42
  12. package/.next/build/postcss.js +5 -5
  13. package/.next/build-manifest.json +8 -7
  14. package/.next/diagnostics/framework.json +1 -1
  15. package/.next/diagnostics/route-bundle-stats.json +93 -0
  16. package/.next/fallback-build-manifest.json +3 -2
  17. package/.next/images-manifest.json +1 -0
  18. package/.next/next-minimal-server.js.nft.json +1 -1
  19. package/.next/next-server.js.nft.json +1 -1
  20. package/.next/prerender-manifest.json +33 -9
  21. package/.next/required-server-files.js +18 -6
  22. package/.next/required-server-files.json +18 -6
  23. package/.next/routes-manifest.json +19 -0
  24. package/.next/server/app/_global-error/page/build-manifest.json +5 -5
  25. package/.next/server/app/_global-error/page.js +8 -9
  26. package/.next/server/app/_global-error/page.js.nft.json +1 -1
  27. package/.next/server/app/_global-error/page_client-reference-manifest.js +2 -1
  28. package/.next/server/app/_global-error.html +1 -2
  29. package/.next/server/app/_global-error.rsc +11 -9
  30. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  31. package/.next/server/app/_global-error.segments/_full.segment.rsc +11 -9
  32. package/.next/server/app/_global-error.segments/_head.segment.rsc +3 -3
  33. package/.next/server/app/_global-error.segments/_index.segment.rsc +4 -3
  34. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  35. package/.next/server/app/_not-found/page/build-manifest.json +5 -5
  36. package/.next/server/app/_not-found/page.js +11 -12
  37. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  38. package/.next/server/app/_not-found/page_client-reference-manifest.js +2 -1
  39. package/.next/server/app/_not-found.html +1 -1
  40. package/.next/server/app/_not-found.rsc +13 -11
  41. package/.next/server/app/_not-found.segments/_full.segment.rsc +13 -11
  42. package/.next/server/app/_not-found.segments/_head.segment.rsc +3 -3
  43. package/.next/server/app/_not-found.segments/_index.segment.rsc +5 -5
  44. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  45. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +4 -3
  46. package/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  47. package/.next/server/app/api/config/route/build-manifest.json +1 -3
  48. package/.next/server/app/api/config/route.js +4 -4
  49. package/.next/server/app/api/config/route.js.nft.json +1 -1
  50. package/.next/server/app/api/config/route_client-reference-manifest.js +2 -1
  51. package/.next/server/app/api/gateway/[...path]/route/build-manifest.json +1 -3
  52. package/.next/server/app/api/gateway/[...path]/route.js +5 -5
  53. package/.next/server/app/api/gateway/[...path]/route.js.nft.json +1 -1
  54. package/.next/server/app/api/gateway/[...path]/route_client-reference-manifest.js +2 -1
  55. package/.next/server/app/api/gateway/models/route/build-manifest.json +1 -3
  56. package/.next/server/app/api/gateway/models/route.js +4 -4
  57. package/.next/server/app/api/gateway/models/route.js.nft.json +1 -1
  58. package/.next/server/app/api/gateway/models/route_client-reference-manifest.js +2 -1
  59. package/.next/server/app/api/gateway/route/build-manifest.json +1 -3
  60. package/.next/server/app/api/gateway/route.js +5 -5
  61. package/.next/server/app/api/gateway/route.js.nft.json +1 -1
  62. package/.next/server/app/api/gateway/route_client-reference-manifest.js +2 -1
  63. package/.next/server/app/api/ide/claude/apply/route/build-manifest.json +1 -3
  64. package/.next/server/app/api/ide/claude/apply/route.js +4 -4
  65. package/.next/server/app/api/ide/claude/apply/route.js.nft.json +1 -1
  66. package/.next/server/app/api/ide/claude/apply/route_client-reference-manifest.js +2 -1
  67. package/.next/server/app/api/ide/claude/available-models/route/build-manifest.json +1 -3
  68. package/.next/server/app/api/ide/claude/available-models/route.js +4 -4
  69. package/.next/server/app/api/ide/claude/available-models/route.js.nft.json +1 -1
  70. package/.next/server/app/api/ide/claude/available-models/route_client-reference-manifest.js +2 -1
  71. package/.next/server/app/api/ide/claude/restore/route/build-manifest.json +1 -3
  72. package/.next/server/app/api/ide/claude/restore/route.js +3 -3
  73. package/.next/server/app/api/ide/claude/restore/route.js.nft.json +1 -1
  74. package/.next/server/app/api/ide/claude/restore/route_client-reference-manifest.js +2 -1
  75. package/.next/server/app/api/ide/claude/save/route/build-manifest.json +1 -3
  76. package/.next/server/app/api/ide/claude/save/route.js +4 -4
  77. package/.next/server/app/api/ide/claude/save/route.js.nft.json +1 -1
  78. package/.next/server/app/api/ide/claude/save/route_client-reference-manifest.js +2 -1
  79. package/.next/server/app/api/ide/claude/status/route/build-manifest.json +1 -3
  80. package/.next/server/app/api/ide/claude/status/route.js +4 -4
  81. package/.next/server/app/api/ide/claude/status/route.js.nft.json +1 -1
  82. package/.next/server/app/api/ide/claude/status/route_client-reference-manifest.js +2 -1
  83. package/.next/server/app/api/ide/claude/test/route/build-manifest.json +1 -3
  84. package/.next/server/app/api/ide/claude/test/route.js +5 -5
  85. package/.next/server/app/api/ide/claude/test/route.js.nft.json +1 -1
  86. package/.next/server/app/api/ide/claude/test/route_client-reference-manifest.js +2 -1
  87. package/.next/server/app/api/ide/openclaw/apply/route/build-manifest.json +1 -3
  88. package/.next/server/app/api/ide/openclaw/apply/route.js +4 -4
  89. package/.next/server/app/api/ide/openclaw/apply/route.js.nft.json +1 -1
  90. package/.next/server/app/api/ide/openclaw/apply/route_client-reference-manifest.js +2 -1
  91. package/.next/server/app/api/ide/openclaw/available-models/route/build-manifest.json +1 -3
  92. package/.next/server/app/api/ide/openclaw/available-models/route.js +4 -4
  93. package/.next/server/app/api/ide/openclaw/available-models/route.js.nft.json +1 -1
  94. package/.next/server/app/api/ide/openclaw/available-models/route_client-reference-manifest.js +2 -1
  95. package/.next/server/app/api/ide/openclaw/preview/route/build-manifest.json +1 -3
  96. package/.next/server/app/api/ide/openclaw/preview/route.js +4 -4
  97. package/.next/server/app/api/ide/openclaw/preview/route.js.nft.json +1 -1
  98. package/.next/server/app/api/ide/openclaw/preview/route_client-reference-manifest.js +2 -1
  99. package/.next/server/app/api/ide/openclaw/restore/route/build-manifest.json +1 -3
  100. package/.next/server/app/api/ide/openclaw/restore/route.js +3 -3
  101. package/.next/server/app/api/ide/openclaw/restore/route.js.nft.json +1 -1
  102. package/.next/server/app/api/ide/openclaw/restore/route_client-reference-manifest.js +2 -1
  103. package/.next/server/app/api/ide/openclaw/save/route/build-manifest.json +1 -3
  104. package/.next/server/app/api/ide/openclaw/save/route.js +4 -4
  105. package/.next/server/app/api/ide/openclaw/save/route.js.nft.json +1 -1
  106. package/.next/server/app/api/ide/openclaw/save/route_client-reference-manifest.js +2 -1
  107. package/.next/server/app/api/ide/openclaw/status/route/build-manifest.json +1 -3
  108. package/.next/server/app/api/ide/openclaw/status/route.js +4 -4
  109. package/.next/server/app/api/ide/openclaw/status/route.js.nft.json +1 -1
  110. package/.next/server/app/api/ide/openclaw/status/route_client-reference-manifest.js +2 -1
  111. package/.next/server/app/api/ide/openclaw/test/route/build-manifest.json +1 -3
  112. package/.next/server/app/api/ide/openclaw/test/route.js +3 -3
  113. package/.next/server/app/api/ide/openclaw/test/route.js.nft.json +1 -1
  114. package/.next/server/app/api/ide/openclaw/test/route_client-reference-manifest.js +2 -1
  115. package/.next/server/app/api/ide/opencode/apply/route/build-manifest.json +1 -3
  116. package/.next/server/app/api/ide/opencode/apply/route.js +4 -4
  117. package/.next/server/app/api/ide/opencode/apply/route.js.nft.json +1 -1
  118. package/.next/server/app/api/ide/opencode/apply/route_client-reference-manifest.js +2 -1
  119. package/.next/server/app/api/ide/opencode/available-models/route/build-manifest.json +1 -3
  120. package/.next/server/app/api/ide/opencode/available-models/route.js +4 -4
  121. package/.next/server/app/api/ide/opencode/available-models/route.js.nft.json +1 -1
  122. package/.next/server/app/api/ide/opencode/available-models/route_client-reference-manifest.js +2 -1
  123. package/.next/server/app/api/ide/opencode/preview/route/build-manifest.json +1 -3
  124. package/.next/server/app/api/ide/opencode/preview/route.js +4 -4
  125. package/.next/server/app/api/ide/opencode/preview/route.js.nft.json +1 -1
  126. package/.next/server/app/api/ide/opencode/preview/route_client-reference-manifest.js +2 -1
  127. package/.next/server/app/api/ide/opencode/restore/route/build-manifest.json +1 -3
  128. package/.next/server/app/api/ide/opencode/restore/route.js +3 -3
  129. package/.next/server/app/api/ide/opencode/restore/route.js.nft.json +1 -1
  130. package/.next/server/app/api/ide/opencode/restore/route_client-reference-manifest.js +2 -1
  131. package/.next/server/app/api/ide/opencode/save/route/build-manifest.json +1 -3
  132. package/.next/server/app/api/ide/opencode/save/route.js +4 -4
  133. package/.next/server/app/api/ide/opencode/save/route.js.nft.json +1 -1
  134. package/.next/server/app/api/ide/opencode/save/route_client-reference-manifest.js +2 -1
  135. package/.next/server/app/api/ide/opencode/status/route/build-manifest.json +1 -3
  136. package/.next/server/app/api/ide/opencode/status/route.js +4 -4
  137. package/.next/server/app/api/ide/opencode/status/route.js.nft.json +1 -1
  138. package/.next/server/app/api/ide/opencode/status/route_client-reference-manifest.js +2 -1
  139. package/.next/server/app/api/ide/opencode/test/route/build-manifest.json +1 -3
  140. package/.next/server/app/api/ide/opencode/test/route.js +3 -3
  141. package/.next/server/app/api/ide/opencode/test/route.js.nft.json +1 -1
  142. package/.next/server/app/api/ide/opencode/test/route_client-reference-manifest.js +2 -1
  143. package/.next/server/app/api/logs/route/build-manifest.json +1 -3
  144. package/.next/server/app/api/logs/route.js +4 -4
  145. package/.next/server/app/api/logs/route.js.nft.json +1 -1
  146. package/.next/server/app/api/logs/route_client-reference-manifest.js +2 -1
  147. package/.next/server/app/api/models/route/build-manifest.json +1 -3
  148. package/.next/server/app/api/models/route.js +5 -5
  149. package/.next/server/app/api/models/route.js.nft.json +1 -1
  150. package/.next/server/app/api/models/route_client-reference-manifest.js +2 -1
  151. package/.next/server/app/api/providers/route/build-manifest.json +1 -3
  152. package/.next/server/app/api/providers/route.js +5 -5
  153. package/.next/server/app/api/providers/route.js.nft.json +1 -1
  154. package/.next/server/app/api/providers/route_client-reference-manifest.js +2 -1
  155. package/.next/server/app/api/providers/test/route/build-manifest.json +1 -3
  156. package/.next/server/app/api/providers/test/route.js +5 -5
  157. package/.next/server/app/api/providers/test/route.js.nft.json +1 -1
  158. package/.next/server/app/api/providers/test/route_client-reference-manifest.js +2 -1
  159. package/.next/server/app/api/service/force-stop/route/build-manifest.json +1 -3
  160. package/.next/server/app/api/service/force-stop/route.js +4 -4
  161. package/.next/server/app/api/service/force-stop/route.js.nft.json +1 -1
  162. package/.next/server/app/api/service/force-stop/route_client-reference-manifest.js +2 -1
  163. package/.next/server/app/api/service/start/route/build-manifest.json +1 -3
  164. package/.next/server/app/api/service/start/route.js +4 -4
  165. package/.next/server/app/api/service/start/route.js.nft.json +1 -1
  166. package/.next/server/app/api/service/start/route_client-reference-manifest.js +2 -1
  167. package/.next/server/app/api/service/status/route/build-manifest.json +1 -3
  168. package/.next/server/app/api/service/status/route.js +4 -4
  169. package/.next/server/app/api/service/status/route.js.nft.json +1 -1
  170. package/.next/server/app/api/service/status/route_client-reference-manifest.js +2 -1
  171. package/.next/server/app/api/service/stop/route/build-manifest.json +1 -3
  172. package/.next/server/app/api/service/stop/route.js +4 -4
  173. package/.next/server/app/api/service/stop/route.js.nft.json +1 -1
  174. package/.next/server/app/api/service/stop/route_client-reference-manifest.js +2 -1
  175. package/.next/server/app/api/tokenizer/history/route/app-paths-manifest.json +3 -0
  176. package/.next/server/app/api/tokenizer/history/route/build-manifest.json +9 -0
  177. package/.next/server/app/api/tokenizer/history/route/server-reference-manifest.json +4 -0
  178. package/.next/server/app/api/tokenizer/history/route.js +7 -0
  179. package/.next/server/app/api/tokenizer/history/route.js.map +5 -0
  180. package/.next/server/app/api/tokenizer/history/route.js.nft.json +1 -0
  181. package/.next/server/app/api/tokenizer/history/route_client-reference-manifest.js +3 -0
  182. package/.next/server/app/api/tokenizer/test/route/app-paths-manifest.json +3 -0
  183. package/.next/server/app/api/tokenizer/test/route/build-manifest.json +9 -0
  184. package/.next/server/app/api/tokenizer/test/route/server-reference-manifest.json +4 -0
  185. package/.next/server/app/api/tokenizer/test/route.js +8 -0
  186. package/.next/server/app/api/tokenizer/test/route.js.map +5 -0
  187. package/.next/server/app/api/tokenizer/test/route.js.nft.json +1 -0
  188. package/.next/server/app/api/tokenizer/test/route_client-reference-manifest.js +3 -0
  189. package/.next/server/app/ide/page/build-manifest.json +5 -5
  190. package/.next/server/app/ide/page.js +12 -14
  191. package/.next/server/app/ide/page.js.nft.json +1 -1
  192. package/.next/server/app/ide/page_client-reference-manifest.js +2 -1
  193. package/.next/server/app/ide.html +1 -1
  194. package/.next/server/app/ide.rsc +15 -13
  195. package/.next/server/app/ide.segments/_full.segment.rsc +15 -13
  196. package/.next/server/app/ide.segments/_head.segment.rsc +3 -3
  197. package/.next/server/app/ide.segments/_index.segment.rsc +5 -5
  198. package/.next/server/app/ide.segments/_tree.segment.rsc +2 -2
  199. package/.next/server/app/ide.segments/ide/__PAGE__.segment.rsc +4 -4
  200. package/.next/server/app/ide.segments/ide.segment.rsc +4 -3
  201. package/.next/server/app/index.html +1 -1
  202. package/.next/server/app/index.rsc +11 -11
  203. package/.next/server/app/index.segments/__PAGE__.segment.rsc +4 -4
  204. package/.next/server/app/index.segments/_full.segment.rsc +11 -11
  205. package/.next/server/app/index.segments/_head.segment.rsc +3 -3
  206. package/.next/server/app/index.segments/_index.segment.rsc +5 -5
  207. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  208. package/.next/server/app/logs/page/build-manifest.json +5 -5
  209. package/.next/server/app/logs/page.js +12 -14
  210. package/.next/server/app/logs/page.js.nft.json +1 -1
  211. package/.next/server/app/logs/page_client-reference-manifest.js +2 -1
  212. package/.next/server/app/logs.html +1 -1
  213. package/.next/server/app/logs.rsc +15 -13
  214. package/.next/server/app/logs.segments/_full.segment.rsc +15 -13
  215. package/.next/server/app/logs.segments/_head.segment.rsc +3 -3
  216. package/.next/server/app/logs.segments/_index.segment.rsc +5 -5
  217. package/.next/server/app/logs.segments/_tree.segment.rsc +2 -2
  218. package/.next/server/app/logs.segments/logs/__PAGE__.segment.rsc +4 -4
  219. package/.next/server/app/logs.segments/logs.segment.rsc +4 -3
  220. package/.next/server/app/models/page/build-manifest.json +5 -5
  221. package/.next/server/app/models/page.js +12 -14
  222. package/.next/server/app/models/page.js.nft.json +1 -1
  223. package/.next/server/app/models/page_client-reference-manifest.js +2 -1
  224. package/.next/server/app/models.html +1 -1
  225. package/.next/server/app/models.rsc +15 -13
  226. package/.next/server/app/models.segments/_full.segment.rsc +15 -13
  227. package/.next/server/app/models.segments/_head.segment.rsc +3 -3
  228. package/.next/server/app/models.segments/_index.segment.rsc +5 -5
  229. package/.next/server/app/models.segments/_tree.segment.rsc +2 -2
  230. package/.next/server/app/models.segments/models/__PAGE__.segment.rsc +4 -4
  231. package/.next/server/app/models.segments/models.segment.rsc +4 -3
  232. package/.next/server/app/page/build-manifest.json +5 -5
  233. package/.next/server/app/page.js +12 -14
  234. package/.next/server/app/page.js.nft.json +1 -1
  235. package/.next/server/app/page_client-reference-manifest.js +2 -1
  236. package/.next/server/app/providers/page/build-manifest.json +5 -5
  237. package/.next/server/app/providers/page.js +12 -14
  238. package/.next/server/app/providers/page.js.nft.json +1 -1
  239. package/.next/server/app/providers/page_client-reference-manifest.js +2 -1
  240. package/.next/server/app/providers.html +1 -1
  241. package/.next/server/app/providers.rsc +15 -13
  242. package/.next/server/app/providers.segments/_full.segment.rsc +15 -13
  243. package/.next/server/app/providers.segments/_head.segment.rsc +3 -3
  244. package/.next/server/app/providers.segments/_index.segment.rsc +5 -5
  245. package/.next/server/app/providers.segments/_tree.segment.rsc +2 -2
  246. package/.next/server/app/providers.segments/providers/__PAGE__.segment.rsc +4 -4
  247. package/.next/server/app/providers.segments/providers.segment.rsc +4 -3
  248. package/.next/server/app/tokenizer/page/app-paths-manifest.json +3 -0
  249. package/.next/server/app/tokenizer/page/build-manifest.json +16 -0
  250. package/.next/server/app/tokenizer/page/next-font-manifest.json +6 -0
  251. package/.next/server/app/tokenizer/page/react-loadable-manifest.json +1 -0
  252. package/.next/server/app/tokenizer/page/server-reference-manifest.json +4 -0
  253. package/.next/server/app/tokenizer/page.js +13 -0
  254. package/.next/server/app/tokenizer/page.js.map +5 -0
  255. package/.next/server/app/tokenizer/page.js.nft.json +1 -0
  256. package/.next/server/app/tokenizer/page_client-reference-manifest.js +3 -0
  257. package/.next/server/app/tokenizer.html +1 -0
  258. package/.next/server/app/tokenizer.meta +15 -0
  259. package/.next/server/app/tokenizer.rsc +20 -0
  260. package/.next/server/app/tokenizer.segments/_full.segment.rsc +20 -0
  261. package/.next/server/app/tokenizer.segments/_head.segment.rsc +5 -0
  262. package/.next/server/app/tokenizer.segments/_index.segment.rsc +6 -0
  263. package/.next/server/app/tokenizer.segments/_tree.segment.rsc +2 -0
  264. package/.next/server/app/tokenizer.segments/tokenizer/__PAGE__.segment.rsc +9 -0
  265. package/.next/server/app/tokenizer.segments/tokenizer.segment.rsc +5 -0
  266. package/.next/server/app-paths-manifest.json +4 -1
  267. package/.next/server/chunks/0zjb_server_app_api_ide_openclaw_available-models_route_actions_0.gjr6a.js +3 -0
  268. package/.next/server/chunks/0zjb_server_app_api_ide_opencode_available-models_route_actions_0poyhyk.js +3 -0
  269. package/.next/server/chunks/[root-of-the-server]__0-_5z3v._.js +3 -0
  270. package/.next/server/chunks/[root-of-the-server]__0-_5z3v._.js.map +1 -0
  271. package/.next/server/chunks/[root-of-the-server]__012ucp~._.js +3 -0
  272. package/.next/server/chunks/[root-of-the-server]__012ucp~._.js.map +1 -0
  273. package/.next/server/chunks/[root-of-the-server]__01atdgx._.js +3 -0
  274. package/.next/server/chunks/[root-of-the-server]__01atdgx._.js.map +1 -0
  275. package/.next/server/chunks/[root-of-the-server]__01~ft76._.js +3 -0
  276. package/.next/server/chunks/[root-of-the-server]__01~ft76._.js.map +1 -0
  277. package/.next/server/chunks/[root-of-the-server]__04sfkei._.js +3 -0
  278. package/.next/server/chunks/[root-of-the-server]__04sfkei._.js.map +1 -0
  279. package/.next/server/chunks/[root-of-the-server]__065r.wp._.js +3 -0
  280. package/.next/server/chunks/[root-of-the-server]__065r.wp._.js.map +1 -0
  281. package/.next/server/chunks/[root-of-the-server]__07pm7px._.js +3 -0
  282. package/.next/server/chunks/[root-of-the-server]__07pm7px._.js.map +1 -0
  283. package/.next/server/chunks/[root-of-the-server]__07vosna._.js +3 -0
  284. package/.next/server/chunks/[root-of-the-server]__07vosna._.js.map +1 -0
  285. package/.next/server/chunks/[root-of-the-server]__083j1v0._.js +3 -0
  286. package/.next/server/chunks/[root-of-the-server]__083j1v0._.js.map +1 -0
  287. package/.next/server/chunks/[root-of-the-server]__08_ekvs._.js +3 -0
  288. package/.next/server/chunks/[root-of-the-server]__08_ekvs._.js.map +1 -0
  289. package/.next/server/chunks/[root-of-the-server]__08ftz8n._.js +3 -0
  290. package/.next/server/chunks/[root-of-the-server]__08ftz8n._.js.map +1 -0
  291. package/.next/server/chunks/[root-of-the-server]__08oq8ma._.js +3 -0
  292. package/.next/server/chunks/[root-of-the-server]__08oq8ma._.js.map +1 -0
  293. package/.next/server/chunks/[root-of-the-server]__099b1my._.js +3 -0
  294. package/.next/server/chunks/[root-of-the-server]__099b1my._.js.map +1 -0
  295. package/.next/server/chunks/[root-of-the-server]__0aw-~h8._.js +3 -0
  296. package/.next/server/chunks/[root-of-the-server]__0aw-~h8._.js.map +1 -0
  297. package/.next/server/chunks/[root-of-the-server]__0dj43ut._.js +3 -0
  298. package/.next/server/chunks/[root-of-the-server]__0dj43ut._.js.map +1 -0
  299. package/.next/server/chunks/[root-of-the-server]__0efv_yh._.js +3 -0
  300. package/.next/server/chunks/[root-of-the-server]__0efv_yh._.js.map +1 -0
  301. package/.next/server/chunks/[root-of-the-server]__0el37wu._.js +7 -0
  302. package/.next/server/chunks/[root-of-the-server]__0el37wu._.js.map +1 -0
  303. package/.next/server/chunks/[root-of-the-server]__0g.1w-q._.js +3 -0
  304. package/.next/server/chunks/[root-of-the-server]__0g.1w-q._.js.map +1 -0
  305. package/.next/server/chunks/[root-of-the-server]__0im~-m7._.js +3 -0
  306. package/.next/server/chunks/[root-of-the-server]__0im~-m7._.js.map +1 -0
  307. package/.next/server/chunks/[root-of-the-server]__0jf1q27._.js +3 -0
  308. package/.next/server/chunks/[root-of-the-server]__0jf1q27._.js.map +1 -0
  309. package/.next/server/chunks/[root-of-the-server]__0kldv62._.js +3 -0
  310. package/.next/server/chunks/[root-of-the-server]__0kldv62._.js.map +1 -0
  311. package/.next/server/chunks/[root-of-the-server]__0lr16iw._.js +3 -0
  312. package/.next/server/chunks/[root-of-the-server]__0lr16iw._.js.map +1 -0
  313. package/.next/server/chunks/[root-of-the-server]__0m62mql._.js +3 -0
  314. package/.next/server/chunks/[root-of-the-server]__0m62mql._.js.map +1 -0
  315. package/.next/server/chunks/[root-of-the-server]__0qp1t_m._.js +3 -0
  316. package/.next/server/chunks/[root-of-the-server]__0qp1t_m._.js.map +1 -0
  317. package/.next/server/chunks/[root-of-the-server]__0qz-m.u._.js +3 -0
  318. package/.next/server/chunks/[root-of-the-server]__0qz-m.u._.js.map +1 -0
  319. package/.next/server/chunks/[root-of-the-server]__0r235yd._.js +3 -0
  320. package/.next/server/chunks/[root-of-the-server]__0r235yd._.js.map +1 -0
  321. package/.next/server/chunks/[root-of-the-server]__0rjkw2y._.js +3 -0
  322. package/.next/server/chunks/[root-of-the-server]__0rjkw2y._.js.map +1 -0
  323. package/.next/server/chunks/[root-of-the-server]__0uaqs.r._.js +3 -0
  324. package/.next/server/chunks/[root-of-the-server]__0uaqs.r._.js.map +1 -0
  325. package/.next/server/chunks/[root-of-the-server]__0vktxod._.js +3 -0
  326. package/.next/server/chunks/[root-of-the-server]__0vktxod._.js.map +1 -0
  327. package/.next/server/chunks/[root-of-the-server]__0vlh9um._.js +3 -0
  328. package/.next/server/chunks/[root-of-the-server]__0vlh9um._.js.map +1 -0
  329. package/.next/server/chunks/{[root-of-the-server]__c1b4b601._.js → [root-of-the-server]__0xb5i_t._.js} +21 -9
  330. package/.next/server/chunks/[root-of-the-server]__0xb5i_t._.js.map +1 -0
  331. package/.next/server/chunks/[root-of-the-server]__0xsal5d._.js +3 -0
  332. package/.next/server/chunks/[root-of-the-server]__0xsal5d._.js.map +1 -0
  333. package/.next/server/chunks/[root-of-the-server]__0yo.c6n._.js +3 -0
  334. package/.next/server/chunks/[root-of-the-server]__0yo.c6n._.js.map +1 -0
  335. package/.next/server/chunks/[root-of-the-server]__0yz0y4l._.js +13 -0
  336. package/.next/server/chunks/[root-of-the-server]__0yz0y4l._.js.map +1 -0
  337. package/.next/server/chunks/{[root-of-the-server]__e7623a6c._.js → [root-of-the-server]__11srlmi._.js} +2 -2
  338. package/.next/server/chunks/{[root-of-the-server]__e7623a6c._.js.map → [root-of-the-server]__11srlmi._.js.map} +1 -1
  339. package/.next/server/chunks/[root-of-the-server]__12d44rt._.js +3 -0
  340. package/.next/server/chunks/[root-of-the-server]__12d44rt._.js.map +1 -0
  341. package/.next/server/chunks/[turbopack]_runtime.js +168 -60
  342. package/.next/server/chunks/[turbopack]_runtime.js.map +6 -5
  343. package/.next/server/chunks/_0v0oe6c._.js +3 -0
  344. package/.next/server/chunks/{_b48847f5._.js.map → _0v0oe6c._.js.map} +1 -1
  345. package/.next/server/chunks/{_next-internal_server_app_api_config_route_actions_308a9f33.js → _next-internal_server_app_api_config_route_actions_08dm.dx.js} +1 -1
  346. package/.next/server/chunks/{_next-internal_server_app_api_gateway_[___path]_route_actions_835b2379.js → _next-internal_server_app_api_gateway_[___path]_route_actions_0mmqyo7.js} +1 -1
  347. package/.next/server/chunks/{_next-internal_server_app_api_gateway_models_route_actions_302c9983.js → _next-internal_server_app_api_gateway_models_route_actions_08b214z.js} +1 -1
  348. package/.next/server/chunks/{_next-internal_server_app_api_gateway_route_actions_e5e7405d.js → _next-internal_server_app_api_gateway_route_actions_0.jzdw1.js} +1 -1
  349. package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_apply_route_actions_5056516c.js → _next-internal_server_app_api_ide_claude_apply_route_actions_0dw2_pf.js} +1 -1
  350. package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_available-models_route_actions_94d710a0.js → _next-internal_server_app_api_ide_claude_available-models_route_actions_0pmwy75.js} +1 -1
  351. package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_restore_route_actions_f37acc94.js → _next-internal_server_app_api_ide_claude_restore_route_actions_11x77hl.js} +1 -1
  352. package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_save_route_actions_407c55f5.js → _next-internal_server_app_api_ide_claude_save_route_actions_0b35ro_.js} +1 -1
  353. package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_status_route_actions_5ac73db8.js → _next-internal_server_app_api_ide_claude_status_route_actions_0fnw-w7.js} +1 -1
  354. package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_test_route_actions_70587902.js → _next-internal_server_app_api_ide_claude_test_route_actions_0jc1czy.js} +1 -1
  355. package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_apply_route_actions_2cb9e4b4.js → _next-internal_server_app_api_ide_openclaw_apply_route_actions_07re971.js} +1 -1
  356. package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_preview_route_actions_9814a8e4.js → _next-internal_server_app_api_ide_openclaw_preview_route_actions_0q53p05.js} +1 -1
  357. package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_restore_route_actions_10ad8f9d.js → _next-internal_server_app_api_ide_openclaw_restore_route_actions_02yog9-.js} +1 -1
  358. package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_save_route_actions_044ad081.js → _next-internal_server_app_api_ide_openclaw_save_route_actions_00tjxsz.js} +1 -1
  359. package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_status_route_actions_ed9786d2.js → _next-internal_server_app_api_ide_openclaw_status_route_actions_10wsun4.js} +1 -1
  360. package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_test_route_actions_ce2cb808.js → _next-internal_server_app_api_ide_openclaw_test_route_actions_0zgwyon.js} +1 -1
  361. package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_apply_route_actions_6c422244.js → _next-internal_server_app_api_ide_opencode_apply_route_actions_0in-w.g.js} +1 -1
  362. package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_preview_route_actions_256c82e0.js → _next-internal_server_app_api_ide_opencode_preview_route_actions_06h6.w~.js} +1 -1
  363. package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_restore_route_actions_371993d3.js → _next-internal_server_app_api_ide_opencode_restore_route_actions_09ipt-l.js} +1 -1
  364. package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_save_route_actions_6e4c9c41.js → _next-internal_server_app_api_ide_opencode_save_route_actions_0i-~x79.js} +1 -1
  365. package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_status_route_actions_498ad77b.js → _next-internal_server_app_api_ide_opencode_status_route_actions_0cpf6rv.js} +1 -1
  366. package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_test_route_actions_c71be510.js → _next-internal_server_app_api_ide_opencode_test_route_actions_0y8aq8h.js} +1 -1
  367. package/.next/server/chunks/{_next-internal_server_app_api_logs_route_actions_30a87f47.js → _next-internal_server_app_api_logs_route_actions_08ef2j7.js} +1 -1
  368. package/.next/server/chunks/{_next-internal_server_app_api_models_route_actions_b6abdc83.js → _next-internal_server_app_api_models_route_actions_0vfccm4.js} +1 -1
  369. package/.next/server/chunks/{_next-internal_server_app_api_providers_route_actions_5388b373.js → _next-internal_server_app_api_providers_route_actions_0ee1p_m.js} +1 -1
  370. package/.next/server/chunks/{_next-internal_server_app_api_providers_test_route_actions_b97ab15a.js → _next-internal_server_app_api_providers_test_route_actions_0vyo652.js} +1 -1
  371. package/.next/server/chunks/{_next-internal_server_app_api_service_force-stop_route_actions_95eba80b.js → _next-internal_server_app_api_service_force-stop_route_actions_0pu9xrq.js} +1 -1
  372. package/.next/server/chunks/{_next-internal_server_app_api_service_start_route_actions_d50efb77.js → _next-internal_server_app_api_service_start_route_actions_0_o53a2.js} +1 -1
  373. package/.next/server/chunks/{_next-internal_server_app_api_service_status_route_actions_30149042.js → _next-internal_server_app_api_service_status_route_actions_08ag8v4.js} +1 -1
  374. package/.next/server/chunks/{_next-internal_server_app_api_service_stop_route_actions_19443941.js → _next-internal_server_app_api_service_stop_route_actions_04dp83p.js} +1 -1
  375. package/.next/server/chunks/_next-internal_server_app_api_tokenizer_history_route_actions_09~nqtd.js +3 -0
  376. package/.next/server/chunks/_next-internal_server_app_api_tokenizer_test_route_actions_0t2swp-.js +3 -0
  377. package/.next/server/chunks/{node_modules_next_dist_esm_build_templates_app-route_4be65264.js → node_modules_next_dist_esm_build_templates_app-route_0d1n5~u.js} +6 -6
  378. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_0d1n5~u.js.map +1 -0
  379. package/.next/server/chunks/ssr/[root-of-the-server]__0.zquoa._.js +3 -0
  380. package/.next/server/chunks/ssr/[root-of-the-server]__0.zquoa._.js.map +1 -0
  381. package/.next/server/chunks/ssr/[root-of-the-server]__01dqyhh._.js +3 -0
  382. package/.next/server/chunks/ssr/[root-of-the-server]__01dqyhh._.js.map +1 -0
  383. package/.next/server/chunks/ssr/[root-of-the-server]__04qwc64._.js +3 -0
  384. package/.next/server/chunks/ssr/[root-of-the-server]__04qwc64._.js.map +1 -0
  385. package/.next/server/chunks/ssr/[root-of-the-server]__06r_ug4._.js +3 -0
  386. package/.next/server/chunks/ssr/[root-of-the-server]__06r_ug4._.js.map +1 -0
  387. package/.next/server/chunks/ssr/{[root-of-the-server]__f92001a5._.js → [root-of-the-server]__0814l01._.js} +2 -2
  388. package/.next/server/chunks/ssr/[root-of-the-server]__0814l01._.js.map +1 -0
  389. package/.next/server/chunks/ssr/[root-of-the-server]__0gb1hlj._.js +3 -0
  390. package/.next/server/chunks/ssr/[root-of-the-server]__0gb1hlj._.js.map +1 -0
  391. package/.next/server/chunks/ssr/[root-of-the-server]__0p8tmu2._.js +3 -0
  392. package/.next/server/chunks/ssr/[root-of-the-server]__0p8tmu2._.js.map +1 -0
  393. package/.next/server/chunks/ssr/[root-of-the-server]__0rf3.7n._.js +3 -0
  394. package/.next/server/chunks/ssr/[root-of-the-server]__0rf3.7n._.js.map +1 -0
  395. package/.next/server/chunks/ssr/[root-of-the-server]__0~6rwng._.js +33 -0
  396. package/.next/server/chunks/ssr/[root-of-the-server]__0~6rwng._.js.map +1 -0
  397. package/.next/server/chunks/ssr/[root-of-the-server]__10xgshr._.js +33 -0
  398. package/.next/server/chunks/ssr/[root-of-the-server]__10xgshr._.js.map +1 -0
  399. package/.next/server/chunks/ssr/[root-of-the-server]__11i~7lq._.js +3 -0
  400. package/.next/server/chunks/ssr/[root-of-the-server]__11i~7lq._.js.map +1 -0
  401. package/.next/server/chunks/ssr/[turbopack]_runtime.js +168 -60
  402. package/.next/server/chunks/ssr/[turbopack]_runtime.js.map +6 -5
  403. package/.next/server/chunks/ssr/_0k83omg._.js +6 -0
  404. package/.next/server/chunks/ssr/_0k83omg._.js.map +1 -0
  405. package/.next/server/chunks/ssr/_0yyi5po._.js +3 -0
  406. package/.next/server/chunks/ssr/_0yyi5po._.js.map +1 -0
  407. package/.next/server/chunks/ssr/{_next-internal_server_app__global-error_page_actions_75761787.js → _next-internal_server_app__global-error_page_actions_0k77kol.js} +1 -1
  408. package/.next/server/chunks/ssr/{_next-internal_server_app__not-found_page_actions_554ec2bf.js → _next-internal_server_app__not-found_page_actions_0eq97pa.js} +1 -1
  409. package/.next/server/chunks/ssr/{_next-internal_server_app_ide_page_actions_d521d6ae.js → _next-internal_server_app_ide_page_actions_0_opd4~.js} +1 -1
  410. package/.next/server/chunks/ssr/{_next-internal_server_app_logs_page_actions_a1c69041.js → _next-internal_server_app_logs_page_actions_0rvsl~d.js} +1 -1
  411. package/.next/server/chunks/ssr/{_next-internal_server_app_models_page_actions_543cf22f.js → _next-internal_server_app_models_page_actions_0eiz7f7.js} +1 -1
  412. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_09-gtaw.js +3 -0
  413. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_09-gtaw.js.map +1 -0
  414. package/.next/server/chunks/ssr/{_next-internal_server_app_providers_page_actions_c75f6cb3.js → _next-internal_server_app_providers_page_actions_0ya36nw.js} +1 -1
  415. package/.next/server/chunks/ssr/_next-internal_server_app_providers_page_actions_0ya36nw.js.map +1 -0
  416. package/.next/server/chunks/ssr/_next-internal_server_app_tokenizer_page_actions_0imc_ya.js +3 -0
  417. package/.next/server/chunks/ssr/_next-internal_server_app_tokenizer_page_actions_0imc_ya.js.map +1 -0
  418. package/.next/server/chunks/ssr/node_modules_09w7yel._.js +33 -0
  419. package/.next/server/chunks/ssr/node_modules_09w7yel._.js.map +1 -0
  420. package/.next/server/chunks/ssr/node_modules_next_dist_06hehg4._.js +19 -0
  421. package/.next/server/chunks/ssr/node_modules_next_dist_06hehg4._.js.map +1 -0
  422. package/.next/server/chunks/ssr/node_modules_next_dist_0e1izl_._.js +6 -0
  423. package/.next/server/chunks/ssr/node_modules_next_dist_0e1izl_._.js.map +1 -0
  424. package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_9774470f._.js → node_modules_next_dist_client_components_0inhx6q._.js} +2 -2
  425. package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_builtin_forbidden_45780354.js → node_modules_next_dist_client_components_builtin_forbidden_0ghu-f7.js} +2 -2
  426. package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_builtin_global-error_ece394eb.js → node_modules_next_dist_client_components_builtin_global-error_0lgvd_..js} +2 -2
  427. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_0lgvd_..js.map +1 -0
  428. package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_builtin_unauthorized_15817684.js → node_modules_next_dist_client_components_builtin_unauthorized_0cjv-23.js} +2 -2
  429. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_05u.ff5.js +4 -0
  430. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_05u.ff5.js.map +1 -0
  431. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_06a5k-w.js +4 -0
  432. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_06a5k-w.js.map +1 -0
  433. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0_rrdx6.js +4 -0
  434. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0_rrdx6.js.map +1 -0
  435. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0a7b~p7.js +4 -0
  436. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0a7b~p7.js.map +1 -0
  437. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0bj8dkg.js +4 -0
  438. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0bj8dkg.js.map +1 -0
  439. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0cvrgh7.js +4 -0
  440. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0cvrgh7.js.map +1 -0
  441. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0nkcfme.js +4 -0
  442. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0nkcfme.js.map +1 -0
  443. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0rc3ul_.js +4 -0
  444. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_0rc3ul_.js.map +1 -0
  445. package/.next/server/chunks/ssr/src_app_components_ConfirmDialog_tsx_0mm3plr._.js +3 -0
  446. package/.next/server/chunks/ssr/src_app_components_ConfirmDialog_tsx_0mm3plr._.js.map +1 -0
  447. package/.next/server/chunks/ssr/src_app_ide_page_tsx_0no40dj._.js +3 -0
  448. package/.next/server/chunks/ssr/{src_app_ide_page_tsx_8962793b._.js.map → src_app_ide_page_tsx_0no40dj._.js.map} +1 -1
  449. package/.next/server/chunks/ssr/src_app_logs_page_tsx_0l8mmxe._.js +3 -0
  450. package/.next/server/chunks/ssr/{src_app_logs_page_tsx_7b7b7b83._.js.map → src_app_logs_page_tsx_0l8mmxe._.js.map} +1 -1
  451. package/.next/server/chunks/ssr/src_app_models_page_tsx_10vsbc1._.js +3 -0
  452. package/.next/server/chunks/ssr/{src_app_models_page_tsx_ed71d32e._.js.map → src_app_models_page_tsx_10vsbc1._.js.map} +1 -1
  453. package/.next/server/chunks/ssr/src_app_page_tsx_0ss2.w7._.js +3 -0
  454. package/.next/server/chunks/ssr/src_app_page_tsx_0ss2.w7._.js.map +1 -0
  455. package/.next/server/chunks/ssr/src_app_providers_page_tsx_10ipz~8._.js +3 -0
  456. package/.next/server/chunks/ssr/{src_app_providers_page_tsx_eb8b5137._.js.map → src_app_providers_page_tsx_10ipz~8._.js.map} +1 -1
  457. package/.next/server/chunks/ssr/src_app_tokenizer_page_tsx_0eqhpbs._.js +3 -0
  458. package/.next/server/chunks/ssr/src_app_tokenizer_page_tsx_0eqhpbs._.js.map +1 -0
  459. package/.next/server/functions-config-manifest.json +3 -1
  460. package/.next/server/middleware-build-manifest.js +10 -10
  461. package/.next/server/pages/404.html +1 -1
  462. package/.next/server/pages/500.html +1 -2
  463. package/.next/server/prefetch-hints.json +1 -0
  464. package/.next/server/server-reference-manifest.js +1 -1
  465. package/.next/server/server-reference-manifest.json +1 -1
  466. package/.next/static/XHnu7Z1vWSrgmneps8rX4/_clientMiddlewareManifest.js +1 -0
  467. package/.next/static/chunks/01xlw8hd842-c.js +1 -0
  468. package/.next/static/chunks/0bzupvr5gt3k9.js +31 -0
  469. package/.next/static/chunks/0d3shmwh5_nmn.js +1 -0
  470. package/.next/static/chunks/0h7-_zr5_nt.5.js +1 -0
  471. package/.next/static/chunks/0mjx90nkvhsot.js +1 -0
  472. package/.next/static/chunks/0ntp1qkrtsgn0.js +1 -0
  473. package/.next/static/chunks/0tc5l6c1zalyc.css +1 -0
  474. package/.next/static/chunks/0v7.1nc4jyaet.js +1 -0
  475. package/.next/static/chunks/0vlwn301rv7dw.js +1 -0
  476. package/.next/static/chunks/0y3~cortx~or~.js +5 -0
  477. package/.next/static/chunks/0~c9fm3-3-f41.js +1 -0
  478. package/.next/static/chunks/11-7_fybhp2~y.js +1 -0
  479. package/.next/static/chunks/121-ofr4.6_5t.js +1 -0
  480. package/.next/static/chunks/16g.ca89g7fib.js +1 -0
  481. package/.next/static/chunks/turbopack-0griofc2i3wvs.js +1 -0
  482. package/.next/types/routes.d.ts +5 -2
  483. package/.next/types/validator.ts +27 -0
  484. package/CHANGELOG.md +15 -0
  485. package/README.md +6 -0
  486. package/dist/.next/dev/types/validator.js +12 -0
  487. package/dist/.next/types/validator.js +12 -0
  488. package/dist/package.json +3 -2
  489. package/dist/src/app/api/tokenizer/history/route.js +60 -0
  490. package/dist/src/app/api/tokenizer/test/route.js +97 -0
  491. package/dist/src/app/components/Nav.js +2 -1
  492. package/dist/src/app/tokenizer/page.js +318 -0
  493. package/dist/src/cli/index.js +3 -3
  494. package/dist/src/db/database.js +19 -21
  495. package/dist/src/db/queries.js +21 -0
  496. package/dist/src/server/tokenizer.js +215 -0
  497. package/package.json +3 -2
  498. package/src/app/api/tokenizer/history/route.ts +63 -0
  499. package/src/app/api/tokenizer/test/route.ts +151 -0
  500. package/src/app/components/Nav.tsx +2 -2
  501. package/src/app/tokenizer/page.tsx +813 -0
  502. package/src/cli/index.ts +4 -4
  503. package/src/db/database.ts +18 -25
  504. package/src/db/queries.ts +22 -0
  505. package/src/server/tokenizer.ts +285 -0
  506. package/.next/build/chunks/[root-of-the-server]__44695d76._.js.map +0 -11
  507. package/.next/build/chunks/[root-of-the-server]__6d51cb5d._.js.map +0 -8
  508. package/.next/server/chunks/[root-of-the-server]__001d5756._.js +0 -3
  509. package/.next/server/chunks/[root-of-the-server]__001d5756._.js.map +0 -1
  510. package/.next/server/chunks/[root-of-the-server]__05f8578b._.js +0 -3
  511. package/.next/server/chunks/[root-of-the-server]__05f8578b._.js.map +0 -1
  512. package/.next/server/chunks/[root-of-the-server]__1480f018._.js +0 -3
  513. package/.next/server/chunks/[root-of-the-server]__1480f018._.js.map +0 -1
  514. package/.next/server/chunks/[root-of-the-server]__1909f3aa._.js +0 -3
  515. package/.next/server/chunks/[root-of-the-server]__1909f3aa._.js.map +0 -1
  516. package/.next/server/chunks/[root-of-the-server]__1d4b7fc5._.js +0 -3
  517. package/.next/server/chunks/[root-of-the-server]__1d4b7fc5._.js.map +0 -1
  518. package/.next/server/chunks/[root-of-the-server]__33fec899._.js +0 -3
  519. package/.next/server/chunks/[root-of-the-server]__33fec899._.js.map +0 -1
  520. package/.next/server/chunks/[root-of-the-server]__372ef2bf._.js +0 -3
  521. package/.next/server/chunks/[root-of-the-server]__372ef2bf._.js.map +0 -1
  522. package/.next/server/chunks/[root-of-the-server]__3a204d25._.js +0 -3
  523. package/.next/server/chunks/[root-of-the-server]__3a204d25._.js.map +0 -1
  524. package/.next/server/chunks/[root-of-the-server]__3aaf963c._.js +0 -3
  525. package/.next/server/chunks/[root-of-the-server]__3aaf963c._.js.map +0 -1
  526. package/.next/server/chunks/[root-of-the-server]__43810962._.js +0 -3
  527. package/.next/server/chunks/[root-of-the-server]__43810962._.js.map +0 -1
  528. package/.next/server/chunks/[root-of-the-server]__4a8f9bc7._.js +0 -3
  529. package/.next/server/chunks/[root-of-the-server]__4a8f9bc7._.js.map +0 -1
  530. package/.next/server/chunks/[root-of-the-server]__55cd88b8._.js +0 -3
  531. package/.next/server/chunks/[root-of-the-server]__55cd88b8._.js.map +0 -1
  532. package/.next/server/chunks/[root-of-the-server]__59aacd30._.js +0 -21
  533. package/.next/server/chunks/[root-of-the-server]__59aacd30._.js.map +0 -1
  534. package/.next/server/chunks/[root-of-the-server]__5e8276bc._.js +0 -3
  535. package/.next/server/chunks/[root-of-the-server]__5e8276bc._.js.map +0 -1
  536. package/.next/server/chunks/[root-of-the-server]__64356cb2._.js +0 -3
  537. package/.next/server/chunks/[root-of-the-server]__64356cb2._.js.map +0 -1
  538. package/.next/server/chunks/[root-of-the-server]__6ce199d2._.js +0 -3
  539. package/.next/server/chunks/[root-of-the-server]__6ce199d2._.js.map +0 -1
  540. package/.next/server/chunks/[root-of-the-server]__760eaa16._.js +0 -3
  541. package/.next/server/chunks/[root-of-the-server]__760eaa16._.js.map +0 -1
  542. package/.next/server/chunks/[root-of-the-server]__772134c6._.js +0 -3
  543. package/.next/server/chunks/[root-of-the-server]__772134c6._.js.map +0 -1
  544. package/.next/server/chunks/[root-of-the-server]__7b77f523._.js +0 -3
  545. package/.next/server/chunks/[root-of-the-server]__7b77f523._.js.map +0 -1
  546. package/.next/server/chunks/[root-of-the-server]__7c298a19._.js +0 -3
  547. package/.next/server/chunks/[root-of-the-server]__7c298a19._.js.map +0 -1
  548. package/.next/server/chunks/[root-of-the-server]__85540228._.js +0 -3
  549. package/.next/server/chunks/[root-of-the-server]__85540228._.js.map +0 -1
  550. package/.next/server/chunks/[root-of-the-server]__94fe8d3c._.js +0 -3
  551. package/.next/server/chunks/[root-of-the-server]__94fe8d3c._.js.map +0 -1
  552. package/.next/server/chunks/[root-of-the-server]__97622908._.js +0 -3
  553. package/.next/server/chunks/[root-of-the-server]__97622908._.js.map +0 -1
  554. package/.next/server/chunks/[root-of-the-server]__a02e6618._.js +0 -3
  555. package/.next/server/chunks/[root-of-the-server]__a02e6618._.js.map +0 -1
  556. package/.next/server/chunks/[root-of-the-server]__a32a20a7._.js +0 -3
  557. package/.next/server/chunks/[root-of-the-server]__a32a20a7._.js.map +0 -1
  558. package/.next/server/chunks/[root-of-the-server]__a719d045._.js +0 -3
  559. package/.next/server/chunks/[root-of-the-server]__a719d045._.js.map +0 -1
  560. package/.next/server/chunks/[root-of-the-server]__af5b556a._.js +0 -3
  561. package/.next/server/chunks/[root-of-the-server]__af5b556a._.js.map +0 -1
  562. package/.next/server/chunks/[root-of-the-server]__c1b4b601._.js.map +0 -1
  563. package/.next/server/chunks/[root-of-the-server]__cafe113e._.js +0 -3
  564. package/.next/server/chunks/[root-of-the-server]__cafe113e._.js.map +0 -1
  565. package/.next/server/chunks/[root-of-the-server]__ccfc7f1d._.js +0 -3
  566. package/.next/server/chunks/[root-of-the-server]__ccfc7f1d._.js.map +0 -1
  567. package/.next/server/chunks/[root-of-the-server]__dc8b0bed._.js +0 -3
  568. package/.next/server/chunks/[root-of-the-server]__dc8b0bed._.js.map +0 -1
  569. package/.next/server/chunks/[root-of-the-server]__f0461b8d._.js +0 -3
  570. package/.next/server/chunks/[root-of-the-server]__f0461b8d._.js.map +0 -1
  571. package/.next/server/chunks/[root-of-the-server]__f8949f88._.js +0 -3
  572. package/.next/server/chunks/[root-of-the-server]__f8949f88._.js.map +0 -1
  573. package/.next/server/chunks/_b48847f5._.js +0 -3
  574. package/.next/server/chunks/ce889_server_app_api_ide_openclaw_available-models_route_actions_e568e70b.js +0 -3
  575. package/.next/server/chunks/ce889_server_app_api_ide_opencode_available-models_route_actions_95230db3.js +0 -3
  576. package/.next/server/chunks/node_modules_next_dist_esm_build_templates_app-route_4be65264.js.map +0 -1
  577. package/.next/server/chunks/ssr/[root-of-the-server]__083d944d._.js +0 -3
  578. package/.next/server/chunks/ssr/[root-of-the-server]__083d944d._.js.map +0 -1
  579. package/.next/server/chunks/ssr/[root-of-the-server]__15600e29._.js +0 -3
  580. package/.next/server/chunks/ssr/[root-of-the-server]__15600e29._.js.map +0 -1
  581. package/.next/server/chunks/ssr/[root-of-the-server]__1836f866._.js +0 -3
  582. package/.next/server/chunks/ssr/[root-of-the-server]__1836f866._.js.map +0 -1
  583. package/.next/server/chunks/ssr/[root-of-the-server]__256a03fe._.js +0 -3
  584. package/.next/server/chunks/ssr/[root-of-the-server]__256a03fe._.js.map +0 -1
  585. package/.next/server/chunks/ssr/[root-of-the-server]__31fde618._.js +0 -3
  586. package/.next/server/chunks/ssr/[root-of-the-server]__31fde618._.js.map +0 -1
  587. package/.next/server/chunks/ssr/[root-of-the-server]__523c120c._.js +0 -3
  588. package/.next/server/chunks/ssr/[root-of-the-server]__523c120c._.js.map +0 -1
  589. package/.next/server/chunks/ssr/[root-of-the-server]__70a81394._.js +0 -3
  590. package/.next/server/chunks/ssr/[root-of-the-server]__70a81394._.js.map +0 -1
  591. package/.next/server/chunks/ssr/[root-of-the-server]__81937253._.js +0 -3
  592. package/.next/server/chunks/ssr/[root-of-the-server]__81937253._.js.map +0 -1
  593. package/.next/server/chunks/ssr/[root-of-the-server]__976ad963._.js +0 -3
  594. package/.next/server/chunks/ssr/[root-of-the-server]__976ad963._.js.map +0 -1
  595. package/.next/server/chunks/ssr/[root-of-the-server]__af2ad6aa._.js +0 -3
  596. package/.next/server/chunks/ssr/[root-of-the-server]__af2ad6aa._.js.map +0 -1
  597. package/.next/server/chunks/ssr/[root-of-the-server]__b9356576._.js +0 -4
  598. package/.next/server/chunks/ssr/[root-of-the-server]__b9356576._.js.map +0 -1
  599. package/.next/server/chunks/ssr/[root-of-the-server]__ccb6a4da._.js +0 -3
  600. package/.next/server/chunks/ssr/[root-of-the-server]__ccb6a4da._.js.map +0 -1
  601. package/.next/server/chunks/ssr/[root-of-the-server]__cfa2d991._.js +0 -3
  602. package/.next/server/chunks/ssr/[root-of-the-server]__cfa2d991._.js.map +0 -1
  603. package/.next/server/chunks/ssr/[root-of-the-server]__f437da88._.js +0 -3
  604. package/.next/server/chunks/ssr/[root-of-the-server]__f437da88._.js.map +0 -1
  605. package/.next/server/chunks/ssr/[root-of-the-server]__f92001a5._.js.map +0 -1
  606. package/.next/server/chunks/ssr/_06262cbd._.js +0 -4
  607. package/.next/server/chunks/ssr/_06262cbd._.js.map +0 -1
  608. package/.next/server/chunks/ssr/_0cd72da5._.js +0 -4
  609. package/.next/server/chunks/ssr/_0cd72da5._.js.map +0 -1
  610. package/.next/server/chunks/ssr/_4828a6d2._.js +0 -4
  611. package/.next/server/chunks/ssr/_4828a6d2._.js.map +0 -1
  612. package/.next/server/chunks/ssr/_69468f4c._.js +0 -3
  613. package/.next/server/chunks/ssr/_69468f4c._.js.map +0 -1
  614. package/.next/server/chunks/ssr/_93850476._.js +0 -6
  615. package/.next/server/chunks/ssr/_93850476._.js.map +0 -1
  616. package/.next/server/chunks/ssr/_c1309523._.js +0 -4
  617. package/.next/server/chunks/ssr/_c1309523._.js.map +0 -1
  618. package/.next/server/chunks/ssr/_f7d273e3._.js +0 -4
  619. package/.next/server/chunks/ssr/_f7d273e3._.js.map +0 -1
  620. package/.next/server/chunks/ssr/_next-internal_server_app_page_actions_39d4fc33.js +0 -3
  621. package/.next/server/chunks/ssr/node_modules_next_dist_08570d7f._.js +0 -4
  622. package/.next/server/chunks/ssr/node_modules_next_dist_08570d7f._.js.map +0 -1
  623. package/.next/server/chunks/ssr/node_modules_next_dist_174ae28d._.js +0 -10
  624. package/.next/server/chunks/ssr/node_modules_next_dist_174ae28d._.js.map +0 -1
  625. package/.next/server/chunks/ssr/node_modules_next_dist_27457240._.js +0 -6
  626. package/.next/server/chunks/ssr/node_modules_next_dist_27457240._.js.map +0 -1
  627. package/.next/server/chunks/ssr/node_modules_next_dist_4b63a0e1._.js +0 -3
  628. package/.next/server/chunks/ssr/node_modules_next_dist_4b63a0e1._.js.map +0 -1
  629. package/.next/server/chunks/ssr/node_modules_next_dist_client_components_builtin_global-error_ece394eb.js.map +0 -1
  630. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_65a7265e.js +0 -4
  631. package/.next/server/chunks/ssr/node_modules_next_dist_esm_build_templates_app-page_65a7265e.js.map +0 -1
  632. package/.next/server/chunks/ssr/node_modules_next_dist_f9713a08._.js +0 -3
  633. package/.next/server/chunks/ssr/node_modules_next_dist_f9713a08._.js.map +0 -1
  634. package/.next/server/chunks/ssr/src_app_ide_page_tsx_8962793b._.js +0 -3
  635. package/.next/server/chunks/ssr/src_app_logs_page_tsx_7b7b7b83._.js +0 -3
  636. package/.next/server/chunks/ssr/src_app_models_page_tsx_ed71d32e._.js +0 -3
  637. package/.next/server/chunks/ssr/src_app_providers_page_tsx_eb8b5137._.js +0 -3
  638. package/.next/static/cf2SWIkI5HVbnDjLExI42/_clientMiddlewareManifest.json +0 -1
  639. package/.next/static/chunks/5663c8696095f277.js +0 -1
  640. package/.next/static/chunks/64f547b3bcd3aef4.js +0 -1
  641. package/.next/static/chunks/6992685fe009e8fd.css +0 -1
  642. package/.next/static/chunks/6e0dee5b6681763c.js +0 -1
  643. package/.next/static/chunks/6f7efe5271343778.js +0 -1
  644. package/.next/static/chunks/75f76753fd97c8fd.js +0 -1
  645. package/.next/static/chunks/7c8b7cbb3339f139.js +0 -1
  646. package/.next/static/chunks/8ccc14e022ff6de3.js +0 -1
  647. package/.next/static/chunks/8cf1e5f00ebaea52.js +0 -1
  648. package/.next/static/chunks/a6dad97d9634a72d.js.map +0 -1
  649. package/.next/static/chunks/a7f539bf6487f4ff.js +0 -5
  650. package/.next/static/chunks/a89fdf03c5b0dfbd.js +0 -1
  651. package/.next/static/chunks/d2be314c3ece3fbe.js +0 -1
  652. package/.next/static/chunks/f2f58a7e93290fbb.js +0 -1
  653. package/.next/static/chunks/ff1a16fafef87110.js +0 -1
  654. package/.next/static/chunks/turbopack-fdb839c72e10c2ea.js +0 -4
  655. /package/.next/build/chunks/{[turbopack-node]_transforms_postcss_ts_df7a5b11._.js.map → [turbopack-node]_transforms_postcss_ts_0nnejqq._.js.map} +0 -0
  656. /package/.next/server/chunks/{_next-internal_server_app_api_config_route_actions_308a9f33.js.map → 0zjb_server_app_api_ide_openclaw_available-models_route_actions_0.gjr6a.js.map} +0 -0
  657. /package/.next/server/chunks/{_next-internal_server_app_api_gateway_[___path]_route_actions_835b2379.js.map → 0zjb_server_app_api_ide_opencode_available-models_route_actions_0poyhyk.js.map} +0 -0
  658. /package/.next/server/chunks/{_next-internal_server_app_api_gateway_models_route_actions_302c9983.js.map → _next-internal_server_app_api_config_route_actions_08dm.dx.js.map} +0 -0
  659. /package/.next/server/chunks/{_next-internal_server_app_api_gateway_route_actions_e5e7405d.js.map → _next-internal_server_app_api_gateway_[___path]_route_actions_0mmqyo7.js.map} +0 -0
  660. /package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_apply_route_actions_5056516c.js.map → _next-internal_server_app_api_gateway_models_route_actions_08b214z.js.map} +0 -0
  661. /package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_available-models_route_actions_94d710a0.js.map → _next-internal_server_app_api_gateway_route_actions_0.jzdw1.js.map} +0 -0
  662. /package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_restore_route_actions_f37acc94.js.map → _next-internal_server_app_api_ide_claude_apply_route_actions_0dw2_pf.js.map} +0 -0
  663. /package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_save_route_actions_407c55f5.js.map → _next-internal_server_app_api_ide_claude_available-models_route_actions_0pmwy75.js.map} +0 -0
  664. /package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_status_route_actions_5ac73db8.js.map → _next-internal_server_app_api_ide_claude_restore_route_actions_11x77hl.js.map} +0 -0
  665. /package/.next/server/chunks/{_next-internal_server_app_api_ide_claude_test_route_actions_70587902.js.map → _next-internal_server_app_api_ide_claude_save_route_actions_0b35ro_.js.map} +0 -0
  666. /package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_apply_route_actions_2cb9e4b4.js.map → _next-internal_server_app_api_ide_claude_status_route_actions_0fnw-w7.js.map} +0 -0
  667. /package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_preview_route_actions_9814a8e4.js.map → _next-internal_server_app_api_ide_claude_test_route_actions_0jc1czy.js.map} +0 -0
  668. /package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_restore_route_actions_10ad8f9d.js.map → _next-internal_server_app_api_ide_openclaw_apply_route_actions_07re971.js.map} +0 -0
  669. /package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_save_route_actions_044ad081.js.map → _next-internal_server_app_api_ide_openclaw_preview_route_actions_0q53p05.js.map} +0 -0
  670. /package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_status_route_actions_ed9786d2.js.map → _next-internal_server_app_api_ide_openclaw_restore_route_actions_02yog9-.js.map} +0 -0
  671. /package/.next/server/chunks/{_next-internal_server_app_api_ide_openclaw_test_route_actions_ce2cb808.js.map → _next-internal_server_app_api_ide_openclaw_save_route_actions_00tjxsz.js.map} +0 -0
  672. /package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_apply_route_actions_6c422244.js.map → _next-internal_server_app_api_ide_openclaw_status_route_actions_10wsun4.js.map} +0 -0
  673. /package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_preview_route_actions_256c82e0.js.map → _next-internal_server_app_api_ide_openclaw_test_route_actions_0zgwyon.js.map} +0 -0
  674. /package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_restore_route_actions_371993d3.js.map → _next-internal_server_app_api_ide_opencode_apply_route_actions_0in-w.g.js.map} +0 -0
  675. /package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_save_route_actions_6e4c9c41.js.map → _next-internal_server_app_api_ide_opencode_preview_route_actions_06h6.w~.js.map} +0 -0
  676. /package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_status_route_actions_498ad77b.js.map → _next-internal_server_app_api_ide_opencode_restore_route_actions_09ipt-l.js.map} +0 -0
  677. /package/.next/server/chunks/{_next-internal_server_app_api_ide_opencode_test_route_actions_c71be510.js.map → _next-internal_server_app_api_ide_opencode_save_route_actions_0i-~x79.js.map} +0 -0
  678. /package/.next/server/chunks/{_next-internal_server_app_api_logs_route_actions_30a87f47.js.map → _next-internal_server_app_api_ide_opencode_status_route_actions_0cpf6rv.js.map} +0 -0
  679. /package/.next/server/chunks/{_next-internal_server_app_api_models_route_actions_b6abdc83.js.map → _next-internal_server_app_api_ide_opencode_test_route_actions_0y8aq8h.js.map} +0 -0
  680. /package/.next/server/chunks/{_next-internal_server_app_api_providers_route_actions_5388b373.js.map → _next-internal_server_app_api_logs_route_actions_08ef2j7.js.map} +0 -0
  681. /package/.next/server/chunks/{_next-internal_server_app_api_providers_test_route_actions_b97ab15a.js.map → _next-internal_server_app_api_models_route_actions_0vfccm4.js.map} +0 -0
  682. /package/.next/server/chunks/{_next-internal_server_app_api_service_force-stop_route_actions_95eba80b.js.map → _next-internal_server_app_api_providers_route_actions_0ee1p_m.js.map} +0 -0
  683. /package/.next/server/chunks/{_next-internal_server_app_api_service_start_route_actions_d50efb77.js.map → _next-internal_server_app_api_providers_test_route_actions_0vyo652.js.map} +0 -0
  684. /package/.next/server/chunks/{_next-internal_server_app_api_service_status_route_actions_30149042.js.map → _next-internal_server_app_api_service_force-stop_route_actions_0pu9xrq.js.map} +0 -0
  685. /package/.next/server/chunks/{_next-internal_server_app_api_service_stop_route_actions_19443941.js.map → _next-internal_server_app_api_service_start_route_actions_0_o53a2.js.map} +0 -0
  686. /package/.next/server/chunks/{ce889_server_app_api_ide_openclaw_available-models_route_actions_e568e70b.js.map → _next-internal_server_app_api_service_status_route_actions_08ag8v4.js.map} +0 -0
  687. /package/.next/server/chunks/{ce889_server_app_api_ide_opencode_available-models_route_actions_95230db3.js.map → _next-internal_server_app_api_service_stop_route_actions_04dp83p.js.map} +0 -0
  688. /package/.next/server/chunks/{ssr/_next-internal_server_app__global-error_page_actions_75761787.js.map → _next-internal_server_app_api_tokenizer_history_route_actions_09~nqtd.js.map} +0 -0
  689. /package/.next/server/chunks/{ssr/_next-internal_server_app__not-found_page_actions_554ec2bf.js.map → _next-internal_server_app_api_tokenizer_test_route_actions_0t2swp-.js.map} +0 -0
  690. /package/.next/server/chunks/ssr/{_next-internal_server_app_ide_page_actions_d521d6ae.js.map → _next-internal_server_app__global-error_page_actions_0k77kol.js.map} +0 -0
  691. /package/.next/server/chunks/ssr/{_next-internal_server_app_logs_page_actions_a1c69041.js.map → _next-internal_server_app__not-found_page_actions_0eq97pa.js.map} +0 -0
  692. /package/.next/server/chunks/ssr/{_next-internal_server_app_models_page_actions_543cf22f.js.map → _next-internal_server_app_ide_page_actions_0_opd4~.js.map} +0 -0
  693. /package/.next/server/chunks/ssr/{_next-internal_server_app_page_actions_39d4fc33.js.map → _next-internal_server_app_logs_page_actions_0rvsl~d.js.map} +0 -0
  694. /package/.next/server/chunks/ssr/{_next-internal_server_app_providers_page_actions_c75f6cb3.js.map → _next-internal_server_app_models_page_actions_0eiz7f7.js.map} +0 -0
  695. /package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_9774470f._.js.map → node_modules_next_dist_client_components_0inhx6q._.js.map} +0 -0
  696. /package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_builtin_forbidden_45780354.js.map → node_modules_next_dist_client_components_builtin_forbidden_0ghu-f7.js.map} +0 -0
  697. /package/.next/server/chunks/ssr/{node_modules_next_dist_client_components_builtin_unauthorized_15817684.js.map → node_modules_next_dist_client_components_builtin_unauthorized_0cjv-23.js.map} +0 -0
  698. /package/.next/static/{cf2SWIkI5HVbnDjLExI42 → XHnu7Z1vWSrgmneps8rX4}/_buildManifest.js +0 -0
  699. /package/.next/static/{cf2SWIkI5HVbnDjLExI42 → XHnu7Z1vWSrgmneps8rX4}/_ssgManifest.js +0 -0
  700. /package/.next/static/chunks/{a6dad97d9634a72d.js → 03~yq9q893hmn.js} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../node_modules/%40swc/helpers/cjs/_interop_require_wildcard.cjs","../../../../node_modules/next/src/shared/lib/router/utils/querystring.ts","../../../../node_modules/next/src/shared/lib/router/utils/format-url.ts","../../../../node_modules/next/src/client/use-merged-ref.ts","../../../../node_modules/next/src/shared/lib/utils.ts","../../../../node_modules/next/src/shared/lib/router/utils/parse-path.ts","../../../../node_modules/next/src/shared/lib/router/utils/add-path-prefix.ts","../../../../node_modules/next/src/shared/lib/router/utils/remove-trailing-slash.ts","../../../../node_modules/next/src/client/normalize-trailing-slash.ts","../../../../node_modules/next/src/client/add-base-path.ts","../../../../node_modules/next/src/shared/lib/utils/warn-once.ts","../../../../node_modules/next/src/client/components/router-reducer/router-reducer-types.ts","../../../../node_modules/next/src/client/components/segment-cache/types.ts","../../../../node_modules/next/src/client/components/segment-cache/cache-key.ts","../../../../node_modules/next/src/shared/lib/app-router-types.ts","../../../../node_modules/next/src/client/components/match-segments.ts","../../../../node_modules/next/src/shared/lib/segment-cache/vary-params-decoding.ts","../../../../node_modules/next/src/client/components/app-router-headers.ts","../../../../node_modules/next/src/shared/lib/invariant-error.ts","../../../../node_modules/next/src/shared/lib/is-thenable.ts","../../../../node_modules/next/src/client/components/use-action-queue.ts","../../../../node_modules/next/src/client/app-call-server.ts","../../../../node_modules/next/src/client/app-find-source-map-url.ts","../../../../node_modules/next/src/shared/lib/segment.ts","../../../../node_modules/next/src/shared/lib/segment-cache/segment-value-encoding.ts","../../../../node_modules/next/src/client/route-params.ts","../../../../node_modules/next/src/client/components/router-reducer/create-href-from-url.ts","../../../../node_modules/next/src/client/flight-data-helpers.ts","../../../../node_modules/next/src/shared/lib/hash.ts","../../../../node_modules/next/src/shared/lib/router/utils/cache-busting-search-param.ts","../../../../node_modules/next/src/client/components/router-reducer/set-cache-busting-search-param.ts","../../../../node_modules/next/src/shared/lib/deployment-id.ts","../../../../node_modules/next/src/client/navigation-build-id.ts","../../../../node_modules/next/src/lib/constants.ts","../../../../node_modules/next/src/client/components/router-reducer/is-navigating-to-new-root-layout.ts","../../../../node_modules/next/src/client/components/router-reducer/reducers/committed-state.ts","../../../../node_modules/next/src/client/components/segment-cache/lru.ts","../../../../node_modules/next/src/client/components/segment-cache/cache-map.ts","../../../../node_modules/next/src/client/components/segment-cache/vary-path.ts","../../../../node_modules/next/src/client/components/segment-cache/optimistic-routes.ts","../../../../node_modules/next/src/client/components/router-reducer/ppr-navigations.ts","../../../../node_modules/next/src/shared/lib/page-path/ensure-leading-slash.ts","../../../../node_modules/next/src/shared/lib/router/utils/app-paths.ts","../../../../node_modules/next/src/shared/lib/router/utils/interception-routes.ts","../../../../node_modules/next/src/client/components/router-reducer/compute-changed-path.ts","../../../../node_modules/next/src/client/lib/javascript-url.ts","../../../../node_modules/next/src/client/components/segment-cache/navigation-testing-lock.ts","../../../../node_modules/next/src/client/components/segment-cache/navigation.ts","../../../../node_modules/next/src/client/components/router-reducer/reducers/navigate-reducer.ts","../../../../node_modules/next/src/client/components/segment-cache/bfcache.ts","../../../../node_modules/next/src/client/components/router-reducer/fetch-server-response.ts","../../../../node_modules/next/src/shared/lib/promise-with-resolvers.ts","../../../../node_modules/next/src/client/components/segment-cache/cache.ts","../../../../node_modules/next/src/client/components/segment-cache/scheduler.ts","../../../../node_modules/next/src/client/components/links.ts","../../../../node_modules/next/src/shared/lib/router/utils/path-has-prefix.ts","../../../../node_modules/next/src/client/has-base-path.ts","../../../../node_modules/next/src/shared/lib/router/utils/is-local-url.ts","../../../../node_modules/next/src/shared/lib/utils/error-once.ts","../../../../node_modules/next/src/client/app-dir/link.tsx","../../../../node_modules/next/src/client/components/unrecognized-action-error.ts","../../../../node_modules/next/src/client/components/readonly-url-search-params.ts","../../../../node_modules/next/src/client/components/redirect-status-code.ts","../../../../node_modules/next/src/client/components/redirect-error.ts","../../../../node_modules/next/src/client/components/redirect.ts","../../../../node_modules/next/src/client/components/http-access-fallback/http-access-fallback.ts","../../../../node_modules/next/src/client/components/not-found.ts","../../../../node_modules/next/src/client/components/forbidden.ts","../../../../node_modules/next/src/client/components/unauthorized.ts","../../../../node_modules/next/src/server/app-render/staged-rendering.ts","../../../../node_modules/next/src/server/dynamic-rendering-utils.ts","../../../../node_modules/next/src/server/lib/router-utils/is-postpone.ts","../../../../node_modules/next/src/shared/lib/lazy-dynamic/bailout-to-csr.ts","../../../../node_modules/next/src/client/components/is-next-router-error.ts","../../../../node_modules/next/src/client/components/hooks-server-context.ts","../../../../node_modules/next/src/client/components/static-generation-bailout.ts","../../../../node_modules/next/src/lib/framework/boundary-constants.tsx","../../../../node_modules/next/src/lib/scheduler.ts","../../../../node_modules/next/src/server/app-render/instant-validation/boundary-constants.ts","../../../../node_modules/next/src/server/app-render/dynamic-rendering.ts","../../../../node_modules/next/src/client/components/unstable-rethrow.server.ts","../../../../node_modules/next/src/client/components/unstable-rethrow.ts","../../../../node_modules/next/src/client/components/navigation.react-server.ts","../../../../node_modules/next/src/client/components/navigation.ts","../../../../node_modules/next/navigation.js","../../../../src/app/components/Nav.tsx"],"sourcesContent":["\"use strict\";\n\nfunction _getRequireWildcardCache(nodeInterop) {\n if (typeof WeakMap !== \"function\") return null;\n\n var cacheBabelInterop = new WeakMap();\n var cacheNodeInterop = new WeakMap();\n\n return (_getRequireWildcardCache = function(nodeInterop) {\n return nodeInterop ? cacheNodeInterop : cacheBabelInterop;\n })(nodeInterop);\n}\nfunction _interop_require_wildcard(obj, nodeInterop) {\n if (!nodeInterop && obj && obj.__esModule) return obj;\n if (obj === null || typeof obj !== \"object\" && typeof obj !== \"function\") return { default: obj };\n\n var cache = _getRequireWildcardCache(nodeInterop);\n\n if (cache && cache.has(obj)) return cache.get(obj);\n\n var newObj = { __proto__: null };\n var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;\n\n for (var key in obj) {\n if (key !== \"default\" && Object.prototype.hasOwnProperty.call(obj, key)) {\n var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;\n if (desc && (desc.get || desc.set)) Object.defineProperty(newObj, key, desc);\n else newObj[key] = obj[key];\n }\n }\n\n newObj.default = obj;\n\n if (cache) cache.set(obj, newObj);\n\n return newObj;\n}\nexports._ = _interop_require_wildcard;\n","import type { ParsedUrlQuery } from 'querystring'\n\nexport function searchParamsToUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n const query: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n const existing = query[key]\n if (typeof existing === 'undefined') {\n query[key] = value\n } else if (Array.isArray(existing)) {\n existing.push(value)\n } else {\n query[key] = [existing, value]\n }\n }\n return query\n}\n\nfunction stringifyUrlQueryParam(param: unknown): string {\n if (typeof param === 'string') {\n return param\n }\n\n if (\n (typeof param === 'number' && !isNaN(param)) ||\n typeof param === 'boolean'\n ) {\n return String(param)\n } else {\n return ''\n }\n}\n\nexport function urlQueryToSearchParams(query: ParsedUrlQuery): URLSearchParams {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(query)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n searchParams.append(key, stringifyUrlQueryParam(item))\n }\n } else {\n searchParams.set(key, stringifyUrlQueryParam(value))\n }\n }\n return searchParams\n}\n\nexport function assign(\n target: URLSearchParams,\n ...searchParamsList: URLSearchParams[]\n): URLSearchParams {\n for (const searchParams of searchParamsList) {\n for (const key of searchParams.keys()) {\n target.delete(key)\n }\n\n for (const [key, value] of searchParams.entries()) {\n target.append(key, value)\n }\n }\n\n return target\n}\n","// Format function modified from nodejs\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport type { UrlObject } from 'url'\nimport type { ParsedUrlQuery } from 'querystring'\nimport * as querystring from './querystring'\n\nconst slashedProtocols = /https?|ftp|gopher|file/\n\nexport function formatUrl(urlObj: UrlObject) {\n let { auth, hostname } = urlObj\n let protocol = urlObj.protocol || ''\n let pathname = urlObj.pathname || ''\n let hash = urlObj.hash || ''\n let query = urlObj.query || ''\n let host: string | false = false\n\n auth = auth ? encodeURIComponent(auth).replace(/%3A/i, ':') + '@' : ''\n\n if (urlObj.host) {\n host = auth + urlObj.host\n } else if (hostname) {\n host = auth + (~hostname.indexOf(':') ? `[${hostname}]` : hostname)\n if (urlObj.port) {\n host += ':' + urlObj.port\n }\n }\n\n if (query && typeof query === 'object') {\n query = String(querystring.urlQueryToSearchParams(query as ParsedUrlQuery))\n }\n\n let search = urlObj.search || (query && `?${query}`) || ''\n\n if (protocol && !protocol.endsWith(':')) protocol += ':'\n\n if (\n urlObj.slashes ||\n ((!protocol || slashedProtocols.test(protocol)) && host !== false)\n ) {\n host = '//' + (host || '')\n if (pathname && pathname[0] !== '/') pathname = '/' + pathname\n } else if (!host) {\n host = ''\n }\n\n if (hash && hash[0] !== '#') hash = '#' + hash\n if (search && search[0] !== '?') search = '?' + search\n\n pathname = pathname.replace(/[?#]/g, encodeURIComponent)\n search = search.replace('#', '%23')\n\n return `${protocol}${host}${pathname}${search}${hash}`\n}\n\nexport const urlObjectKeys = [\n 'auth',\n 'hash',\n 'host',\n 'hostname',\n 'href',\n 'path',\n 'pathname',\n 'port',\n 'protocol',\n 'query',\n 'search',\n 'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n if (process.env.NODE_ENV === 'development') {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach((key) => {\n if (!urlObjectKeys.includes(key)) {\n console.warn(\n `Unknown key passed via urlObject into url.format: ${key}`\n )\n }\n })\n }\n }\n\n return formatUrl(url)\n}\n","import { useCallback, useRef, type Ref } from 'react'\n\n// This is a compatibility hook to support React 18 and 19 refs.\n// In 19, a cleanup function from refs may be returned.\n// In 18, returning a cleanup function creates a warning.\n// Since we take userspace refs, we don't know ahead of time if a cleanup function will be returned.\n// This implements cleanup functions with the old behavior in 18.\n// We know refs are always called alternating with `null` and then `T`.\n// So a call with `null` means we need to call the previous cleanup functions.\nexport function useMergedRef<TElement>(\n refA: Ref<TElement>,\n refB: Ref<TElement>\n): Ref<TElement> {\n const cleanupA = useRef<(() => void) | null>(null)\n const cleanupB = useRef<(() => void) | null>(null)\n\n // NOTE: In theory, we could skip the wrapping if only one of the refs is non-null.\n // (this happens often if the user doesn't pass a ref to Link/Form/Image)\n // But this can cause us to leak a cleanup-ref into user code (previously via `<Link legacyBehavior>`),\n // and the user might pass that ref into ref-merging library that doesn't support cleanup refs\n // (because it hasn't been updated for React 19)\n // which can then cause things to blow up, because a cleanup-returning ref gets called with `null`.\n // So in practice, it's safer to be defensive and always wrap the ref, even on React 19.\n return useCallback(\n (current: TElement | null): void => {\n if (current === null) {\n const cleanupFnA = cleanupA.current\n if (cleanupFnA) {\n cleanupA.current = null\n cleanupFnA()\n }\n const cleanupFnB = cleanupB.current\n if (cleanupFnB) {\n cleanupB.current = null\n cleanupFnB()\n }\n } else {\n if (refA) {\n cleanupA.current = applyRef(refA, current)\n }\n if (refB) {\n cleanupB.current = applyRef(refB, current)\n }\n }\n },\n [refA, refB]\n )\n}\n\nfunction applyRef<TElement>(\n refA: NonNullable<Ref<TElement>>,\n current: TElement\n) {\n if (typeof refA === 'function') {\n const cleanup = refA(current)\n if (typeof cleanup === 'function') {\n return cleanup\n } else {\n return () => refA(null)\n }\n } else {\n refA.current = current\n return () => {\n refA.current = null\n }\n }\n}\n","import type { HtmlProps } from './html-context.shared-runtime'\nimport type { ComponentType, JSX } from 'react'\nimport type { DomainLocale } from '../../server/config'\nimport type { Env } from '@next/env'\nimport type { IncomingMessage, ServerResponse } from 'http'\nimport type { NextRouter } from './router/router'\nimport type { ParsedUrlQuery } from 'querystring'\nimport type { PreviewData } from '../../types'\nimport type { COMPILER_NAMES } from './constants'\nimport type fs from 'fs'\n\nexport type NextComponentType<\n Context extends BaseContext = NextPageContext,\n InitialProps = {},\n Props = {},\n> = ComponentType<Props> & {\n /**\n * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n * @param context Context of `page`\n */\n getInitialProps?(context: Context): InitialProps | Promise<InitialProps>\n}\n\nexport type DocumentType = NextComponentType<\n DocumentContext,\n DocumentInitialProps,\n DocumentProps\n>\n\nexport type AppType<P = {}> = NextComponentType<\n AppContextType,\n P,\n AppPropsType<any, P>\n>\n\nexport type AppTreeType = ComponentType<\n AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport const WEB_VITALS = ['CLS', 'FCP', 'FID', 'INP', 'LCP', 'TTFB'] as const\nexport type NextWebVitalsMetric = {\n id: string\n startTime: number\n value: number\n attribution?: { [key: string]: unknown }\n} & (\n | {\n label: 'web-vital'\n name: (typeof WEB_VITALS)[number]\n }\n | {\n label: 'custom'\n name:\n | 'Next.js-hydration'\n | 'Next.js-route-change-to-render'\n | 'Next.js-render'\n }\n)\n\nexport type Enhancer<C> = (Component: C) => C\n\nexport type ComponentsEnhancer =\n | {\n enhanceApp?: Enhancer<AppType>\n enhanceComponent?: Enhancer<NextComponentType>\n }\n | Enhancer<NextComponentType>\n\nexport type RenderPageResult = {\n html: string\n head?: Array<JSX.Element | null>\n}\n\nexport type RenderPage = (\n options?: ComponentsEnhancer\n) => DocumentInitialProps | Promise<DocumentInitialProps>\n\nexport type BaseContext = {\n res?: ServerResponse\n [k: string]: any\n}\n\nexport type NEXT_DATA = {\n props: Record<string, any>\n page: string\n query: ParsedUrlQuery\n buildId: string\n assetPrefix?: string\n nextExport?: boolean\n autoExport?: boolean\n isFallback?: boolean\n isExperimentalCompile?: boolean\n dynamicIds?: (string | number)[]\n err?: Error & {\n statusCode?: number\n source?: typeof COMPILER_NAMES.server | typeof COMPILER_NAMES.edgeServer\n }\n gsp?: boolean\n gssp?: boolean\n customServer?: boolean\n gip?: boolean\n appGip?: boolean\n locale?: string\n locales?: readonly string[]\n defaultLocale?: string\n domainLocales?: readonly DomainLocale[]\n scriptLoader?: any[]\n isPreview?: boolean\n notFoundSrcPage?: string\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n /**\n * Error object if encountered during rendering\n */\n err?: (Error & { statusCode?: number }) | null\n /**\n * `HTTP` request object.\n */\n req?: IncomingMessage\n /**\n * `HTTP` response object.\n */\n res?: ServerResponse\n /**\n * Path section of `URL`.\n */\n pathname: string\n /**\n * Query string section of `URL` parsed as an object.\n */\n query: ParsedUrlQuery\n /**\n * `String` of the actual path including query.\n */\n asPath?: string\n /**\n * The currently active locale\n */\n locale?: string\n /**\n * All configured locales\n */\n locales?: readonly string[]\n /**\n * The configured default locale\n */\n defaultLocale?: string\n /**\n * `Component` the tree of the App to use if needing to render separately\n */\n AppTree: AppTreeType\n}\n\nexport type AppContextType<Router extends NextRouter = NextRouter> = {\n Component: NextComponentType<NextPageContext>\n AppTree: AppTreeType\n ctx: NextPageContext\n router: Router\n}\n\nexport type AppInitialProps<PageProps = any> = {\n pageProps: PageProps\n}\n\nexport type AppPropsType<\n Router extends NextRouter = NextRouter,\n PageProps = {},\n> = AppInitialProps<PageProps> & {\n Component: NextComponentType<NextPageContext, any, any>\n router: Router\n __N_SSG?: boolean\n __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n renderPage: RenderPage\n defaultGetInitialProps(\n ctx: DocumentContext,\n options?: { nonce?: string }\n ): Promise<DocumentInitialProps>\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n styles?: React.ReactElement[] | Iterable<React.ReactNode> | JSX.Element\n}\n\nexport type DocumentProps = DocumentInitialProps & HtmlProps\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n /**\n * Object of `query` values from url\n */\n query: Partial<{\n [key: string]: string | string[]\n }>\n /**\n * Object of `cookies` from header\n */\n cookies: Partial<{\n [key: string]: string\n }>\n\n body: any\n\n env: Env\n\n draftMode?: boolean\n\n preview?: boolean\n /**\n * Preview data set on the request, if any\n * */\n previewData?: PreviewData\n}\n\n/**\n * Send body of response\n */\ntype Send<T> = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse<Data = any> = ServerResponse & {\n /**\n * Send data `any` data in response\n */\n send: Send<Data>\n /**\n * Send data `json` data in response\n */\n json: Send<Data>\n status: (statusCode: number) => NextApiResponse<Data>\n redirect(url: string): NextApiResponse<Data>\n redirect(status: number, url: string): NextApiResponse<Data>\n\n /**\n * Set draft mode\n */\n setDraftMode: (options: { enable: boolean }) => NextApiResponse<Data>\n\n /**\n * Set preview data for Next.js' prerender mode\n */\n setPreviewData: (\n data: object | string,\n options?: {\n /**\n * Specifies the number (in seconds) for the preview session to last for.\n * The given number will be converted to an integer by rounding down.\n * By default, no maximum age is set and the preview session finishes\n * when the client shuts down (browser is closed).\n */\n maxAge?: number\n /**\n * Specifies the path for the preview session to work under. By default,\n * the path is considered the \"default path\", i.e., any pages under \"/\".\n */\n path?: string\n }\n ) => NextApiResponse<Data>\n\n /**\n * Clear preview data for Next.js' prerender mode\n */\n clearPreviewData: (options?: { path?: string }) => NextApiResponse<Data>\n\n /**\n * Revalidate a specific page and regenerate it using On-Demand Incremental\n * Static Regeneration.\n * The path should be an actual path, not a rewritten path. E.g. for\n * \"/blog/[slug]\" this should be \"/blog/post-1\".\n * @link https://nextjs.org/docs/app/building-your-application/data-fetching/incremental-static-regeneration#on-demand-revalidation-with-revalidatepath\n */\n revalidate: (\n urlPath: string,\n opts?: {\n unstable_onlyGenerated?: boolean\n }\n ) => Promise<void>\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler<T = any> = (\n req: NextApiRequest,\n res: NextApiResponse<T>\n) => unknown | Promise<unknown>\n\n/**\n * Utils\n */\nexport function execOnce<T extends (...args: any[]) => ReturnType<T>>(\n fn: T\n): T {\n let used = false\n let result: ReturnType<T>\n\n return ((...args: any[]) => {\n if (!used) {\n used = true\n result = fn(...args)\n }\n return result\n }) as T\n}\n\n// Scheme: https://tools.ietf.org/html/rfc3986#section-3.1\n// Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3\nconst ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\\d+\\-.]*?:/\nexport const isAbsoluteUrl = (url: string) => ABSOLUTE_URL_REGEX.test(url)\n\nexport function getLocationOrigin() {\n const { protocol, hostname, port } = window.location\n return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n const { href } = window.location\n const origin = getLocationOrigin()\n return href.substring(origin.length)\n}\n\nexport function getDisplayName<P>(Component: ComponentType<P>) {\n return typeof Component === 'string'\n ? Component\n : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n return res.finished || res.headersSent\n}\n\nexport function normalizeRepeatedSlashes(url: string) {\n const urlParts = url.split('?')\n const urlNoQuery = urlParts[0]\n\n return (\n urlNoQuery\n // first we replace any non-encoded backslashes with forward\n // then normalize repeated forward slashes\n .replace(/\\\\/g, '/')\n .replace(/\\/\\/+/g, '/') +\n (urlParts[1] ? `?${urlParts.slice(1).join('?')}` : '')\n )\n}\n\nexport async function loadGetInitialProps<\n C extends BaseContext,\n IP = {},\n P = {},\n>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {\n if (process.env.NODE_ENV !== 'production') {\n if (App.prototype?.getInitialProps) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" is defined as an instance method - visit https://nextjs.org/docs/messages/get-initial-props-as-an-instance-method for more information.`\n throw new Error(message)\n }\n }\n // when called from _app `ctx` is nested in `ctx`\n const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n if (!App.getInitialProps) {\n if (ctx.ctx && ctx.Component) {\n // @ts-ignore pageProps default\n return {\n pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n }\n }\n return {} as IP\n }\n\n const props = await App.getInitialProps(ctx)\n\n if (res && isResSent(res)) {\n return props\n }\n\n if (!props) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n throw new Error(message)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (Object.keys(props).length === 0 && !ctx.ctx) {\n console.warn(\n `${getDisplayName(\n App\n )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://nextjs.org/docs/messages/empty-object-getInitialProps`\n )\n }\n }\n\n return props\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n SP &&\n (['mark', 'measure', 'getEntriesByName'] as const).every(\n (method) => typeof performance[method] === 'function'\n )\n\nexport class DecodeError extends Error {}\nexport class NormalizeError extends Error {}\nexport class PageNotFoundError extends Error {\n code: string\n\n constructor(page: string) {\n super()\n this.code = 'ENOENT'\n this.name = 'PageNotFoundError'\n this.message = `Cannot find module for page: ${page}`\n }\n}\n\nexport class MissingStaticPage extends Error {\n constructor(page: string, message: string) {\n super()\n this.message = `Failed to load static file for page: ${page} ${message}`\n }\n}\n\nexport class MiddlewareNotFoundError extends Error {\n code: string\n constructor() {\n super()\n this.code = 'ENOENT'\n this.message = `Cannot find the middleware module`\n }\n}\n\nexport interface CacheFs {\n existsSync: typeof fs.existsSync\n readFile: typeof fs.promises.readFile\n readFileSync: typeof fs.readFileSync\n writeFile(f: string, d: any): Promise<void>\n mkdir(dir: string): Promise<void | string>\n stat(f: string): Promise<{ mtime: Date }>\n}\n\nexport function stringifyError(error: Error) {\n return JSON.stringify({ message: error.message, stack: error.stack })\n}\n","/**\n * Given a path this function will find the pathname, query and hash and return\n * them. This is useful to parse full paths on the client side.\n * @param path A path to parse e.g. /foo/bar?id=1#hash\n */\nexport function parsePath(path: string) {\n const hashIndex = path.indexOf('#')\n const queryIndex = path.indexOf('?')\n const hasQuery = queryIndex > -1 && (hashIndex < 0 || queryIndex < hashIndex)\n\n if (hasQuery || hashIndex > -1) {\n return {\n pathname: path.substring(0, hasQuery ? queryIndex : hashIndex),\n query: hasQuery\n ? path.substring(queryIndex, hashIndex > -1 ? hashIndex : undefined)\n : '',\n hash: hashIndex > -1 ? path.slice(hashIndex) : '',\n }\n }\n\n return { pathname: path, query: '', hash: '' }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Adds the provided prefix to the given path. It first ensures that the path\n * is indeed starting with a slash.\n */\nexport function addPathPrefix(path: string, prefix?: string) {\n if (!path.startsWith('/') || !prefix) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n return `${prefix}${pathname}${query}${hash}`\n}\n","/**\n * Removes the trailing slash for a given route or page path. Preserves the\n * root page. Examples:\n * - `/foo/bar/` -> `/foo/bar`\n * - `/foo/bar` -> `/foo/bar`\n * - `/` -> `/`\n */\nexport function removeTrailingSlash(route: string) {\n return route.replace(/\\/$/, '') || '/'\n}\n","import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'\nimport { parsePath } from '../shared/lib/router/utils/parse-path'\n\n/**\n * Normalizes the trailing slash of a path according to the `trailingSlash` option\n * in `next.config.js`.\n */\nexport const normalizePathTrailingSlash = (path: string) => {\n if (!path.startsWith('/') || process.env.__NEXT_MANUAL_TRAILING_SLASH) {\n return path\n }\n\n const { pathname, query, hash } = parsePath(path)\n if (process.env.__NEXT_TRAILING_SLASH) {\n if (/\\.[^/]+\\/?$/.test(pathname)) {\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n } else if (pathname.endsWith('/')) {\n return `${pathname}${query}${hash}`\n } else {\n return `${pathname}/${query}${hash}`\n }\n }\n\n return `${removeTrailingSlash(pathname)}${query}${hash}`\n}\n","import { addPathPrefix } from '../shared/lib/router/utils/add-path-prefix'\nimport { normalizePathTrailingSlash } from './normalize-trailing-slash'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function addBasePath(path: string, required?: boolean): string {\n return normalizePathTrailingSlash(\n process.env.__NEXT_MANUAL_CLIENT_BASE_PATH && !required\n ? path\n : addPathPrefix(path, basePath)\n )\n}\n","let warnOnce = (_: string) => {}\nif (process.env.NODE_ENV !== 'production') {\n const warnings = new Set<string>()\n warnOnce = (msg: string) => {\n if (!warnings.has(msg)) {\n console.warn(msg)\n }\n warnings.add(msg)\n }\n}\n\nexport { warnOnce }\n","import type { CacheNode, ScrollRef } from '../../../shared/lib/app-router-types'\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport type { NavigationSeed } from '../segment-cache/navigation'\nimport type { FetchServerResponseResult } from './fetch-server-response'\n\nexport const ACTION_REFRESH = 'refresh'\nexport const ACTION_NAVIGATE = 'navigate'\nexport const ACTION_RESTORE = 'restore'\nexport const ACTION_SERVER_PATCH = 'server-patch'\nexport const ACTION_HMR_REFRESH = 'hmr-refresh'\nexport const ACTION_SERVER_ACTION = 'server-action'\n\nexport type RouterChangeByServerResponse = ({\n navigatedAt,\n previousTree,\n serverResponse,\n}: {\n navigatedAt: number\n previousTree: FlightRouterState\n serverResponse: FetchServerResponseResult\n}) => void\n\n/**\n * Refresh triggers a refresh of the full page data.\n * - fetches the Flight data and fills rsc at the root of the cache.\n * - The router state is updated at the root.\n */\nexport interface RefreshAction {\n type: typeof ACTION_REFRESH\n /**\n * Bypass invalidating the segment cache. Used by the Instant Navigation\n * Testing API to preserve prefetched data when refreshing after an MPA\n * navigation. Not exposed in production builds by default.\n */\n bypassCacheInvalidation?: boolean\n}\n\nexport interface HmrRefreshAction {\n type: typeof ACTION_HMR_REFRESH\n}\n\nexport type ServerActionDispatcher = (\n args: Omit<\n ServerActionAction,\n 'type' | 'mutable' | 'navigate' | 'changeByServerResponse' | 'cache'\n >\n) => void\n\nexport interface ServerActionAction {\n type: typeof ACTION_SERVER_ACTION\n actionId: string\n actionArgs: any[]\n resolve: (value: any) => void\n reject: (reason?: any) => void\n didRevalidate?: boolean\n}\n\n/**\n * Navigate triggers a navigation to the provided url. It supports two types: `push` and `replace`.\n *\n * `navigateType`:\n * - `push` - pushes a new history entry in the browser history\n * - `replace` - replaces the current history entry in the browser history\n *\n * Navigate has multiple cache heuristics:\n * - page was prefetched\n * - Apply router state tree from prefetch\n * - Apply Flight data from prefetch to the cache\n * - If Flight data is a string, it's a redirect and the state is updated to trigger a redirect\n * - Check if hard navigation is needed\n * - Hard navigation happens when a dynamic parameter below the common layout changed\n * - When hard navigation is needed the cache is invalidated below the flightSegmentPath\n * - The missing cache nodes of the page will be fetched in layout-router and trigger the SERVER_PATCH action\n * - If hard navigation is not needed\n * - The cache is reused\n * - If any cache nodes are missing they'll be fetched in layout-router and trigger the SERVER_PATCH action\n * - page was not prefetched\n * - The navigate was called from `next/router` (`router.push()` / `router.replace()`) / `next/link` without prefetched data available (e.g. the prefetch didn't come back from the server before clicking the link)\n * - Flight data is fetched in the reducer (suspends the reducer)\n * - Router state tree is created based on Flight data\n * - Cache is filled based on the Flight data\n *\n * Above steps explain 3 cases:\n * - `soft` - Reuses the existing cache and fetches missing nodes in layout-router.\n * - `hard` - Creates a new cache where cache nodes are removed below the common layout and fetches missing nodes in layout-router.\n * - `optimistic` (explicit no prefetch) - Creates a new cache and kicks off the data fetch in the reducer. The data fetch is awaited in the layout-router.\n */\nexport interface NavigateAction {\n type: typeof ACTION_NAVIGATE\n url: URL\n isExternalUrl: boolean\n locationSearch: Location['search']\n navigateType: 'push' | 'replace'\n scrollBehavior: ScrollBehavior\n}\n\n/**\n * Restore applies the provided router state.\n * - Used for `popstate` (back/forward navigation) where a known router state has to be applied.\n * - Also used when syncing the router state with `pushState`/`replaceState` calls.\n * - Router state is applied as-is from the history state, if available.\n * - If the history state does not contain the router state, the existing router state is used.\n * - If any cache node is missing it will be fetched in layout-router during rendering and the server-patch case.\n * - If existing cache nodes match these are used.\n */\nexport interface RestoreAction {\n type: typeof ACTION_RESTORE\n url: URL\n historyState: AppHistoryState | undefined\n}\n\nexport type AppHistoryState = {\n tree: FlightRouterState\n renderedSearch: string\n}\n\n/**\n * Server-patch applies the provided Flight data to the cache and router tree.\n */\nexport interface ServerPatchAction {\n type: typeof ACTION_SERVER_PATCH\n previousTree: FlightRouterState\n url: URL\n nextUrl: string | null\n seed: NavigationSeed | null\n mpa: boolean\n navigateType: 'push' | 'replace'\n}\n\n/**\n * PrefetchKind defines the type of prefetching that should be done.\n * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.\n * - `full` - prefetch the page data fully.\n */\n\nexport enum PrefetchKind {\n AUTO = 'auto',\n FULL = 'full',\n}\n\n/**\n * Prefetch adds the provided FlightData to the prefetch cache\n * - Creates the router state tree based on the patch in FlightData\n * - Adds the FlightData to the prefetch cache\n * - In ACTION_NAVIGATE the prefetch cache is checked and the router state tree and FlightData are applied.\n */\n\nexport interface PushRef {\n /**\n * If the app-router should push a new history entry in app-router's useEffect()\n */\n pendingPush: boolean\n /**\n * Multi-page navigation through location.href.\n */\n mpaNavigation: boolean\n /**\n * Skip applying the router state to the browser history state.\n */\n preserveCustomHistoryState: boolean\n}\n\n/**\n * Controls the scroll behavior for a navigation.\n */\nexport const enum ScrollBehavior {\n /** Use per-node ScrollRef to decide whether to scroll. */\n Default = 0,\n /** Suppress scroll entirely (e.g. scroll={false} on Link or router.push). */\n NoScroll = 1,\n}\n\nexport type FocusAndScrollRef = {\n /**\n * The scroll ref from the most recent navigation. Set to whatever was\n * accumulated during tree construction (or null if nothing was\n * accumulated). On the next navigation, if new scroll targets are\n * created, the previous scrollRef is invalidated by setting\n * `current = false`.\n */\n scrollRef: ScrollRef | null\n /**\n * When true, the scroll handler uses `focusAndScrollRef.scrollRef`\n * for every segment regardless of per-node state. Used for hash-only\n * navigations where every segment should be treated as a scroll\n * target. When false, the handler checks `cacheNode.scrollRef`\n * instead (per-node), so only segments that actually navigated scroll.\n */\n forceScroll: boolean\n /**\n * The hash fragment that should be scrolled to.\n */\n hashFragment: string | null\n /**\n * If only the URLs hash fragment changed\n */\n onlyHashChange: boolean\n}\n\n/**\n * Handles keeping the state of app-router.\n */\nexport type AppRouterState = {\n /**\n * The router state, this is written into the history state in app-router using replaceState/pushState.\n * - Has to be serializable as it is written into the history state.\n * - Holds which segments and parallel routes are shown on the screen.\n */\n tree: FlightRouterState\n /**\n * The cache holds React nodes for every segment that is shown on screen as well as previously shown segments.\n * It also holds in-progress data requests.\n */\n cache: CacheNode\n /**\n * Decides if the update should create a new history entry and if the navigation has to trigger a browser navigation.\n */\n pushRef: PushRef\n /**\n * Decides if the update should apply scroll and focus management.\n */\n focusAndScrollRef: FocusAndScrollRef\n /**\n * The canonical url that is pushed/replaced.\n * - This is the url you see in the browser.\n */\n canonicalUrl: string\n\n /**\n * The search query observed by the server during rendering. This may be\n * different from the canonical URL's search query if the server performed\n * a rewrite. Even though a client component won't observe this (unless it\n * were passed from a Server component), the client router needs to know this\n * so it can properly cache segment data; it'ss part of a page segment's\n * cache key.\n */\n renderedSearch: string\n\n /**\n * The underlying \"url\" representing the UI state, which is used for intercepting routes.\n */\n nextUrl: string | null\n\n /**\n * The previous next-url that was used previous to a dynamic navigation.\n */\n previousNextUrl: string | null\n\n debugInfo: Array<unknown> | null\n}\n\nexport type ReadonlyReducerState = Readonly<AppRouterState>\nexport type ReducerState =\n | (Promise<AppRouterState> & { _debugInfo?: Array<unknown> })\n | AppRouterState\nexport type ReducerActions = Readonly<\n | RefreshAction\n | NavigateAction\n | RestoreAction\n | ServerPatchAction\n | HmrRefreshAction\n | ServerActionAction\n>\n","/**\n * Shared types and constants for the Segment Cache.\n */\n\nexport const enum NavigationResultTag {\n MPA,\n Success,\n NoOp,\n Async,\n}\n\n/**\n * The priority of the prefetch task. Higher numbers are higher priority.\n */\nexport const enum PrefetchPriority {\n /**\n * Assigned to the most recently hovered/touched link. Special network\n * bandwidth is reserved for this task only. There's only ever one Intent-\n * priority task at a time; when a new Intent task is scheduled, the previous\n * one is bumped down to Default.\n */\n Intent = 2,\n /**\n * The default priority for prefetch tasks.\n */\n Default = 1,\n /**\n * Assigned to tasks when they spawn non-blocking background work, like\n * revalidating a partially cached entry to see if more data is available.\n */\n Background = 0,\n}\n\nexport const enum FetchStrategy {\n // Deliberately ordered so we can easily compare two segments\n // and determine if one segment is \"more specific\" than another\n // (i.e. if it's likely that it contains more data)\n LoadingBoundary = 0,\n PPR = 1,\n PPRRuntime = 2,\n Full = 3,\n}\n\n/**\n * A subset of fetch strategies used for prefetch tasks.\n * A prefetch task can't know if it should use `PPR` or `LoadingBoundary`\n * until we complete the initial tree prefetch request, so we use `PPR` to signal both cases\n * and adjust it based on the route when actually fetching.\n * */\nexport type PrefetchTaskFetchStrategy =\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full\n","// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque<K, T> = T & { __brand: K }\n\n// Only functions in this module should be allowed to create CacheKeys.\nexport type NormalizedPathname = Opaque<'NormalizedPathname', string>\nexport type NormalizedSearch = Opaque<'NormalizedSearch', string>\nexport type NormalizedNextUrl = Opaque<'NormalizedNextUrl', string>\n\nexport type RouteCacheKey = Opaque<\n 'RouteCacheKey',\n {\n pathname: NormalizedPathname\n search: NormalizedSearch\n nextUrl: NormalizedNextUrl | null\n\n // TODO: Eventually the dynamic params will be added here, too.\n }\n>\n\nexport function createCacheKey(\n originalHref: string,\n nextUrl: string | null\n): RouteCacheKey {\n const originalUrl = new URL(originalHref)\n const cacheKey = {\n pathname: originalUrl.pathname as NormalizedPathname,\n search: originalUrl.search as NormalizedSearch,\n nextUrl: nextUrl as NormalizedNextUrl | null,\n } as RouteCacheKey\n return cacheKey\n}\n","/**\n * App Router types - Client-safe types for the Next.js App Router\n *\n * This file contains type definitions that can be safely imported\n * by both client-side and server-side code without circular dependencies.\n */\n\nimport type React from 'react'\n\nexport type LoadingModuleData =\n | [React.JSX.Element, React.ReactNode, React.ReactNode]\n | null\n\nimport type { VaryParamsThenable } from './segment-cache/vary-params-decoding'\n\n/** viewport metadata node */\nexport type HeadData = React.ReactNode\n\n/**\n * Cache node used in app-router / layout-router.\n */\n\nexport type CacheNode = {\n /**\n * When rsc is not null, it represents the RSC data for the\n * corresponding segment.\n *\n * `null` is a valid React Node but because segment data is always a\n * <LayoutRouter> component, we can use `null` to represent empty. When it is\n * null, it represents missing data, and rendering should suspend.\n */\n rsc: React.ReactNode\n\n /**\n * Represents a static version of the segment that can be shown immediately,\n * and may or may not contain dynamic holes. It's prefetched before a\n * navigation occurs.\n *\n * During rendering, we will choose whether to render `rsc` or `prefetchRsc`\n * with `useDeferredValue`. As with the `rsc` field, a value of `null` means\n * no value was provided. In this case, the LayoutRouter will go straight to\n * rendering the `rsc` value; if that one is also missing, it will suspend and\n * trigger a lazy fetch.\n */\n prefetchRsc: React.ReactNode\n\n prefetchHead: HeadData | null\n\n head: HeadData\n\n slots: Record<string, CacheNode> | null\n\n /**\n * A shared mutable ref that tracks whether this segment should be scrolled\n * to. All new segments created during a single navigation share the same\n * ref. When any segment's scroll handler fires, it sets `current` to\n * `false` so no other segment scrolls for the same navigation.\n *\n * `null` means this segment is not a scroll target (e.g., a reused shared\n * layout segment).\n */\n scrollRef: ScrollRef | null\n}\n\n/**\n * A mutable ref shared across all new segments created during a single\n * navigation. Used to ensure that only one segment scrolls per navigation.\n */\nexport type ScrollRef = { current: boolean }\n\nexport type DynamicParamTypes =\n | 'catchall'\n | 'catchall-intercepted-(..)(..)'\n | 'catchall-intercepted-(.)'\n | 'catchall-intercepted-(..)'\n | 'catchall-intercepted-(...)'\n | 'optional-catchall'\n | 'dynamic'\n | 'dynamic-intercepted-(..)(..)'\n | 'dynamic-intercepted-(.)'\n | 'dynamic-intercepted-(..)'\n | 'dynamic-intercepted-(...)'\n\nexport type DynamicParamTypesShort =\n | 'c'\n | 'ci(..)(..)'\n | 'ci(.)'\n | 'ci(..)'\n | 'ci(...)'\n | 'oc'\n | 'd'\n | 'di(..)(..)'\n | 'di(.)'\n | 'di(..)'\n | 'di(...)'\n\n// The tuple form of a segment, used for dynamic route params\nexport type DynamicSegmentTuple = [\n // Param name\n paramName: string,\n // Param cache key (almost the same as the value, but arrays are\n // concatenated into strings)\n // TODO: We should change this to just be the value. Currently we convert\n // it back to a value when passing to useParams. It only needs to be\n // a string when converted to a a cache key, but that doesn't mean we\n // need to store it as that representation.\n paramCacheKey: string,\n // Dynamic param type\n dynamicParamType: DynamicParamTypesShort,\n // Static sibling segments at the same URL level. Used by the client\n // router to determine if a prefetch can be reused when navigating to\n // a static sibling of a dynamic route. For example, if the route is\n // /products/[id] and there's also /products/sale, then staticSiblings\n // would be ['sale']. null means the siblings are unknown (e.g. in\n // webpack dev mode).\n staticSiblings: readonly string[] | null,\n]\n\nexport type Segment = string | DynamicSegmentTuple\n\n/**\n * Router state\n */\nexport type FlightRouterState = [\n segment: Segment,\n parallelRoutes: { [parallelRouterKey: string]: FlightRouterState },\n refreshState?: CompressedRefreshState | null,\n /**\n * - \"refetch\" is used during a request to inform the server where rendering\n * should start from.\n *\n * - \"inside-shared-layout\" is used during a prefetch request to inform the\n * server that even if the segment matches, it should be treated as if it's\n * within the \"new\" part of a navigation — inside the shared layout. If\n * the segment doesn't match, then it has no effect, since it would be\n * treated as new regardless. If it does match, though, the server does not\n * need to render it, because the client already has it.\n *\n * - \"metadata-only\" instructs the server to skip rendering the segments and\n * only send the head data.\n *\n * A bit confusing, but that's because it has only one extremely narrow use\n * case — during a non-PPR prefetch, the server uses it to find the first\n * loading boundary beneath a shared layout.\n *\n * TODO: We should rethink the protocol for dynamic requests. It might not\n * make sense for the client to send a FlightRouterState, since this type is\n * overloaded with concerns.\n */\n refresh?: 'refetch' | 'inside-shared-layout' | 'metadata-only' | null,\n /**\n * Bitmask of PrefetchHint flags. Encodes route structure metadata:\n * root layout, loading boundaries, instant configs, and runtime prefetch\n * hints. Only set when non-zero.\n */\n prefetchHints?: number,\n]\n\n/**\n * When rendering a parallel route, some of the parallel paths may not match\n * the current URL. In that case, the Next client has to render something,\n * so it will render whichever was the last route to match that slot. We use\n * this type to track when this has happened. It's a tuple of the original\n * URL that was used to fetch the segment, and the (possibly rewritten) search\n * query that was rendered by the server. The URL is needed when performing\n * a refresh of the segment, and the search query is needed for looking up\n * matching entries in the segment cache.\n */\nexport type CompressedRefreshState = [url: string, renderedSearch: string]\n\nexport const enum PrefetchHint {\n // This segment has a runtime prefetch enabled (via unstable_instant with\n // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.\n HasRuntimePrefetch = 0b00001,\n // This segment or one of its descendants has an instant config defined\n // (any truthy unstable_instant, regardless of prefetch mode). Propagates\n // upward so the root segment reflects the entire subtree.\n SubtreeHasInstant = 0b00010,\n // This segment itself has a loading.tsx boundary.\n SegmentHasLoadingBoundary = 0b00100,\n // A descendant segment (but not this one) has a loading.tsx boundary.\n // Propagates upward so the root reflects the entire subtree.\n SubtreeHasLoadingBoundary = 0b01000,\n // This segment is the root layout of the application.\n IsRootLayout = 0b10000,\n // This segment's response includes its parent's data inlined into it.\n // Set at build time by the segment size measurement pass.\n ParentInlinedIntoSelf = 0b100000,\n // This segment's data is inlined into one of its children — don't fetch\n // it separately. Set at build time by the segment size measurement pass.\n InlinedIntoChild = 0b1000000,\n // On a __PAGE__: this page's response includes the head (metadata/viewport)\n // at the end of its SegmentPrefetch[] array.\n HeadInlinedIntoSelf = 0b10000000,\n // On the root hint node: the head was NOT inlined into any page — fetch\n // it separately. Absence of this bit means the head is bundled into a page.\n HeadOutlined = 0b100000000,\n}\n\n/**\n * Individual Flight response path\n */\nexport type FlightSegmentPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n segment: Segment,\n parallelRouterKey: string,\n ]\n\n/**\n * Represents a tree of segments and the Flight data (i.e. React nodes) that\n * correspond to each one. The tree is isomorphic to the FlightRouterState;\n * however in the future we want to be able to fetch arbitrary partial segments\n * without having to fetch all its children. So this response format will\n * likely change.\n */\nexport type CacheNodeSeedData = [\n node: React.ReactNode | null,\n parallelRoutes: {\n [parallelRouterKey: string]: CacheNodeSeedData | null\n },\n // TODO: This field is no longer used. Remove it.\n loading: null,\n isPartial: boolean,\n /**\n * A thenable that resolves to the set of route params this segment accessed\n * during server rendering. Used by the client router to determine cache key\n * specificity - segments that only access certain params can be reused across\n * navigations where unaccessed params change.\n *\n * - null thenable: tracking was not enabled for this render (e.g., not a\n * prerender). Treat conservatively - assume all params vary.\n * - Thenable resolves to empty Set: segment accesses no params (e.g., client\n * components, or server components that don't read params). Can be shared\n * across all param values.\n * - Thenable resolves to non-empty Set: segment depends on those params.\n * Can only reuse when those specific params match.\n */\n varyParams: VaryParamsThenable | null,\n]\n\nexport type FlightDataSegment = [\n /* segment of the rendered slice: */ Segment,\n /* treePatch */ FlightRouterState,\n /* cacheNodeSeedData */ CacheNodeSeedData | null, // Can be null during prefetch if there's no loading component\n /* head: viewport */ HeadData,\n /* isHeadPartial */ boolean,\n]\n\nexport type FlightDataPath =\n // Uses `any` as repeating pattern can't be typed.\n | any[]\n // Looks somewhat like this\n | [\n // Holds full path to the segment.\n ...FlightSegmentPath[],\n ...FlightDataSegment,\n ]\n\n/**\n * The Flight response data\n */\nexport type FlightData = Array<FlightDataPath> | string\n\n/**\n * Per-route prefetch hints computed at build time. Mirrors the shape of the\n * loader tree so hints can be traversed in parallel during router state\n * creation. Each node stores a bitmask of PrefetchHint flags\n * (ParentInlinedIntoSelf, InlinedIntoChild) computed by the segment size\n * measurement pass.\n *\n * Persisted to prefetch-hints.json as Record<string, PrefetchHints> (keyed\n * by route pattern) and loaded at server startup.\n */\nexport type PrefetchHints = {\n /** Bitmask of PrefetchHint flags for this segment. */\n hints: number\n /** Child hint nodes, keyed by parallel route key. */\n slots: Record<string, PrefetchHints> | null\n}\n\nexport type ActionResult = Promise<any>\n\nexport type InitialRSCPayload = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** initialCanonicalUrlParts */\n c: string[]\n /** initialRenderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** initialFlightData */\n f: FlightDataPath[]\n /** missingSlots */\n m: Set<string> | undefined\n /** GlobalError */\n G: [React.ComponentType<any>, React.ReactNode | undefined]\n /** supportsPerSegmentPrefetching */\n S: boolean\n /**\n * headVaryParams - vary params for the head (metadata) of the response.\n */\n h: VaryParamsThenable | null\n /** staleTime in seconds - Only present when Cache Components is enabled. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n}\n\n// Response from `createFromFetch` for normal rendering\nexport type NavigationFlightResponse = {\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** supportsPerSegmentPrefetching */\n S: boolean\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n /** staleTime - Only present in dynamic runtime prefetch responses. */\n s?: AsyncIterable<number>\n /** staticStageByteLength - Resolves when the static stage ends. */\n l?: Promise<number>\n /** headVaryParams */\n h: VaryParamsThenable | null\n /** runtimePrefetchStream — Embedded runtime prefetch Flight stream. */\n p?: ReadableStream<Uint8Array>\n /**\n * dynamicStaleTime — Per-page BFCache stale time in seconds, from\n * `unstable_dynamicStaleTime`. Only included for dynamic renders. Controls\n * how long the client router cache retains dynamic navigation data. This is\n * distinct from the `s` field, which controls segment cache (prefetch)\n * staleness.\n */\n d?: number\n}\n\n// Response from `createFromFetch` for server actions. Action's flight data can be null\nexport type ActionFlightResponse = {\n /** actionResult */\n a: ActionResult\n /** buildId, can be empty if the x-nextjs-build-id header is set */\n b?: string\n /** flightData */\n f: FlightData\n /** renderedSearch */\n q: string\n /** couldBeIntercepted */\n i: boolean\n}\n\nexport type RSCPayload =\n | InitialRSCPayload\n | NavigationFlightResponse\n | ActionFlightResponse\n","import type { Segment } from '../../shared/lib/app-router-types'\n\nexport const matchSegment = (\n existingSegment: Segment,\n segment: Segment\n): boolean => {\n // segment is either Array or string\n if (typeof existingSegment === 'string') {\n if (typeof segment === 'string') {\n // Common case: segment is just a string\n return existingSegment === segment\n }\n return false\n }\n\n if (typeof segment === 'string') {\n return false\n }\n return existingSegment[0] === segment[0] && existingSegment[1] === segment[1]\n}\n","/**\n * Vary Params Decoding\n *\n * This module is shared between server and client.\n */\n\nexport type VaryParams = Set<string>\n\ntype FulfilledVaryParamsThenable = {\n status: 'fulfilled'\n value: VaryParams\n} & PromiseLike<VaryParams>\n\ntype PendingVaryParamsThenable = {\n // 'resolved_model' is an internal React Flight state: the underlying model\n // data has arrived but the thenable hasn't been \"unwrapped\" yet. Calling\n // .then() triggers Flight to synchronously transition to 'fulfilled'.\n status: 'pending' | 'resolved_model'\n value: unknown\n} & PromiseLike<VaryParams>\n\nexport type VaryParamsThenable =\n | FulfilledVaryParamsThenable\n | PendingVaryParamsThenable\n\n/**\n * Synchronously reads vary params from a thenable.\n *\n * By the time this is called (client-side or in collectSegmentData), the\n * thenable should already be fulfilled because the Flight stream has been\n * fully received. We check the status synchronously to avoid unnecessary\n * microtasks.\n *\n * Returns null if the thenable is still pending (which shouldn't happen in\n * normal operation - it indicates the server failed to track vary params).\n */\nexport function readVaryParams(\n thenable: VaryParamsThenable\n): VaryParams | null {\n // Attach a no-op listener to force Flight to synchronously resolve the\n // thenable. When a thenable arrives from the Flight stream, it may be in an\n // intermediate 'resolved_model' state (data received but not unwrapped).\n // Calling .then() triggers Flight to transition it to 'fulfilled', making\n // the value available synchronously. React uses this same optimization\n // internally to avoid unnecessary microtasks.\n thenable.then(noop)\n // If the thenable is still not 'fulfilled' after calling .then(), the server\n // failed to resolve it before the stream ended. Treat as unknown.\n if (thenable.status !== 'fulfilled') {\n return null\n }\n return thenable.value\n}\n\nconst noop = () => {}\n","export const RSC_HEADER = 'rsc' as const\nexport const ACTION_HEADER = 'next-action' as const\n// TODO: Instead of sending the full router state, we only need to send the\n// segment path. Saves bytes. Then we could also use this field for segment\n// prefetches, which also need to specify a particular segment.\nexport const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree' as const\nexport const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const\n// This contains the path to the segment being prefetched.\n// TODO: If we change next-router-state-tree to be a segment path, we can use\n// that instead. Then next-router-prefetch and next-router-segment-prefetch can\n// be merged into a single enum.\nexport const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER =\n 'next-router-segment-prefetch' as const\nexport const NEXT_HMR_REFRESH_HEADER = 'next-hmr-refresh' as const\nexport const NEXT_HMR_REFRESH_HASH_COOKIE = '__next_hmr_refresh_hash__' as const\nexport const NEXT_URL = 'next-url' as const\nexport const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const\n\n// Header for the Instant Navigation Testing API. In development and testing\n// builds, static pre-renders normally don't happen. This header tells the\n// server to perform a static pre-render anyway, allowing tests to assert on\n// the prefetched UI. Not exposed in production builds by default.\nexport const NEXT_INSTANT_PREFETCH_HEADER =\n 'next-instant-navigation-testing-prefetch' as const\n\n// Cookie for the Instant Navigation Testing API. Used for MPA navigations\n// (page reload, full page load) where we can't set request headers. When set,\n// the server renders only the static shell. Not exposed in production builds\n// by default.\nexport const NEXT_INSTANT_TEST_COOKIE =\n 'next-instant-navigation-testing' as const\n\nexport const FLIGHT_HEADERS = [\n RSC_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n] as const\n\nexport const NEXT_RSC_UNION_QUERY = '_rsc' as const\n\nexport const NEXT_ROUTER_STALE_TIME_HEADER = 'x-nextjs-stale-time' as const\nexport const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed' as const\nexport const NEXT_REWRITTEN_PATH_HEADER = 'x-nextjs-rewritten-path' as const\nexport const NEXT_REWRITTEN_QUERY_HEADER = 'x-nextjs-rewritten-query' as const\nexport const NEXT_IS_PRERENDER_HEADER = 'x-nextjs-prerender' as const\nexport const NEXT_ACTION_NOT_FOUND_HEADER = 'x-nextjs-action-not-found' as const\nexport const NEXT_REQUEST_ID_HEADER = 'x-nextjs-request-id' as const\nexport const NEXT_HTML_REQUEST_ID_HEADER = 'x-nextjs-html-request-id' as const\n\n// TODO: Should this include nextjs in the name, like the others?\nexport const NEXT_ACTION_REVALIDATED_HEADER = 'x-action-revalidated' as const\n","export class InvariantError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(\n `Invariant: ${message.endsWith('.') ? message : message + '.'} This is a bug in Next.js.`,\n options\n )\n this.name = 'InvariantError'\n }\n}\n","/**\n * Check to see if a value is Thenable.\n *\n * @param promise the maybe-thenable value\n * @returns true if the value is thenable\n */\nexport function isThenable<T = unknown>(\n promise: Promise<T> | T\n): promise is Promise<T> {\n return (\n promise !== null &&\n typeof promise === 'object' &&\n 'then' in promise &&\n typeof promise.then === 'function'\n )\n}\n","import type { Dispatch } from 'react'\nimport React, { use, useMemo, useOptimistic } from 'react'\nimport { isThenable } from '../../shared/lib/is-thenable'\nimport type { AppRouterActionQueue } from './app-router-instance'\nimport {\n ACTION_REFRESH,\n type AppRouterState,\n type ReducerActions,\n type ReducerState,\n} from './router-reducer/router-reducer-types'\n\n// The app router state lives outside of React, so we can import the dispatch\n// method directly wherever we need it, rather than passing it around via props\n// or context.\nlet dispatch: Dispatch<ReducerActions> | null = null\n\n/**\n * Called when the instant navigation test lock is released. If the router\n * is initialized, dispatches a soft refresh to fetch dynamic data. If not\n * (e.g. the lock was released before hydration finished), falls back to a\n * hard reload.\n */\nexport function refreshOnInstantNavigationUnlock() {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n if (dispatch !== null) {\n dispatch({ type: ACTION_REFRESH, bypassCacheInvalidation: true })\n } else {\n window.location.reload()\n }\n }\n}\n\nexport function dispatchAppRouterAction(action: ReducerActions) {\n if (dispatch === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n dispatch(action)\n}\n\n// Optimistic state setter for experimental_gesturePush. Only should be used\n// during a gesture transition.\nlet setGestureRouterState: ((state: ReducerState) => void) | null = null\n\nexport function dispatchGestureState(state: ReducerState) {\n if (setGestureRouterState === null) {\n throw new Error(\n 'Internal Next.js error: Router action dispatched before initialization.'\n )\n }\n setGestureRouterState(state)\n}\n\nconst __DEV__ = process.env.NODE_ENV !== 'production'\nconst promisesWithDebugInfo: WeakMap<\n Promise<AppRouterState>,\n Promise<AppRouterState> & { _debugInfo?: Array<unknown> }\n> = __DEV__ ? new WeakMap() : (null as any)\n\nexport function useActionQueue(\n actionQueue: AppRouterActionQueue\n): AppRouterState {\n const [canonicalState, setState] = React.useState<ReducerState>(\n actionQueue.state\n )\n\n // Wrap the canonical state in useOptimistic to support\n // experimental_gesturePush. During a gesture transition, this returns a fork\n // of the router state that represents the eventual target if/when the gesture\n // completes. Otherwise it returns the canonical state.\n const [state, setGesture] = useOptimistic(canonicalState)\n if (typeof window !== 'undefined') {\n setGestureRouterState = setGesture\n }\n\n // Because of a known issue that requires to decode Flight streams inside the\n // render phase, we have to be a bit clever and assign the dispatch method to\n // a module-level variable upon initialization. The useState hook in this\n // module only exists to synchronize state that lives outside of React.\n // Ideally, what we'd do instead is pass the state as a prop to root.render;\n // this is conceptually how we're modeling the app router state, despite the\n // weird implementation details.\n let nextDispatch: Dispatch<ReducerActions>\n\n if (process.env.NODE_ENV !== 'production') {\n const { useAppDevRenderingIndicator } =\n require('../../next-devtools/userspace/use-app-dev-rendering-indicator') as typeof import('../../next-devtools/userspace/use-app-dev-rendering-indicator')\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const appDevRenderingIndicator = useAppDevRenderingIndicator()\n\n nextDispatch = (action: ReducerActions) => {\n appDevRenderingIndicator(() => {\n actionQueue.dispatch(action, setState)\n })\n }\n } else {\n nextDispatch = (action: ReducerActions) =>\n actionQueue.dispatch(action, setState)\n }\n\n if (typeof window !== 'undefined') {\n dispatch = nextDispatch\n }\n\n // When navigating to a non-prefetched route, then App Router state will be\n // blocked until the server responds. We need to transfer the `_debugInfo`\n // from the underlying Flight response onto the top-level promise that is\n // passed to React (via `use`) so that the latency is accurately represented\n // in the React DevTools.\n const stateWithDebugInfo = useMemo(() => {\n if (!__DEV__) {\n return state\n }\n\n if (isThenable(state)) {\n // useMemo can't be used to cache a Promise since the memoized value is thrown\n // away when we suspend. So we use a WeakMap to cache the Promise with debug info.\n let promiseWithDebugInfo = promisesWithDebugInfo.get(state)\n if (promiseWithDebugInfo === undefined) {\n const debugInfo: Array<unknown> = []\n promiseWithDebugInfo = Promise.resolve(state).then((asyncState) => {\n if (asyncState.debugInfo !== null) {\n debugInfo.push(...asyncState.debugInfo)\n }\n return asyncState\n }) as Promise<AppRouterState> & { _debugInfo?: Array<unknown> }\n promiseWithDebugInfo._debugInfo = debugInfo\n\n promisesWithDebugInfo.set(state, promiseWithDebugInfo)\n }\n\n return promiseWithDebugInfo\n }\n return state\n }, [state])\n\n return isThenable(stateWithDebugInfo)\n ? use(stateWithDebugInfo)\n : stateWithDebugInfo\n}\n","import { startTransition } from 'react'\nimport { ACTION_SERVER_ACTION } from './components/router-reducer/router-reducer-types'\nimport { dispatchAppRouterAction } from './components/use-action-queue'\n\nexport async function callServer(actionId: string, actionArgs: any[]) {\n return new Promise((resolve, reject) => {\n startTransition(() => {\n dispatchAppRouterAction({\n type: ACTION_SERVER_ACTION,\n actionId,\n actionArgs,\n resolve,\n reject,\n })\n })\n })\n}\n","const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''\nconst pathname = `${basePath}/__nextjs_source-map`\n\nexport const findSourceMapURL =\n // Source maps are only served by the dev server.\n process.env.__NEXT_DEV_SERVER\n ? function findSourceMapURL(filename: string): string | null {\n if (filename === '') {\n return null\n }\n\n if (\n filename.startsWith(document.location.origin) &&\n filename.includes('/_next/static')\n ) {\n // This is a request for a client chunk. This can only happen when\n // using Turbopack. In this case, since we control how those source\n // maps are generated, we can safely assume that the sourceMappingURL\n // is relative to the filename, with an added `.map` extension. The\n // browser can just request this file, and it gets served through the\n // normal dev server, without the need to route this through\n // the `/__nextjs_source-map` dev middleware.\n return `${filename}.map`\n }\n\n const url = new URL(pathname, document.location.origin)\n url.searchParams.set('filename', filename)\n\n return url.href\n }\n : undefined\n","import type { FlightRouterState, Segment } from './app-router-types'\n\nexport function getSegmentValue(segment: Segment) {\n return Array.isArray(segment) ? segment[1] : segment\n}\n\nexport function isGroupSegment(segment: string) {\n // Use array[0] for performant purpose\n return segment[0] === '(' && segment.endsWith(')')\n}\n\nexport function isParallelRouteSegment(segment: string) {\n return segment.startsWith('@') && segment !== '@children'\n}\n\nexport function addSearchParamsIfPageSegment(\n segment: Segment,\n searchParams: Record<string, string | string[] | undefined>\n) {\n const isPageSegment = segment.includes(PAGE_SEGMENT_KEY)\n\n if (isPageSegment) {\n const stringifiedQuery = JSON.stringify(searchParams)\n return stringifiedQuery !== '{}'\n ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery\n : PAGE_SEGMENT_KEY\n }\n\n return segment\n}\n\nexport function computeSelectedLayoutSegment(\n segments: string[] | null,\n parallelRouteKey: string\n): string | null {\n if (!segments || segments.length === 0) {\n return null\n }\n\n // For 'children', use first segment; for other parallel routes, use last segment\n const rawSegment =\n parallelRouteKey === 'children'\n ? segments[0]\n : segments[segments.length - 1]\n\n // If the default slot is showing, return null since it's not technically \"selected\" (it's a fallback)\n // Returning an internal value like `__DEFAULT__` would be confusing\n return rawSegment === DEFAULT_SEGMENT_KEY ? null : rawSegment\n}\n\n/** Get the canonical parameters from the current level to the leaf node. */\nexport function getSelectedLayoutSegmentPath(\n tree: FlightRouterState,\n parallelRouteKey: string,\n first = true,\n segmentPath: string[] = []\n): string[] {\n let node: FlightRouterState\n if (first) {\n // Use the provided parallel route key on the first parallel route\n node = tree[1][parallelRouteKey]\n } else {\n // After first parallel route prefer children, if there's no children pick the first parallel route.\n const parallelRoutes = tree[1]\n node = parallelRoutes.children ?? Object.values(parallelRoutes)[0]\n }\n\n if (!node) return segmentPath\n const segment = node[0]\n\n let segmentValue = getSegmentValue(segment)\n\n if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) {\n return segmentPath\n }\n\n segmentPath.push(segmentValue)\n\n return getSelectedLayoutSegmentPath(\n node,\n parallelRouteKey,\n false,\n segmentPath\n )\n}\n\nexport const PAGE_SEGMENT_KEY = '__PAGE__'\nexport const DEFAULT_SEGMENT_KEY = '__DEFAULT__'\nexport const NOT_FOUND_SEGMENT_KEY = '/_not-found'\n","import { PAGE_SEGMENT_KEY } from '../segment'\nimport type { Segment as FlightRouterStateSegment } from '../app-router-types'\n\n// TypeScript trick to simulate opaque types, like in Flow.\ntype Opaque<K, T> = T & { __brand: K }\n\nexport type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string>\nexport type SegmentRequestKey = Opaque<'SegmentRequestKey', string>\n\nexport const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey\n\nexport const HEAD_REQUEST_KEY = '/_head' as SegmentRequestKey\n\nexport function createSegmentRequestKeyPart(\n segment: FlightRouterStateSegment\n): SegmentRequestKeyPart {\n if (typeof segment === 'string') {\n if (segment.startsWith(PAGE_SEGMENT_KEY)) {\n // The Flight Router State type sometimes includes the search params in\n // the page segment. However, the Segment Cache tracks this as a separate\n // key. So, we strip the search params here, and then add them back when\n // the cache entry is turned back into a FlightRouterState. This is an\n // unfortunate consequence of the FlightRouteState being used both as a\n // transport type and as a cache key; we'll address this once more of the\n // Segment Cache implementation has settled.\n // TODO: We should hoist the search params out of the FlightRouterState\n // type entirely, This is our plan for dynamic route params, too.\n return PAGE_SEGMENT_KEY as SegmentRequestKeyPart\n }\n const safeName =\n // TODO: FlightRouterState encodes Not Found routes as \"/_not-found\".\n // But params typically don't include the leading slash. We should use\n // a different encoding to avoid this special case.\n segment === '/_not-found'\n ? '_not-found'\n : encodeToFilesystemAndURLSafeString(segment)\n // Since this is not a dynamic segment, it's fully encoded. It does not\n // need to be \"hydrated\" with a param value.\n return safeName as SegmentRequestKeyPart\n }\n\n const name = segment[0]\n const paramType = segment[2]\n const safeName = encodeToFilesystemAndURLSafeString(name)\n\n const encodedName = '$' + paramType + '$' + safeName\n return encodedName as SegmentRequestKeyPart\n}\n\nexport function appendSegmentRequestKeyPart(\n parentRequestKey: SegmentRequestKey,\n parallelRouteKey: string,\n childRequestKeyPart: SegmentRequestKeyPart\n): SegmentRequestKey {\n // Aside from being filesystem safe, segment keys are also designed so that\n // each segment and parallel route creates its own subdirectory. Roughly in\n // the same shape as the source app directory. This is mostly just for easier\n // debugging (you can open up the build folder and navigate the output); if\n // we wanted to do we could just use a flat structure.\n\n // Omit the parallel route key for children, since this is the most\n // common case. Saves some bytes (and it's what the app directory does).\n const slotKey =\n parallelRouteKey === 'children'\n ? childRequestKeyPart\n : `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`\n return (parentRequestKey + '/' + slotKey) as SegmentRequestKey\n}\n\n// Define a regex pattern to match the most common characters found in a route\n// param. It excludes anything that might not be cross-platform filesystem\n// compatible, like |. It does not need to be precise because the fallback is to\n// just base64url-encode the whole parameter, which is fine; we just don't do it\n// by default for compactness, and for easier debugging.\nconst simpleParamValueRegex = /^[a-zA-Z0-9\\-_@]+$/\n\nfunction encodeToFilesystemAndURLSafeString(value: string) {\n if (simpleParamValueRegex.test(value)) {\n return value\n }\n // If there are any unsafe characters, base64url-encode the entire value.\n // We also add a ! prefix so it doesn't collide with the simple case.\n const base64url = btoa(value)\n .replace(/\\+/g, '-') // Replace '+' with '-'\n .replace(/\\//g, '_') // Replace '/' with '_'\n .replace(/=+$/, '') // Remove trailing '='\n return '!' + base64url\n}\n\nexport function convertSegmentPathToStaticExportFilename(\n segmentPath: string\n): string {\n return `__next${segmentPath.replace(/\\//g, '.')}.txt`\n}\n","import type { DynamicParamTypesShort } from '../shared/lib/app-router-types'\nimport {\n addSearchParamsIfPageSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../shared/lib/segment'\nimport { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'\nimport {\n NEXT_REWRITTEN_PATH_HEADER,\n NEXT_REWRITTEN_QUERY_HEADER,\n NEXT_RSC_UNION_QUERY,\n} from './components/app-router-headers'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n} from './components/segment-cache/cache-key'\nimport type { RSCResponse } from './components/router-reducer/fetch-server-response'\nimport type { ParsedUrlQuery } from 'querystring'\n\nexport type RouteParamValue = string | Array<string> | null\n\nexport function getRenderedSearch(\n response: RSCResponse<unknown> | Response\n): NormalizedSearch {\n // If the server performed a rewrite, the search params used to render the\n // page will be different from the params in the request URL. In this case,\n // the response will include a header that gives the rewritten search query.\n const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)\n if (rewrittenQuery !== null) {\n return (\n rewrittenQuery === '' ? '' : '?' + rewrittenQuery\n ) as NormalizedSearch\n }\n // If the header is not present, there was no rewrite, so we use the search\n // query of the response URL.\n return urlToUrlWithoutFlightMarker(new URL(response.url))\n .search as NormalizedSearch\n}\n\nexport function getRenderedPathname(\n response: RSCResponse<unknown> | Response\n): NormalizedPathname {\n // If the server performed a rewrite, the pathname used to render the\n // page will be different from the pathname in the request URL. In this case,\n // the response will include a header that gives the rewritten pathname.\n const rewrittenPath = response.headers.get(NEXT_REWRITTEN_PATH_HEADER)\n return (rewrittenPath ??\n urlToUrlWithoutFlightMarker(new URL(response.url))\n .pathname) as NormalizedPathname\n}\n\nexport function parseDynamicParamFromURLPart(\n paramType: DynamicParamTypesShort,\n pathnameParts: Array<string>,\n partIndex: number\n): RouteParamValue {\n // This needs to match the behavior in get-dynamic-param.ts.\n switch (paramType) {\n // Catchalls\n case 'c': {\n // Catchalls receive all the remaining URL parts. If there are no\n // remaining pathname parts, return an empty array.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => encodeURIComponent(s))\n : []\n }\n // Catchall intercepted\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)': {\n const prefix = paramType.length - 2\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s, i) => {\n if (i === 0) {\n return encodeURIComponent(s.slice(prefix))\n }\n\n return encodeURIComponent(s)\n })\n : []\n }\n // Optional catchalls\n case 'oc': {\n // Optional catchalls receive all the remaining URL parts, unless this is\n // the end of the pathname, in which case they return null.\n return partIndex < pathnameParts.length\n ? pathnameParts.slice(partIndex).map((s) => encodeURIComponent(s))\n : null\n }\n // Dynamic\n case 'd': {\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n return encodeURIComponent(pathnameParts[partIndex])\n }\n // Dynamic intercepted\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)': {\n const prefix = paramType.length - 2\n if (partIndex >= pathnameParts.length) {\n // The route tree expected there to be more parts in the URL than there\n // actually are. This could happen if the x-nextjs-rewritten-path header\n // is incorrectly set, or potentially due to bug in Next.js. TODO:\n // Should this be a hard error? During a prefetch, we can just abort.\n // During a client navigation, we could trigger a hard refresh. But if\n // it happens during initial render, we don't really have any\n // recovery options.\n return ''\n }\n\n return encodeURIComponent(pathnameParts[partIndex].slice(prefix))\n }\n default:\n paramType satisfies never\n return ''\n }\n}\n\nexport function doesStaticSegmentAppearInURL(segment: string): boolean {\n // This is not a parameterized segment; however, we need to determine\n // whether or not this segment appears in the URL. For example, this route\n // groups do not appear in the URL, so they should be skipped. Any other\n // special cases must be handled here.\n // TODO: Consider encoding this directly into the router tree instead of\n // inferring it on the client based on the segment type. Something like\n // a `doesAppearInURL` flag in FlightRouterState.\n if (\n segment === ROOT_SEGMENT_REQUEST_KEY ||\n // For some reason, the loader tree sometimes includes extra __PAGE__\n // \"layouts\" when part of a parallel route. But it's not a leaf node.\n // Otherwise, we wouldn't need this special case because pages are\n // always leaf nodes.\n // TODO: Investigate why the loader produces these fake page segments.\n segment.startsWith(PAGE_SEGMENT_KEY) ||\n // Route groups.\n (segment[0] === '(' && segment.endsWith(')')) ||\n segment === DEFAULT_SEGMENT_KEY ||\n segment === '/_not-found'\n ) {\n return false\n } else {\n // All other segment types appear in the URL\n return true\n }\n}\n\nexport function getCacheKeyForDynamicParam(\n paramValue: RouteParamValue,\n renderedSearch: NormalizedSearch\n): string {\n // This needs to match the logic in get-dynamic-param.ts, until we're able to\n // unify the various implementations so that these are always computed on\n // the client.\n if (typeof paramValue === 'string') {\n // TODO: Refactor or remove this helper function to accept a string rather\n // than the whole segment type. Also we can probably just append the\n // search string instead of turning it into JSON.\n const pageSegmentWithSearchParams = addSearchParamsIfPageSegment(\n paramValue,\n Object.fromEntries(new URLSearchParams(renderedSearch))\n ) as string\n return pageSegmentWithSearchParams\n } else if (paramValue === null) {\n return ''\n } else {\n return paramValue.join('/')\n }\n}\n\nexport function urlToUrlWithoutFlightMarker(url: URL): URL {\n const urlWithoutFlightParameters = new URL(url)\n urlWithoutFlightParameters.searchParams.delete(NEXT_RSC_UNION_QUERY)\n if (process.env.NODE_ENV === 'production') {\n if (\n process.env.__NEXT_CONFIG_OUTPUT === 'export' &&\n urlWithoutFlightParameters.pathname.endsWith('.txt')\n ) {\n const { pathname } = urlWithoutFlightParameters\n const length = pathname.endsWith('/index.txt') ? 10 : 4\n // Slice off `/index.txt` or `.txt` from the end of the pathname\n urlWithoutFlightParameters.pathname = pathname.slice(0, -length)\n }\n }\n return urlWithoutFlightParameters\n}\n\nexport function getParamValueFromCacheKey(\n paramCacheKey: string,\n paramType: DynamicParamTypesShort\n) {\n // Turn the cache key string sent by the server (as part of FlightRouterState)\n // into a value that can be passed to `useParams` and client components.\n const isCatchAll = paramType === 'c' || paramType === 'oc'\n if (isCatchAll) {\n // Catch-all param keys are a concatenation of the path segments.\n // See equivalent logic in `getSelectedParams`.\n // TODO: We should just pass the array directly, rather than concatenate\n // it to a string and then split it back to an array. It needs to be an\n // array in some places, like when passing a key React, but we can convert\n // it at runtime in those places.\n return paramCacheKey.split('/')\n }\n return paramCacheKey\n}\n\nexport function urlSearchParamsToParsedUrlQuery(\n searchParams: URLSearchParams\n): ParsedUrlQuery {\n // Converts a URLSearchParams object to the same type used by the server when\n // creating search params props, i.e. the type returned by Node's\n // \"querystring\" module.\n const result: ParsedUrlQuery = {}\n for (const [key, value] of searchParams.entries()) {\n if (result[key] === undefined) {\n result[key] = value\n } else if (Array.isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [result[key], value]\n }\n }\n return result\n}\n","export function createHrefFromUrl(\n url: Pick<URL, 'pathname' | 'search' | 'hash'>,\n includeHash: boolean = true\n): string {\n return url.pathname + url.search + (includeHash ? url.hash : '')\n}\n","import type {\n CacheNodeSeedData,\n FlightData,\n FlightDataPath,\n FlightRouterState,\n FlightSegmentPath,\n Segment,\n HeadData,\n InitialRSCPayload,\n} from '../shared/lib/app-router-types'\nimport { PAGE_SEGMENT_KEY } from '../shared/lib/segment'\nimport type { NormalizedSearch } from './components/segment-cache/cache-key'\nimport {\n getCacheKeyForDynamicParam,\n parseDynamicParamFromURLPart,\n doesStaticSegmentAppearInURL,\n getRenderedPathname,\n getRenderedSearch,\n} from './route-params'\nimport { createHrefFromUrl } from './components/router-reducer/create-href-from-url'\n\nexport type NormalizedFlightData = {\n /**\n * The full `FlightSegmentPath` inclusive of the final `Segment`\n */\n segmentPath: FlightSegmentPath\n /**\n * The `FlightSegmentPath` exclusive of the final `Segment`\n */\n pathToSegment: FlightSegmentPath\n segment: Segment\n tree: FlightRouterState\n seedData: CacheNodeSeedData | null\n head: HeadData\n isHeadPartial: boolean\n isRootRender: boolean\n}\n\n// TODO: We should only have to export `normalizeFlightData`, however because the initial flight data\n// that gets passed to `createInitialRouterState` doesn't conform to the `FlightDataPath` type (it's missing the root segment)\n// we're currently exporting it so we can use it directly. This should be fixed as part of the unification of\n// the different ways we express `FlightSegmentPath`.\nexport function getFlightDataPartsFromPath(\n flightDataPath: FlightDataPath\n): NormalizedFlightData {\n // Pick the last 4 items from the `FlightDataPath` to get the [tree, seedData, viewport, isHeadPartial].\n const flightDataPathLength = 4\n // tree, seedData, and head are *always* the last three items in the `FlightDataPath`.\n const [tree, seedData, head, isHeadPartial] =\n flightDataPath.slice(-flightDataPathLength)\n // The `FlightSegmentPath` is everything except the last three items. For a root render, it won't be present.\n const segmentPath = flightDataPath.slice(0, -flightDataPathLength)\n\n return {\n // TODO: Unify these two segment path helpers. We are inconsistently pushing an empty segment (\"\")\n // to the start of the segment path in some places which makes it hard to use solely the segment path.\n // Look for \"// TODO-APP: remove ''\" in the codebase.\n pathToSegment: segmentPath.slice(0, -1),\n segmentPath,\n // if the `FlightDataPath` corresponds with the root, there'll be no segment path,\n // in which case we default to ''.\n segment: segmentPath[segmentPath.length - 1] ?? '',\n tree,\n seedData,\n head,\n isHeadPartial,\n isRootRender: flightDataPath.length === flightDataPathLength,\n }\n}\n\nexport function createInitialRSCPayloadFromFallbackPrerender(\n response: Response,\n fallbackInitialRSCPayload: InitialRSCPayload\n): InitialRSCPayload {\n // This is a static fallback page. In order to hydrate the page, we need to\n // parse the client params from the URL, but to account for the possibility\n // that the page was rewritten, we need to check the response headers\n // for x-nextjs-rewritten-path or x-nextjs-rewritten-query headers. Since\n // we can't access the headers of the initial document response, the client\n // performs a fetch request to the current location. Since it's possible that\n // the fetch request will be dynamically rewritten to a different path than\n // the initial document, this fetch request delivers _all_ the hydration data\n // for the page; it was not inlined into the document, like it normally\n // would be.\n //\n // TODO: Consider treating the case where fetch is rewritten to a different\n // path from the document as a special deopt case. We should optimistically\n // assume this won't happen, inline the data into the document, and perform\n // a minimal request (like a HEAD or range request) to verify that the\n // response matches. Tricky to get right because we need to account for\n // all the different deployment environments we support, like output:\n // \"export\" mode, where we currently don't assume that custom response\n // headers are present.\n\n // Patch the Flight data sent by the server with the correct params parsed\n // from the URL + response object.\n const renderedPathname = getRenderedPathname(response)\n const renderedSearch = getRenderedSearch(response)\n const canonicalUrl = createHrefFromUrl(new URL(location.href))\n const originalFlightDataPath = fallbackInitialRSCPayload.f[0]\n const originalFlightRouterState = originalFlightDataPath[0]\n const payload: InitialRSCPayload = {\n c: canonicalUrl.split('/'),\n q: renderedSearch,\n i: fallbackInitialRSCPayload.i,\n f: [\n [\n fillInFallbackFlightRouterState(\n originalFlightRouterState,\n renderedPathname,\n renderedSearch as NormalizedSearch\n ),\n originalFlightDataPath[1],\n originalFlightDataPath[2],\n originalFlightDataPath[2],\n ],\n ],\n m: fallbackInitialRSCPayload.m,\n G: fallbackInitialRSCPayload.G,\n S: fallbackInitialRSCPayload.S,\n h: fallbackInitialRSCPayload.h,\n }\n if (fallbackInitialRSCPayload.b) {\n payload.b = fallbackInitialRSCPayload.b\n }\n return payload\n}\n\nfunction fillInFallbackFlightRouterState(\n flightRouterState: FlightRouterState,\n renderedPathname: string,\n renderedSearch: NormalizedSearch\n): FlightRouterState {\n const pathnameParts = renderedPathname.split('/').filter((p) => p !== '')\n const index = 0\n return fillInFallbackFlightRouterStateImpl(\n flightRouterState,\n renderedSearch,\n pathnameParts,\n index\n )\n}\n\nfunction fillInFallbackFlightRouterStateImpl(\n flightRouterState: FlightRouterState,\n renderedSearch: NormalizedSearch,\n pathnameParts: Array<string>,\n pathnamePartsIndex: number\n): FlightRouterState {\n const originalSegment = flightRouterState[0]\n let newSegment: Segment\n let doesAppearInURL: boolean\n if (typeof originalSegment === 'string') {\n newSegment = originalSegment\n doesAppearInURL = doesStaticSegmentAppearInURL(originalSegment)\n } else {\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const paramValue = parseDynamicParamFromURLPart(\n paramType,\n pathnameParts,\n pathnamePartsIndex\n )\n const cacheKey = getCacheKeyForDynamicParam(paramValue, renderedSearch)\n newSegment = [paramName, cacheKey, paramType, staticSiblings]\n doesAppearInURL = true\n }\n\n // Only increment the index if the segment appears in the URL. If it's a\n // \"virtual\" segment, like a route group, it remains the same.\n const childPathnamePartsIndex = doesAppearInURL\n ? pathnamePartsIndex + 1\n : pathnamePartsIndex\n\n const children = flightRouterState[1]\n const newChildren: { [key: string]: FlightRouterState } = {}\n for (let key in children) {\n const childFlightRouterState = children[key]\n newChildren[key] = fillInFallbackFlightRouterStateImpl(\n childFlightRouterState,\n renderedSearch,\n pathnameParts,\n childPathnamePartsIndex\n )\n }\n\n const newState: FlightRouterState = [\n newSegment,\n newChildren,\n null,\n flightRouterState[3],\n flightRouterState[4],\n ]\n return newState\n}\n\nexport function getNextFlightSegmentPath(\n flightSegmentPath: FlightSegmentPath\n): FlightSegmentPath {\n // Since `FlightSegmentPath` is a repeated tuple of `Segment` and `ParallelRouteKey`, we slice off two items\n // to get the next segment path.\n return flightSegmentPath.slice(2)\n}\n\nexport function normalizeFlightData(\n flightData: FlightData\n): NormalizedFlightData[] | string {\n // FlightData can be a string when the server didn't respond with a proper flight response,\n // or when a redirect happens, to signal to the client that it needs to perform an MPA navigation.\n if (typeof flightData === 'string') {\n return flightData\n }\n\n return flightData.map((flightDataPath) =>\n getFlightDataPartsFromPath(flightDataPath)\n )\n}\n\n/**\n * This function is used to prepare the flight router state for the request.\n * It removes markers that are not needed by the server, and are purely used\n * for stashing state on the client.\n * @param flightRouterState - The flight router state to prepare.\n * @param isHmrRefresh - Whether this is an HMR refresh request.\n * @returns The prepared flight router state.\n */\nexport function prepareFlightRouterStateForRequest(\n flightRouterState: FlightRouterState,\n isHmrRefresh?: boolean\n): string {\n // HMR requests need the complete, unmodified state for proper functionality\n if (isHmrRefresh) {\n return encodeURIComponent(JSON.stringify(flightRouterState))\n }\n\n return encodeURIComponent(\n JSON.stringify(stripClientOnlyDataFromFlightRouterState(flightRouterState))\n )\n}\n\n/**\n * Recursively strips client-only data from FlightRouterState while preserving\n * server-needed information for proper rendering decisions.\n */\nfunction stripClientOnlyDataFromFlightRouterState(\n flightRouterState: FlightRouterState\n): FlightRouterState {\n const [\n segment,\n parallelRoutes,\n _refreshState, // Intentionally unused - URLs are client-only\n refreshMarker,\n prefetchHints,\n ] = flightRouterState\n\n // Strip client-only data from the segment\n const cleanedSegment = stripClientOnlyDataFromSegment(segment)\n\n // Recursively process parallel routes\n const cleanedParallelRoutes: { [key: string]: FlightRouterState } = {}\n for (const [key, childState] of Object.entries(parallelRoutes)) {\n cleanedParallelRoutes[key] =\n stripClientOnlyDataFromFlightRouterState(childState)\n }\n\n const result: FlightRouterState = [cleanedSegment, cleanedParallelRoutes]\n if (refreshMarker) {\n result[2] = null // null slightly more compact than undefined\n result[3] = refreshMarker\n }\n\n // Append optional fields if present\n if (prefetchHints !== undefined) {\n result[4] = prefetchHints\n }\n\n // Everything else is used only by the client and is not needed for requests.\n return result\n}\n\n/**\n * Strips client-only data from segments:\n * - Search parameters from __PAGE__ segments\n * - staticSiblings from dynamic segment tuples (only needed for client-side\n * prefetch reuse decisions)\n */\nfunction stripClientOnlyDataFromSegment(segment: Segment): Segment {\n if (typeof segment === 'string') {\n // Strip search params from __PAGE__ segments\n if (segment.startsWith(PAGE_SEGMENT_KEY + '?')) {\n return PAGE_SEGMENT_KEY\n }\n return segment\n }\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n // Strip staticSiblings (4th element) since server doesn't need it\n const [paramName, paramCacheKey, paramType] = segment\n return [paramName, paramCacheKey, paramType, null]\n}\n","// http://www.cse.yorku.ca/~oz/hash.html\n// More specifically, 32-bit hash via djbxor\n// (ref: https://gist.github.com/eplawless/52813b1d8ad9af510d85?permalink_comment_id=3367765#gistcomment-3367765)\n// This is due to number type differences between rust for turbopack to js number types,\n// where rust does not have easy way to repreesnt js's 53-bit float number type for the matching\n// overflow behavior. This is more `correct` in terms of having canonical hash across different runtime / implementation\n// as can gaurantee determinstic output from 32bit hash.\nexport function djb2Hash(str: string) {\n let hash = 5381\n for (let i = 0; i < str.length; i++) {\n const char = str.charCodeAt(i)\n hash = ((hash << 5) + hash + char) & 0xffffffff\n }\n return hash >>> 0\n}\n\nexport function hexHash(str: string) {\n return djb2Hash(str).toString(36).slice(0, 5)\n}\n","import { hexHash } from '../../hash'\n\nexport function computeCacheBustingSearchParam(\n prefetchHeader: '1' | '2' | '0' | undefined,\n segmentPrefetchHeader: string | string[] | undefined,\n stateTreeHeader: string | string[] | undefined,\n nextUrlHeader: string | string[] | undefined\n): string {\n if (\n (prefetchHeader === undefined || prefetchHeader === '0') &&\n segmentPrefetchHeader === undefined &&\n stateTreeHeader === undefined &&\n nextUrlHeader === undefined\n ) {\n return ''\n }\n return hexHash(\n [\n prefetchHeader || '0',\n segmentPrefetchHeader || '0',\n stateTreeHeader || '0',\n nextUrlHeader || '0',\n ].join(',')\n )\n}\n","'use client'\n\nimport { computeCacheBustingSearchParam } from '../../../shared/lib/router/utils/cache-busting-search-param'\nimport {\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n NEXT_RSC_UNION_QUERY,\n} from '../app-router-headers'\nimport type { RequestHeaders } from './fetch-server-response'\n\n/**\n * Mutates the provided URL by adding a cache-busting search parameter for CDNs that don't\n * support custom headers. This helps avoid caching conflicts by making each request unique.\n *\n * Rather than relying on the Vary header which some CDNs ignore, we append a search param\n * to create a unique URL that forces a fresh request.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * Note: This function mutates the input URL directly and does not return anything.\n *\n * TODO: Since we need to use a search param anyway, we could simplify by removing the custom\n * headers approach entirely and just use search params.\n */\nexport const setCacheBustingSearchParam = (\n url: URL,\n headers: RequestHeaders\n): void => {\n const uniqueCacheKey = computeCacheBustingSearchParam(\n headers[NEXT_ROUTER_PREFETCH_HEADER],\n headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER],\n headers[NEXT_ROUTER_STATE_TREE_HEADER],\n headers[NEXT_URL]\n )\n setCacheBustingSearchParamWithHash(url, uniqueCacheKey)\n}\n\n/**\n * Sets a cache-busting search parameter on a URL using a provided hash value.\n *\n * This function performs the same logic as `setCacheBustingSearchParam` but accepts\n * a pre-computed hash instead of computing it from headers.\n *\n * Example:\n * URL before: https://example.com/path?query=1\n * hash: \"abc123\"\n * URL after: https://example.com/path?query=1&_rsc=abc123\n *\n * If the hash is null, we will set `_rsc` search param without a value.\n * Like this: https://example.com/path?query=1&_rsc\n *\n * Note: This function mutates the input URL directly and does not return anything.\n */\nexport const setCacheBustingSearchParamWithHash = (\n url: URL,\n hash: string\n): void => {\n /**\n * Note that we intentionally do not use `url.searchParams.set` here:\n *\n * const url = new URL('https://example.com/search?q=custom%20spacing');\n * url.searchParams.set('_rsc', 'abc123');\n * console.log(url.toString()); // Outputs: https://example.com/search?q=custom+spacing&_rsc=abc123\n * ^ <--- this is causing confusion\n * This is in fact intended based on https://url.spec.whatwg.org/#interface-urlsearchparams, but\n * we want to preserve the %20 as %20 if that's what the user passed in, hence the custom\n * logic below.\n */\n const existingSearch = url.search\n const rawQuery = existingSearch.startsWith('?')\n ? existingSearch.slice(1)\n : existingSearch\n\n // Always remove any existing cache busting param and add a fresh one to ensure\n // we have the correct value based on current request headers\n const pairs = rawQuery\n .split('&')\n .filter((pair) => pair && !pair.startsWith(`${NEXT_RSC_UNION_QUERY}=`))\n\n if (hash.length > 0) {\n pairs.push(`${NEXT_RSC_UNION_QUERY}=${hash}`)\n } else {\n pairs.push(`${NEXT_RSC_UNION_QUERY}`)\n }\n url.search = pairs.length ? `?${pairs.join('&')}` : ''\n}\n","let deploymentId: string | undefined\n\nif (typeof window !== 'undefined') {\n deploymentId = document.documentElement.dataset.dplId\n // Immediately remove the attribute to prevent hydration errors (the dplId was inserted into the\n // HTML only), React isn't aware of it at all.\n delete document.documentElement.dataset.dplId\n} else {\n // Client side: replaced with globalThis.NEXT_DEPLOYMENT_ID\n // Server side: left as is or replaced with a string or replaced with false\n deploymentId = process.env.NEXT_DEPLOYMENT_ID || undefined\n}\n\nexport function getDeploymentId(): string | undefined {\n return deploymentId\n}\n\nexport function getDeploymentIdQuery(ampersand = false): string {\n let id = getDeploymentId()\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`\n }\n return ''\n}\n\nexport function getAssetToken(): string | undefined {\n return (\n process.env.NEXT_IMMUTABLE_ASSET_TOKEN || process.env.NEXT_DEPLOYMENT_ID\n )\n}\n\nexport function getAssetTokenQuery(ampersand = false): string {\n let id = getAssetToken()\n if (id) {\n return `${ampersand ? '&' : '?'}dpl=${id}`\n }\n return ''\n}\n","// This gets assigned as a side-effect during app initialization. Because it\n// represents the build used to create the JS bundle, it should never change\n// after being set, so we store it in a global variable.\n//\n// When performing RSC requests, if the incoming data has a different build ID,\n// we perform an MPA navigation/refresh to load the updated build and ensure\n// that the client and server in sync.\n//\n// Starts as an empty string. In practice, because setNavigationBuildId is called during initialization\n// before hydration starts, this will always get reassigned to the actual ID before it's ever needed\n// by a navigation. If for some reasons it didn't, due to a bug or race condition, then on\n// navigation the build comparision would fail and trigger an MPA navigation.\n//\n// Note that this can also be initialized with the deployment id instead (if available). So it's not\n// the same as \"the build id\", but we are running out of alternative names for \"build id or\n// deployment id\".\nlet globalBuildId: string = ''\n\nexport function setNavigationBuildId(buildId: string) {\n globalBuildId = buildId\n}\n\nexport function getNavigationBuildId(): string {\n return globalBuildId\n}\n","import type { ServerRuntime } from '../types'\n\nexport const TEXT_PLAIN_CONTENT_TYPE_HEADER = 'text/plain'\nexport const HTML_CONTENT_TYPE_HEADER = 'text/html; charset=utf-8'\nexport const JSON_CONTENT_TYPE_HEADER = 'application/json; charset=utf-8'\nexport const NEXT_QUERY_PARAM_PREFIX = 'nxtP'\nexport const NEXT_INTERCEPTION_MARKER_PREFIX = 'nxtI'\n\nexport const MATCHED_PATH_HEADER = 'x-matched-path'\nexport const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'\nexport const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =\n 'x-prerender-revalidate-if-generated'\n\nexport const RSC_SEGMENTS_DIR_SUFFIX = '.segments'\nexport const RSC_SEGMENT_SUFFIX = '.segment.rsc'\nexport const RSC_SUFFIX = '.rsc'\nexport const ACTION_SUFFIX = '.action'\nexport const NEXT_DATA_SUFFIX = '.json'\nexport const NEXT_META_SUFFIX = '.meta'\nexport const NEXT_BODY_SUFFIX = '.body'\n\nexport const NEXT_NAV_DEPLOYMENT_ID_HEADER = 'x-nextjs-deployment-id'\n\nexport const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'\nexport const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'\nexport const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =\n 'x-next-revalidate-tag-token'\n\nexport const NEXT_RESUME_HEADER = 'next-resume'\nexport const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length'\n\n// if these change make sure we update the related\n// documentation as well\nexport const NEXT_CACHE_TAG_MAX_ITEMS = 128\nexport const NEXT_CACHE_TAG_MAX_LENGTH = 256\nexport const NEXT_CACHE_SOFT_TAG_MAX_LENGTH = 1024\nexport const NEXT_CACHE_IMPLICIT_TAG_ID = '_N_T_'\nexport const NEXT_CACHE_ROOT_PARAM_TAG_ID = '_N_RP_'\n\n// in seconds\nexport const CACHE_ONE_YEAR_SECONDS = 31536000\n\n// in seconds, represents revalidate=false. I.e. never revaliate.\n// We use this value since it can be represented as a V8 SMI for optimal performance.\n// It can also be serialized as JSON if it ever leaks accidentally as an actual value.\nexport const INFINITE_CACHE = 0xfffffffe\n\n// Patterns to detect middleware files\nexport const MIDDLEWARE_FILENAME = 'middleware'\nexport const MIDDLEWARE_LOCATION_REGEXP = `(?:src/)?${MIDDLEWARE_FILENAME}`\n\n// Patterns to detect proxy files (replacement for middleware)\nexport const PROXY_FILENAME = 'proxy'\nexport const PROXY_LOCATION_REGEXP = `(?:src/)?${PROXY_FILENAME}`\n\n// Pattern to detect instrumentation hooks file\nexport const INSTRUMENTATION_HOOK_FILENAME = 'instrumentation'\n\n// Because on Windows absolute paths in the generated code can break because of numbers, eg 1 in the path,\n// we have to use a private alias\nexport const PAGES_DIR_ALIAS = 'private-next-pages'\nexport const DOT_NEXT_ALIAS = 'private-dot-next'\nexport const ROOT_DIR_ALIAS = 'private-next-root-dir'\nexport const APP_DIR_ALIAS = 'private-next-app-dir'\nexport const RSC_MOD_REF_PROXY_ALIAS = 'private-next-rsc-mod-ref-proxy'\nexport const RSC_ACTION_VALIDATE_ALIAS = 'private-next-rsc-action-validate'\nexport const RSC_ACTION_PROXY_ALIAS = 'private-next-rsc-server-reference'\nexport const RSC_CACHE_WRAPPER_ALIAS = 'private-next-rsc-cache-wrapper'\nexport const RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS =\n 'private-next-rsc-track-dynamic-import'\nexport const RSC_ACTION_ENCRYPTION_ALIAS = 'private-next-rsc-action-encryption'\nexport const RSC_ACTION_CLIENT_WRAPPER_ALIAS =\n 'private-next-rsc-action-client-wrapper'\n\nexport const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`\n\nexport const SSG_GET_INITIAL_PROPS_CONFLICT = `You can not use getInitialProps with getStaticProps. To use SSG, please remove your getInitialProps`\n\nexport const SERVER_PROPS_GET_INIT_PROPS_CONFLICT = `You can not use getInitialProps with getServerSideProps. Please remove getInitialProps.`\n\nexport const SERVER_PROPS_SSG_CONFLICT = `You can not use getStaticProps or getStaticPaths with getServerSideProps. To use SSG, please remove getServerSideProps`\n\nexport const STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR = `can not have getInitialProps/getServerSideProps, https://nextjs.org/docs/messages/404-get-initial-props`\n\nexport const SERVER_PROPS_EXPORT_ERROR = `pages with \\`getServerSideProps\\` can not be exported. See more info here: https://nextjs.org/docs/messages/gssp-export`\n\nexport const GSP_NO_RETURNED_VALUE =\n 'Your `getStaticProps` function did not return an object. Did you forget to add a `return`?'\nexport const GSSP_NO_RETURNED_VALUE =\n 'Your `getServerSideProps` function did not return an object. Did you forget to add a `return`?'\n\nexport const UNSTABLE_REVALIDATE_RENAME_ERROR =\n 'The `unstable_revalidate` property is available for general use.\\n' +\n 'Please use `revalidate` instead.'\n\nexport const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`\n\nexport const NON_STANDARD_NODE_ENV = `You are using a non-standard \"NODE_ENV\" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`\n\nexport const SSG_FALLBACK_EXPORT_ERROR = `Pages with \\`fallback\\` enabled in \\`getStaticPaths\\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`\n\nexport const ESLINT_DEFAULT_DIRS = ['app', 'pages', 'components', 'lib', 'src']\n\nexport const SERVER_RUNTIME: Record<string, ServerRuntime> = {\n edge: 'edge',\n experimentalEdge: 'experimental-edge',\n nodejs: 'nodejs',\n}\n\nexport const WEB_SOCKET_MAX_RECONNECTIONS = 12\n\n/**\n * The names of the webpack layers. These layers are the primitives for the\n * webpack chunks.\n */\nconst WEBPACK_LAYERS_NAMES = {\n /**\n * The layer for the shared code between the client and server bundles.\n */\n shared: 'shared',\n /**\n * The layer for server-only runtime and picking up `react-server` export conditions.\n * Including app router RSC pages and app router custom routes and metadata routes.\n */\n reactServerComponents: 'rsc',\n /**\n * Server Side Rendering layer for app (ssr).\n */\n serverSideRendering: 'ssr',\n /**\n * The browser client bundle layer for actions.\n */\n actionBrowser: 'action-browser',\n /**\n * The Node.js bundle layer for the API routes.\n */\n apiNode: 'api-node',\n /**\n * The Edge Lite bundle layer for the API routes.\n */\n apiEdge: 'api-edge',\n /**\n * The layer for the middleware code.\n */\n middleware: 'middleware',\n /**\n * The layer for the instrumentation hooks.\n */\n instrument: 'instrument',\n /**\n * The layer for assets on the edge.\n */\n edgeAsset: 'edge-asset',\n /**\n * The browser client bundle layer for App directory.\n */\n appPagesBrowser: 'app-pages-browser',\n /**\n * The browser client bundle layer for Pages directory.\n */\n pagesDirBrowser: 'pages-dir-browser',\n /**\n * The Edge Lite bundle layer for Pages directory.\n */\n pagesDirEdge: 'pages-dir-edge',\n /**\n * The Node.js bundle layer for Pages directory.\n */\n pagesDirNode: 'pages-dir-node',\n} as const\n\nexport type WebpackLayerName =\n (typeof WEBPACK_LAYERS_NAMES)[keyof typeof WEBPACK_LAYERS_NAMES]\n\nconst WEBPACK_LAYERS = {\n ...WEBPACK_LAYERS_NAMES,\n GROUP: {\n builtinReact: [\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.actionBrowser,\n ],\n serverOnly: [\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.actionBrowser,\n WEBPACK_LAYERS_NAMES.instrument,\n WEBPACK_LAYERS_NAMES.middleware,\n ],\n neutralTarget: [\n // pages api\n WEBPACK_LAYERS_NAMES.apiNode,\n WEBPACK_LAYERS_NAMES.apiEdge,\n ],\n clientOnly: [\n WEBPACK_LAYERS_NAMES.serverSideRendering,\n WEBPACK_LAYERS_NAMES.appPagesBrowser,\n ],\n bundled: [\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.actionBrowser,\n WEBPACK_LAYERS_NAMES.serverSideRendering,\n WEBPACK_LAYERS_NAMES.appPagesBrowser,\n WEBPACK_LAYERS_NAMES.shared,\n WEBPACK_LAYERS_NAMES.instrument,\n WEBPACK_LAYERS_NAMES.middleware,\n ],\n appPages: [\n // app router pages and layouts\n WEBPACK_LAYERS_NAMES.reactServerComponents,\n WEBPACK_LAYERS_NAMES.serverSideRendering,\n WEBPACK_LAYERS_NAMES.appPagesBrowser,\n WEBPACK_LAYERS_NAMES.actionBrowser,\n ],\n },\n}\n\nconst WEBPACK_RESOURCE_QUERIES = {\n edgeSSREntry: '__next_edge_ssr_entry__',\n metadata: '__next_metadata__',\n metadataRoute: '__next_metadata_route__',\n metadataImageMeta: '__next_metadata_image_meta__',\n}\n\nexport { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES }\n","import type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport type { RouteTree } from '../segment-cache/cache'\n\nexport function isNavigatingToNewRootLayout(\n currentTree: FlightRouterState,\n nextTree: RouteTree\n): boolean {\n // Compare segments\n const currentTreeSegment = currentTree[0]\n const nextTreeSegment = nextTree.segment\n\n // If any segment is different before we find the root layout, the root layout has changed.\n // E.g. /same/(group1)/layout.js -> /same/(group2)/layout.js\n // First segment is 'same' for both, keep looking. (group1) changed to (group2) before the root layout was found, it must have changed.\n if (Array.isArray(currentTreeSegment) && Array.isArray(nextTreeSegment)) {\n // Compare dynamic param name and type but ignore the value, different values would not affect the current root layout\n // /[name] - /slug1 and /slug2, both values (slug1 & slug2) still has the same layout /[name]/layout.js\n if (\n currentTreeSegment[0] !== nextTreeSegment[0] ||\n currentTreeSegment[2] !== nextTreeSegment[2]\n ) {\n return true\n }\n } else if (currentTreeSegment !== nextTreeSegment) {\n return true\n }\n\n // Current tree root layout found\n const currentIsRootLayout =\n ((currentTree[4] ?? 0) & PrefetchHint.IsRootLayout) !== 0\n const nextIsRootLayout =\n (nextTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0\n if (currentIsRootLayout) {\n // If the next tree doesn't have the root layout flag, it must have changed.\n return !nextIsRootLayout\n }\n // Current tree didn't have its root layout here, must have changed.\n if (nextIsRootLayout) {\n return true\n }\n\n const slots = nextTree.slots\n const currentTreeChildren = currentTree[1]\n if (slots !== null) {\n for (const slot in slots) {\n const nextTreeChild = slots[slot]\n const currentTreeChild = currentTreeChildren[slot]\n if (\n currentTreeChild === undefined ||\n isNavigatingToNewRootLayout(currentTreeChild, nextTreeChild)\n ) {\n return true\n }\n }\n }\n return false\n}\n","import type { FlightRouterState } from '../../../../shared/lib/app-router-types'\n\n// The tree from the last state that was committed to the browser history\n// (i.e., the last state for which HistoryUpdater's useInsertionEffect ran).\n// This lets the server-patch reducer distinguish between retrying a\n// navigation that already pushed a history entry vs one whose transition\n// suspended and never committed.\n//\n// Currently only used by the server-patch retry logic, but this module is a\n// stepping stone toward a broader refactor of the navigation queue. The\n// existing AppRouter action queue will eventually be replaced by a more\n// reactive model that explicitly tracks pending vs committed navigation\n// state. This file will likely evolve into (or be subsumed by) that new\n// implementation.\nlet lastCommittedTree: FlightRouterState | null = null\n\nexport function getLastCommittedTree(): FlightRouterState | null {\n return lastCommittedTree\n}\n\nexport function setLastCommittedTree(tree: FlightRouterState): void {\n lastCommittedTree = tree\n}\n","import { deleteMapEntry } from './cache-map'\nimport type { UnknownMapEntry } from './cache-map'\nimport { pingPrefetchScheduler } from './scheduler'\n\n// We use an LRU for memory management. We must update this whenever we add or\n// remove a new cache entry, or when an entry changes size.\n\nlet head: UnknownMapEntry | null = null\nlet lruSize: number = 0\n\n// TODO: I chose the max size somewhat arbitrarily. Consider setting this based\n// on navigator.deviceMemory, or some other heuristic. We should make this\n// customizable via the Next.js config, too.\nconst maxLruSize = 50 * 1024 * 1024 // 50 MB\n\nexport function lruPut(node: UnknownMapEntry) {\n if (head === node) {\n // Already at the head\n return\n }\n const prev = node.prev\n const next = node.next\n if (next === null || prev === null) {\n // This is an insertion\n lruSize += node.size\n // Whenever we add an entry, we need to check if we've exceeded the\n // max size. We don't evict entries immediately; they're evicted later in\n // an asynchronous task.\n ensureCleanupIsScheduled()\n } else {\n // This is a move. Remove from its current position.\n prev.next = next\n next.prev = prev\n }\n\n // Move to the front of the list\n if (head === null) {\n // This is the first entry\n node.prev = node\n node.next = node\n } else {\n // Add to the front of the list\n const tail = head.prev\n node.prev = tail\n // In practice, this is never null, but that isn't encoded in the type\n if (tail !== null) {\n tail.next = node\n }\n node.next = head\n head.prev = node\n }\n head = node\n}\n\nexport function updateLruSize(node: UnknownMapEntry, newNodeSize: number) {\n // This is a separate function from `put` so that we can resize the entry\n // regardless of whether it's currently being tracked by the LRU.\n const prevNodeSize = node.size\n node.size = newNodeSize\n if (node.next === null) {\n // This entry is not currently being tracked by the LRU.\n return\n }\n // Update the total LRU size\n lruSize = lruSize - prevNodeSize + newNodeSize\n ensureCleanupIsScheduled()\n}\n\nexport function deleteFromLru(deleted: UnknownMapEntry) {\n const next = deleted.next\n const prev = deleted.prev\n if (next !== null && prev !== null) {\n lruSize -= deleted.size\n\n deleted.next = null\n deleted.prev = null\n\n // Remove from the list\n if (head === deleted) {\n // Update the head\n if (next === head) {\n // This was the last entry\n head = null\n } else {\n head = next\n prev.next = next\n next.prev = prev\n }\n } else {\n prev.next = next\n next.prev = prev\n }\n } else {\n // Already deleted\n }\n}\n\nfunction ensureCleanupIsScheduled() {\n if (lruSize <= maxLruSize) {\n return\n }\n\n // To schedule cleanup, ping the prefetch scheduler. At the end of its work\n // loop, once there are no queued tasks and no in-progress requests, it will\n // call cleanup().\n pingPrefetchScheduler()\n}\n\nexport function cleanup() {\n if (lruSize <= maxLruSize) {\n return\n }\n\n // Evict entries until we're at 90% capacity. We can assume this won't\n // infinite loop because even if `maxLruSize` were 0, eventually\n // `deleteFromLru` sets `head` to `null` when we run out entries.\n const ninetyPercentMax = maxLruSize * 0.9\n while (lruSize > ninetyPercentMax && head !== null) {\n const tail = head.prev\n // In practice, this is never null, but that isn't encoded in the type\n if (tail !== null) {\n // Delete the entry from the map. In turn, this will remove it from\n // the LRU.\n deleteMapEntry(tail)\n }\n }\n}\n","import type { VaryPath } from './vary-path'\nimport { lruPut, updateLruSize, deleteFromLru } from './lru'\n\n/**\n * A specialized data type for storing multi-key cache entries.\n *\n * The basic structure is a map whose keys are tuples, called the keypath.\n * When querying the cache, keypaths are compared per-element.\n *\n * Example:\n * set(map, ['https://localhost', 'foo/bar/baz'], 'yay');\n * get(map, ['https://localhost', 'foo/bar/baz']) -> 'yay'\n *\n * NOTE: Array syntax is used in these examples for illustration purposes, but\n * in reality the paths are lists.\n * \n * The parts of the keypath represent the different inputs that contribute\n * to the entry value. To illustrate, if you were to use this data type to store\n * HTTP responses, the keypath would include the URL and everything listed by\n * the Vary header.\n * \n * See vary-path.ts for more details.\n *\n * The order of elements in a keypath must be consistent between lookups to\n * be considered the same, but besides that, the order of the keys is not\n * semantically meaningful.\n *\n * Keypaths may include a special kind of key called Fallback. When an entry is\n * stored with Fallback as part of its keypath, it means that the entry does not\n * vary by that key. When querying the cache, if an exact match is not found for\n * a keypath, the cache will check for a Fallback match instead. Each element of\n * the keypath may have a Fallback, so retrieval is an O(n ^ 2) operation, but\n * it's expected that keypaths are relatively short.\n *\n * Example:\n * set(cacheMap, ['store', 'product', 1], PRODUCT_PAGE_1);\n * set(cacheMap, ['store', 'product', Fallback], GENERIC_PRODUCT_PAGE);\n *\n * // Exact match\n * get(cacheMap, ['store', 'product', 1]) -> PRODUCT_PAGE_1\n *\n * // Fallback match\n * get(cacheMap, ['store', 'product', 2]) -> GENERIC_PRODUCT_PAGE\n *\n * Because we have the Fallback mechanism, we can impose a constraint that\n * regular JS maps do not have: a value cannot be stored at multiple keypaths\n * simultaneously. These cases should be expressed with Fallback keys instead.\n *\n * Additionally, because values only exist at a single keypath at a time, we\n * can optimize successive lookups by caching the internal map entry on the\n * value itself, using the `ref` field. This is especially useful because it\n * lets us skip the O(n ^ 2) lookup that occurs when Fallback entries\n * are present.\n *\n\n * How to decide if stuff belongs in here, or in cache.ts?\n * -------------------------------------------------------\n * \n * Anything to do with retrival, lifetimes, or eviction needs to go in this\n * module because it affects the fallback algorithm. For example, when\n * performing a lookup, if an entry is stale, it needs to be treated as\n * semantically equivalent to if the entry was not present at all.\n * \n * If there's logic that's not related to the fallback algorithm, though, we\n * should prefer to put it in cache.ts.\n */\n\n// The protocol that values must implement. In practice, the only two types that\n// we ever actually deal with in this module are RouteCacheEntry and\n// SegmentCacheEntry; this is just to keep track of the coupling so we don't\n// leak concerns between the modules unnecessarily.\nexport interface MapValue {\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\n/**\n * Represents a node in the cache map and LRU.\n * MapEntry<V> structurally satisfies this interface for any V extends MapValue.\n *\n * The LRU can contain entries of different value types\n * (e.g., both RouteCacheEntry and SegmentCacheEntry). This interface captures\n * the common structure needed for cache map and LRU operations without\n * requiring knowledge of the specific value type.\n */\nexport interface MapEntry<V extends MapValue> {\n // Cache map structure fields\n parent: MapEntry<V> | null\n key: unknown\n map: Map<unknown, MapEntry<V>> | null\n value: V | null\n\n // LRU linked list fields\n prev: MapEntry<V> | null\n next: MapEntry<V> | null\n size: number\n}\n\n/**\n * A looser type for MapEntry\n * This allows the LRU to work with entries of different\n * value types while still providing type safety.\n *\n * The `map` field lets Map<unknown, MapEntry<V>> be assignable to this\n * type since we're only reading from the map, not inserting into it.\n */\nexport type UnknownMapEntry = {\n parent: UnknownMapEntry | null\n key: unknown\n map: Pick<Map<unknown, UnknownMapEntry>, 'get' | 'delete' | 'size'> | null\n value: MapValue | null\n\n prev: UnknownMapEntry | null\n next: UnknownMapEntry | null\n size: number\n}\n\n// The CacheMap type is just the root entry of the map.\nexport type CacheMap<V extends MapValue> = MapEntry<V>\n\nexport type FallbackType = { __brand: 'Fallback' }\nexport const Fallback = {} as FallbackType\n\n// This is a special internal key that is used for \"revalidation\" entries. It's\n// an implementation detail that shouldn't leak outside of this module.\nconst Revalidation = {}\n\nexport function createCacheMap<V extends MapValue>(): CacheMap<V> {\n const cacheMap: MapEntry<V> = {\n parent: null,\n key: null,\n value: null,\n map: null,\n\n // LRU-related fields\n prev: null,\n next: null,\n size: 0,\n }\n return cacheMap\n}\n\nfunction getOrInitialize<V extends MapValue>(\n cacheMap: CacheMap<V>,\n keys: VaryPath,\n isRevalidation: boolean\n): MapEntry<V> {\n // Go through each level of keys until we find the entry that matches, or\n // create a new entry if one doesn't exist.\n //\n // This function will only return entries that match the keypath _exactly_.\n // Unlike getWithFallback, it will not access fallback entries unless it's\n // explicitly part of the keypath.\n let entry = cacheMap\n let remainingKeys: VaryPath | null = keys\n let key: unknown | null = null\n while (true) {\n const previousKey = key\n if (remainingKeys !== null) {\n key = remainingKeys.value\n remainingKeys = remainingKeys.parent\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath. The \"normal\" entry is its parent.\n\n // However, if the parent entry is currently empty, we don't need to store\n // this as a revalidation entry. Just insert the revalidation into the\n // normal slot.\n if (entry.value === null) {\n return entry\n }\n\n // Otheriwse, create a child entry.\n key = Revalidation\n } else {\n // There are no more keys. This is the terminal entry.\n break\n }\n\n let map = entry.map\n if (map !== null) {\n const existingEntry = map.get(key)\n if (existingEntry !== undefined) {\n // Found a match. Keep going.\n entry = existingEntry\n continue\n }\n } else {\n map = new Map()\n entry.map = map\n }\n // No entry exists yet at this level. Create a new one.\n const newEntry: MapEntry<V> = {\n parent: entry,\n key,\n value: null,\n map: null,\n\n // LRU-related fields\n prev: null,\n next: null,\n size: 0,\n }\n map.set(key, newEntry)\n entry = newEntry\n }\n\n return entry\n}\n\nexport function getFromCacheMap<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n rootEntry: CacheMap<V>,\n keys: VaryPath,\n isRevalidation: boolean\n): V | null {\n const entry = getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n rootEntry,\n keys,\n isRevalidation,\n 0\n )\n if (entry === null || entry.value === null) {\n return null\n }\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry)\n return entry.value\n}\n\nexport function isValueExpired(\n now: number,\n currentCacheVersion: number,\n value: MapValue\n): boolean {\n return value.staleAt <= now || value.version < currentCacheVersion\n}\n\nfunction lazilyEvictIfNeeded<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n entry: MapEntry<V>\n) {\n // We have a matching entry, but before we can return it, we need to check if\n // it's still fresh. Otherwise it should be treated the same as a cache miss.\n\n if (entry.value === null) {\n // This entry has no value, so there's nothing to evict.\n return entry\n }\n\n const value = entry.value\n if (isValueExpired(now, currentCacheVersion, value)) {\n // The value expired. Lazily evict it from the cache, and return null. This\n // is conceptually the same as a cache miss.\n deleteMapEntry(entry)\n return null\n }\n\n // The matched entry has not expired. Return it.\n return entry\n}\n\nfunction getEntryWithFallbackImpl<V extends MapValue>(\n now: number,\n currentCacheVersion: number,\n entry: MapEntry<V>,\n keys: VaryPath | null,\n isRevalidation: boolean,\n previousKey: unknown | null\n): MapEntry<V> | null {\n // This is similar to getExactEntry, but if an exact match is not found for\n // a key, it will return the fallback entry instead. This is recursive at\n // every level, e.g. an entry with keypath [a, Fallback, c, Fallback] is\n // valid match for [a, b, c, d].\n //\n // It will return the most specific match available.\n let key\n let remainingKeys: VaryPath | null\n if (keys !== null) {\n key = keys.value\n remainingKeys = keys.parent\n } else if (isRevalidation && previousKey !== Revalidation) {\n // During a revalidation, we append an internal \"Revalidation\" key to\n // the end of the keypath.\n key = Revalidation\n remainingKeys = null\n } else {\n // There are no more keys. This is the terminal entry.\n\n // TODO: When performing a lookup during a navigation, as opposed to a\n // prefetch, we may want to skip entries that are Pending if there's also\n // a Fulfilled fallback entry. Tricky to say, though, since if it's\n // already pending, it's likely to stream in soon. Maybe we could do this\n // just on slow connections and offline mode.\n\n return lazilyEvictIfNeeded(now, currentCacheVersion, entry)\n }\n const map = entry.map\n if (map !== null) {\n const existingEntry = map.get(key)\n if (existingEntry !== undefined) {\n // Found an exact match for this key. Keep searching.\n const result = getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n existingEntry,\n remainingKeys,\n isRevalidation,\n key\n )\n if (result !== null) {\n return result\n }\n }\n // No match found for this key. Check if there's a fallback.\n const fallbackEntry = map.get(Fallback)\n if (fallbackEntry !== undefined) {\n // Found a fallback for this key. Keep searching.\n return getEntryWithFallbackImpl(\n now,\n currentCacheVersion,\n fallbackEntry,\n remainingKeys,\n isRevalidation,\n key\n )\n }\n }\n return null\n}\n\nexport function setInCacheMap<V extends MapValue>(\n cacheMap: CacheMap<V>,\n keys: VaryPath,\n value: V,\n isRevalidation: boolean\n): void {\n // Add a value to the map at the given keypath. If the value is already\n // part of the map, it's removed from its previous keypath. (NOTE: This is\n // unlike a regular JS map, but the behavior is intentional.)\n const entry = getOrInitialize(cacheMap, keys, isRevalidation)\n setMapEntryValue(entry, value)\n\n // This is an LRU access. Move the entry to the front of the list.\n lruPut(entry)\n updateLruSize(entry, value.size)\n}\n\nfunction setMapEntryValue(entry: UnknownMapEntry, value: MapValue): void {\n if (entry.value !== null) {\n // There's already a value at the given keypath. Disconnect the old value\n // from the map. We're not calling `deleteMapEntry` here because the\n // entry itself is still in the map. We just want to overwrite its value.\n dropRef(entry.value)\n entry.value = null\n }\n\n // This value may already be in the map at a different keypath.\n // Grab a reference before we overwrite it.\n const oldEntry = value.ref\n\n entry.value = value\n value.ref = entry\n\n updateLruSize(entry, value.size)\n\n if (oldEntry !== null && oldEntry !== entry && oldEntry.value === value) {\n // This value is already in the map at a different keypath in the map.\n // Values only exist at a single keypath at a time. Remove it from the\n // previous keypath.\n //\n // Note that only the internal map entry is garbage collected; we don't\n // call `dropRef` here because it's still in the map, just\n // at a new keypath (the one we just set, above).\n deleteMapEntry(oldEntry)\n }\n}\n\nexport function deleteFromCacheMap(value: MapValue): void {\n const entry = value.ref\n if (entry === null) {\n // This value is not a member of any map.\n return\n }\n\n dropRef(value)\n deleteMapEntry(entry)\n}\n\nfunction dropRef(value: MapValue): void {\n // Drop the value from the map by setting its `ref` backpointer to\n // null. This is a separate operation from `deleteMapEntry` because when\n // re-keying a value we need to be able to delete the old, internal map\n // entry without garbage collecting the value itself.\n value.ref = null\n}\n\nexport function deleteMapEntry(entry: UnknownMapEntry): void {\n // Delete the entry from the cache.\n entry.value = null\n\n deleteFromLru(entry)\n\n // Check if we can garbage collect the entry.\n const map = entry.map\n if (map === null) {\n // Since this entry has no value, and also no child entries, we can\n // garbage collect it. Remove it from its parent, and keep garbage\n // collecting the parents until we reach a non-empty entry.\n let parent = entry.parent\n let key = entry.key\n while (parent !== null) {\n const parentMap = parent.map\n if (parentMap !== null) {\n parentMap.delete(key)\n if (parentMap.size === 0) {\n // We just removed the last entry in the parent map.\n parent.map = null\n if (parent.value === null) {\n // The parent node has no child entries, nor does it have a value\n // on itself. It can be garbage collected. Keep going.\n key = parent.key\n parent = parent.parent\n continue\n }\n }\n }\n // The parent is not empty. Stop garbage collecting.\n break\n }\n } else {\n // Check if there's a revalidating entry. If so, promote it to a\n // \"normal\" entry, since the normal one was just deleted.\n const revalidatingEntry = map.get(Revalidation)\n if (revalidatingEntry !== undefined && revalidatingEntry.value !== null) {\n setMapEntryValue(entry, revalidatingEntry.value)\n }\n }\n}\n\nexport function setSizeInCacheMap<V extends MapValue>(\n value: V,\n size: number\n): void {\n const entry = value.ref\n if (entry === null) {\n // This value is not a member of any map.\n return\n }\n // Except during initialization (when the size is set to 0), this is the only\n // place the `size` field should be updated, to ensure it's in sync with the\n // the LRU.\n value.size = size\n updateLruSize(entry, size)\n}\n","import { FetchStrategy } from './types'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n NormalizedNextUrl,\n} from './cache-key'\nimport type { RouteTree } from './cache'\nimport { Fallback, type FallbackType } from './cache-map'\nimport { HEAD_REQUEST_KEY } from '../../../shared/lib/segment-cache/segment-value-encoding'\n\ntype Opaque<T, K> = T & { __brand: K }\n\n/**\n * A linked-list of all the params (or other param-like) inputs that a cache\n * entry may vary by. This is used by the CacheMap module to reuse cache entries\n * across different param values. If a param has a value of Fallback, it means\n * the cache entry is reusable for all possible values of that param. See\n * cache-map.ts for details.\n *\n * A segment's vary path is a pure function of a segment's position in a\n * particular route tree and the (post-rewrite) URL that is being queried. More\n * concretely, successive queries of the cache for the same segment always use\n * the same vary path.\n *\n * A route's vary path is simpler: it's comprised of the pathname, search\n * string, and Next-URL header.\n */\nexport type VaryPath = {\n /**\n * Identifies which param this vary path node corresponds to. Used by\n * getFulfilledSegmentVaryPath to determine which params to replace with\n * Fallback based on the varyParams set from the server.\n *\n * - For path params: the param name (e.g., 'slug')\n * - For search params: '?'\n * - For non-param nodes (request keys, etc.): null\n */\n id: string | null\n value: string | null | FallbackType\n parent: VaryPath | null\n}\n\n// Because it's so important for vary paths to line up across cache accesses,\n// we use opaque type aliases to ensure these are only created within\n// this module.\n\n// requestKey -> searchParams -> nextUrl\nexport type RouteVaryPath = Opaque<\n {\n id: null\n value: NormalizedPathname\n parent: {\n id: '?'\n value: NormalizedSearch\n parent: {\n id: null\n value: NormalizedNextUrl | null | FallbackType\n parent: null\n }\n }\n },\n 'RouteVaryPath'\n>\n\n// requestKey -> pathParams\nexport type LayoutVaryPath = Opaque<\n {\n id: null\n value: string\n parent: PartialSegmentVaryPath | null\n },\n 'LayoutVaryPath'\n>\n\n// requestKey -> searchParams -> pathParams\nexport type PageVaryPath = Opaque<\n {\n id: null\n value: string\n parent: {\n id: '?'\n value: NormalizedSearch | FallbackType\n parent: PartialSegmentVaryPath | null\n }\n },\n 'PageVaryPath'\n>\n\nexport type SegmentVaryPath = LayoutVaryPath | PageVaryPath\n\n// Intermediate type used when building a vary path during a recursive traversal\n// of the route tree.\nexport type PartialSegmentVaryPath = Opaque<VaryPath, 'PartialSegmentVaryPath'>\n\nexport function getRouteVaryPath(\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: NormalizedNextUrl | null\n): RouteVaryPath {\n // requestKey -> searchParams -> nextUrl\n const varyPath: VaryPath = {\n id: null,\n value: pathname,\n parent: {\n id: '?',\n value: search,\n parent: {\n id: null,\n value: nextUrl,\n parent: null,\n },\n },\n }\n return varyPath as RouteVaryPath\n}\n\nexport function getFulfilledRouteVaryPath(\n pathname: NormalizedPathname,\n search: NormalizedSearch,\n nextUrl: NormalizedNextUrl | null,\n couldBeIntercepted: boolean\n): RouteVaryPath {\n // This is called when a route's data is fulfilled. The cache entry will be\n // re-keyed based on which inputs the response varies by.\n // requestKey -> searchParams -> nextUrl\n const varyPath: VaryPath = {\n id: null,\n value: pathname,\n parent: {\n id: '?',\n value: search,\n parent: {\n id: null,\n value: couldBeIntercepted ? nextUrl : Fallback,\n parent: null,\n },\n },\n }\n return varyPath as RouteVaryPath\n}\n\nexport function appendLayoutVaryPath(\n parentPath: PartialSegmentVaryPath | null,\n cacheKey: string,\n paramName: string\n): PartialSegmentVaryPath {\n const varyPathPart: VaryPath = {\n id: paramName,\n value: cacheKey,\n parent: parentPath,\n }\n return varyPathPart as PartialSegmentVaryPath\n}\n\nexport function finalizeLayoutVaryPath(\n requestKey: string,\n varyPath: PartialSegmentVaryPath | null\n): LayoutVaryPath {\n const layoutVaryPath: VaryPath = {\n id: null,\n value: requestKey,\n parent: varyPath,\n }\n return layoutVaryPath as LayoutVaryPath\n}\n\nexport function getPartialLayoutVaryPath(\n finalizedVaryPath: LayoutVaryPath\n): PartialSegmentVaryPath | null {\n // This is the inverse of finalizeLayoutVaryPath.\n return finalizedVaryPath.parent\n}\n\nexport function finalizePageVaryPath(\n requestKey: string,\n renderedSearch: NormalizedSearch,\n varyPath: PartialSegmentVaryPath | null\n): PageVaryPath {\n // Unlike layouts, a page segment's vary path also includes the search string.\n // requestKey -> searchParams -> pathParams\n const pageVaryPath: VaryPath = {\n id: null,\n value: requestKey,\n parent: {\n id: '?',\n value: renderedSearch,\n parent: varyPath,\n },\n }\n return pageVaryPath as PageVaryPath\n}\n\nexport function getPartialPageVaryPath(\n finalizedVaryPath: PageVaryPath\n): PartialSegmentVaryPath | null {\n // This is the inverse of finalizePageVaryPath.\n return finalizedVaryPath.parent.parent\n}\n\nexport function finalizeMetadataVaryPath(\n pageRequestKey: string,\n renderedSearch: NormalizedSearch,\n varyPath: PartialSegmentVaryPath | null\n): PageVaryPath {\n // The metadata \"segment\" is not a real segment because it doesn't exist in\n // the normal structure of the route tree, but in terms of caching, it\n // behaves like a page segment because it varies by all the same params as\n // a page.\n //\n // To keep the protocol for querying the server simple, the request key for\n // the metadata does not include any path information. It's unnecessary from\n // the server's perspective, because unlike page segments, there's only one\n // metadata response per URL, i.e. there's no need to distinguish multiple\n // parallel pages.\n //\n // However, this means the metadata request key is insufficient for\n // caching the the metadata in the client cache, because on the client we\n // use the request key to distinguish the metadata entry from all other\n // page's metadata entries.\n //\n // So instead we create a simulated request key based on the page segment.\n // Conceptually this is equivalent to the request key the server would have\n // assigned the metadata segment if it treated it as part of the actual\n // route structure.\n\n // If there are multiple parallel pages, we use whichever is the first one.\n // This is fine because the only difference between request keys for\n // different parallel pages are things like route groups and parallel\n // route slots. As long as it's always the same one, it doesn't matter.\n const pageVaryPath: VaryPath = {\n id: null,\n // Append the actual metadata request key to the page request key. Note\n // that we're not using a separate vary path part; it's unnecessary because\n // these are not conceptually separate inputs.\n value: pageRequestKey + HEAD_REQUEST_KEY,\n parent: {\n id: '?',\n value: renderedSearch,\n parent: varyPath,\n },\n }\n return pageVaryPath as PageVaryPath\n}\n\nexport function getSegmentVaryPathForRequest(\n fetchStrategy: FetchStrategy,\n tree: RouteTree\n): SegmentVaryPath {\n // This is used for storing pending requests in the cache. We want to choose\n // the most generic vary path based on the strategy used to fetch it, i.e.\n // static/PPR versus runtime prefetching, so that it can be reused as much\n // as possible.\n //\n // We may be able to re-key the response to something even more generic once\n // we receive it — for example, if the server tells us that the response\n // doesn't vary on a particular param — but even before we send the request,\n // we know some params are reusable based on the fetch strategy alone. For\n // example, a static prefetch will never vary on search params.\n //\n // The original vary path with all the params filled in is stored on the\n // route tree object. We will clone this one to create a new vary path\n // where certain params are replaced with Fallback.\n //\n // This result of this function is not stored anywhere. It's only used to\n // access the cache a single time.\n //\n // TODO: Rather than create a new list object just to access the cache, the\n // plan is to add the concept of a \"vary mask\". This will represent all the\n // params that can be treated as Fallback. (Or perhaps the inverse.)\n const originalVaryPath = tree.varyPath\n\n // Only page segments (and the special \"metadata\" segment, which is treated\n // like a page segment for the purposes of caching) may contain search\n // params. There's no reason to include them in the vary path otherwise.\n if (tree.isPage) {\n // Only a runtime prefetch will include search params in the vary path.\n // Static prefetches never include search params, so they can be reused\n // across all possible search param values.\n const doesVaryOnSearchParams =\n fetchStrategy === FetchStrategy.Full ||\n fetchStrategy === FetchStrategy.PPRRuntime\n\n if (!doesVaryOnSearchParams) {\n // The response from the the server will not vary on search params. Clone\n // the end of the original vary path to replace the search params\n // with Fallback.\n //\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with Fallback\n const searchParamsVaryPath = (originalVaryPath as PageVaryPath).parent\n const pathParamsVaryPath = searchParamsVaryPath.parent\n const patchedVaryPath: VaryPath = {\n id: null,\n value: originalVaryPath.value,\n parent: {\n id: '?',\n value: Fallback,\n parent: pathParamsVaryPath,\n },\n }\n return patchedVaryPath as SegmentVaryPath\n }\n }\n\n // The request does vary on search params. We don't need to modify anything.\n return originalVaryPath as SegmentVaryPath\n}\n\nexport function clonePageVaryPathWithNewSearchParams(\n originalVaryPath: PageVaryPath,\n newSearch: NormalizedSearch\n): PageVaryPath {\n // requestKey -> searchParams -> pathParams\n // ^ This part gets replaced with newSearch\n const searchParamsVaryPath = originalVaryPath.parent\n const clonedVaryPath: VaryPath = {\n id: null,\n value: originalVaryPath.value,\n parent: {\n id: '?',\n value: newSearch,\n parent: searchParamsVaryPath.parent,\n },\n }\n return clonedVaryPath as PageVaryPath\n}\n\nexport function getRenderedSearchFromVaryPath(\n varyPath: PageVaryPath\n): NormalizedSearch | null {\n const searchParams = varyPath.parent.value\n return typeof searchParams === 'string'\n ? (searchParams as NormalizedSearch)\n : null\n}\n\nexport function getFulfilledSegmentVaryPath(\n original: VaryPath,\n varyParams: Set<string>\n): SegmentVaryPath {\n // Re-keys a segment's vary path based on which params the segment actually\n // depends on. Params that are NOT in the varyParams set are replaced with\n // Fallback, allowing the cache entry to be reused across different values of\n // those params.\n\n // This is called when a segment is fulfilled with data from the server. The\n // varyParams set comes from the server and indicates which params were\n // accessed during rendering.\n const clone: VaryPath = {\n id: original.id,\n // If the id is null, this node is not a param (e.g., it's a request key).\n // If the id is in the varyParams set, keep the original value.\n // Otherwise, replace with Fallback to make it reusable.\n value:\n original.id === null || varyParams.has(original.id)\n ? original.value\n : Fallback,\n parent:\n original.parent === null\n ? null\n : getFulfilledSegmentVaryPath(original.parent, varyParams),\n }\n return clone as SegmentVaryPath\n}\n","/**\n * Optimistic Routing (Known Routes)\n *\n * This module enables the client to predict route structure for URLs that\n * haven't been prefetched yet, based on previously learned route patterns.\n * When successful, this allows skipping the route tree prefetch request\n * entirely.\n *\n * The core idea is that many URLs map to the same route structure. For example,\n * /blog/post-1 and /blog/post-2 both resolve to /blog/[slug]. Once we've\n * prefetched one, we can predict the structure of the other.\n *\n * However, we can't always make this prediction. Static siblings (like\n * /blog/featured alongside /blog/[slug]) have different route structures.\n * When we learn a dynamic route, we also learn its static siblings so we\n * know when NOT to apply the prediction.\n *\n * Main entry points:\n *\n * 1. discoverKnownRoute: Called after receiving a route tree from the server.\n * Traverses the route tree, compares URL parts to segments, and populates\n * the known route tree if they match. Routes are always inserted into the\n * cache.\n *\n * 2. matchKnownRoute: Called when looking up a route with no cache entry.\n * Matches the candidate URL against learned patterns. Returns a synthetic\n * cache entry if successful, or null to fall back to server resolution.\n *\n * Rewrite detection happens during traversal: if a URL path part doesn't match\n * the corresponding route segment, we stop populating the known route tree\n * (since the mapping is incorrect) but still insert the route into the cache.\n *\n * The known route tree is append-only with no eviction. Route patterns are\n * derived from the filesystem, so they don't become stale within a session.\n * Cache invalidation on deploy clears everything anyway.\n *\n * Current limitations (deopt to server resolution):\n * - Rewrites: Detected during traversal (tree not populated, but route cached)\n * - Intercepted routes: The route tree varies by referrer (Next-Url header),\n * so we can't predict the correct structure from the URL alone. Patterns are\n * still stored during discovery (so the trie stays populated for non-\n * intercepted siblings), but matching bails out when the pattern is marked\n * as interceptable.\n */\n\nimport type { DynamicParamTypesShort } from '../../../shared/lib/app-router-types'\nimport type { RouteTree, FulfilledRouteCacheEntry } from './cache'\nimport {\n EntryStatus,\n writeRouteIntoCache,\n fulfillRouteCacheEntry,\n type PendingRouteCacheEntry,\n createMetadataRouteTree,\n} from './cache'\nimport { doesStaticSegmentAppearInURL } from '../../route-params'\nimport type { NormalizedPathname, NormalizedSearch } from './cache-key'\nimport {\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n finalizeMetadataVaryPath,\n type PartialSegmentVaryPath,\n type PageVaryPath,\n} from './vary-path'\n\n/**\n * The known route tree is analogous to a route table. A different routing\n * implementation might use regexes or URLPattern; ours uses a trie indexed\n * by URL path segments.\n *\n * Each node (KnownRoutePart) represents a position in the URL and can have:\n * - staticChildren: Map of literal segments to child nodes\n * - dynamicChild: A single dynamic segment node ([slug], [...params], etc.)\n * - pattern: A cache entry template for routes that terminate here\n *\n * This tree only contains segments that correspond to actual filesystem routes.\n * Route groups like (marketing) and parallel routes like @modal are not\n * included since they don't appear in URLs. Similarly, if a URL is rewritten\n * to a different filesystem path, the original URL segments don't appear here\n * — only the resolved filesystem route structure is stored.\n *\n * Example tree after learning /blog/[slug], /blog/featured, and /about:\n *\n * ├── about\n * └── blog\n * ├── featured\n * └── [slug]\n *\n * When matching /blog/hello:\n * 1. \"blog\" matches static child\n * 2. \"hello\" doesn't match \"featured\", falls through to [slug]\n * 3. Returns [slug]'s pattern with resolved param { slug: \"hello\" }\n */\ntype KnownRoutePartBase = {\n // Known static paths at this level. The null vs Map distinction is\n // semantically meaningful:\n // - null: Static siblings are UNKNOWN at this level (e.g., webpack dev mode\n // where routes are compiled on-demand). If there's a dynamicChild, we\n // can't safely match it because the URL might be an unknown static sibling.\n // - Map (even if empty): Static siblings are KNOWN. We can safely match a\n // dynamicChild if the URL doesn't match any entry in the Map.\n staticChildren: Map<string, KnownRoutePart> | null\n\n // The cache entry that serves as a pattern for this route.\n // When a URL matches, we clone this and substitute param values.\n // null means we know this path exists (from static siblings) but haven't\n // learned its structure yet.\n pattern: FulfilledRouteCacheEntry | null\n\n // TODO: For prefix rewrite support. When true, this part may not appear in\n // the candidate URL because it was injected by a rewrite.\n // mayBeSkippedInURL: boolean\n}\n\n// The dynamic child fields are structured as a union so that narrowing on\n// dynamicChild also narrows dynamicChildParamName and dynamicChildParamType.\ntype KnownRoutePartWithoutDynamicChild = KnownRoutePartBase & {\n dynamicChild: null\n dynamicChildParamName: null\n dynamicChildParamType: null\n}\n\ntype KnownRoutePartWithDynamicChild = KnownRoutePartBase & {\n dynamicChild: KnownRoutePart\n dynamicChildParamName: string\n dynamicChildParamType: DynamicParamTypesShort\n}\n\ntype KnownRoutePart =\n | KnownRoutePartWithoutDynamicChild\n | KnownRoutePartWithDynamicChild\n\n/**\n * Param values extracted during URL matching. Used to reify the template.\n * - string for regular dynamic [param]\n * - string[] for catch-all [...param] and optional catch-all [[...param]]\n */\ntype ResolvedParams = Map<string, string | string[]>\n\nfunction createEmptyPart(): KnownRoutePart {\n return {\n staticChildren: null,\n dynamicChild: null,\n dynamicChildParamName: null,\n dynamicChildParamType: null,\n pattern: null,\n }\n}\n\n// The root of the known route tree.\nlet knownRouteTreeRoot: KnownRoutePart = createEmptyPart()\n\n/**\n * Learns a route pattern from a server response and inserts it into the cache.\n *\n * Called after receiving a route tree from the server (initial load, navigation,\n * or prefetch). Traverses the route tree, compares URL parts to segments, and\n * populates the known route tree if they match. Routes are always inserted into\n * the cache regardless of whether the URL matches the route structure.\n *\n * When pendingEntry is provided, it's fulfilled and used. When null, an entry\n * is created and inserted into the route cache map.\n *\n * When hasDynamicRewrite is true, the route entry is marked as having a\n * dynamic rewrite, which prevents it from being used as a template for future\n * predictions. This is set when we detect a mismatch between what we predicted\n * and what the server returned.\n *\n * Returns the fulfilled route cache entry.\n */\nexport function discoverKnownRoute(\n now: number,\n pathname: string,\n nextUrl: string | null,\n pendingEntry: PendingRouteCacheEntry | null,\n routeTree: RouteTree,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const tree = routeTree\n\n const pathnameParts = pathname.split('/').filter((p) => p !== '')\n const firstPart = pathnameParts.length > 0 ? pathnameParts[0] : null\n const remainingParts = pathnameParts.length > 0 ? pathnameParts.slice(1) : []\n\n if (pendingEntry !== null) {\n // Fulfill the pending entry first\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n if (hasDynamicRewrite) {\n fulfilledEntry.hasDynamicRewrite = true\n }\n // Populate the known route tree (handles rewrite detection internally).\n // The entry is already in the cache; this just stores it as a pattern\n // if the URL matches the route structure.\n discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n firstPart,\n remainingParts,\n fulfilledEntry,\n now,\n pathname,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n return fulfilledEntry\n }\n\n // No pending entry - discoverKnownRoutePart will create one and insert it\n // into the cache, or return an existing pattern if one exists.\n return discoverKnownRoutePart(\n knownRouteTreeRoot,\n tree,\n firstPart,\n remainingParts,\n null,\n now,\n pathname,\n nextUrl,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n}\n\n/**\n * Gets or creates the dynamic child node for a KnownRoutePart.\n * A node can have at most one dynamic child (you can't have both [slug] and\n * [id] at the same route level), so we either return existing or create new.\n */\nfunction discoverDynamicChild(\n part: KnownRoutePart,\n paramName: string,\n paramType: DynamicParamTypesShort\n): KnownRoutePart {\n if (part.dynamicChild !== null) {\n return part.dynamicChild\n }\n const newChild = createEmptyPart()\n // Type assertion needed because we're converting from \"without\" to \"with\"\n // dynamic child variant.\n const mutablePart = part as unknown as KnownRoutePartWithDynamicChild\n mutablePart.dynamicChild = newChild\n mutablePart.dynamicChildParamName = paramName\n mutablePart.dynamicChildParamType = paramType\n return newChild\n}\n\n/**\n * Recursive workhorse for discoverKnownRoute.\n *\n * Walks the route tree and URL parts in parallel, building out the known\n * route tree as it goes. At each step:\n * 1. Determines if the current segment appears in the URL (dynamic/static)\n * 2. Validates URL matches route structure (detects rewrites)\n * 3. Creates/updates the corresponding KnownRoutePart node\n * 4. Records static siblings for future matching\n * 5. Recurses into child slots (parallel routes)\n *\n * If a URL/route mismatch is detected (rewrite), we stop building the known\n * route tree but still cache the route entry for direct lookup.\n */\nfunction discoverKnownRoutePart(\n parentKnownRoutePart: KnownRoutePart,\n routeTree: RouteTree,\n urlPart: string | null,\n remainingParts: string[],\n existingEntry: FulfilledRouteCacheEntry | null,\n // These are passed through unchanged for entry creation at the leaf\n now: number,\n pathname: string,\n nextUrl: string | null,\n fullTree: RouteTree,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean,\n hasDynamicRewrite: boolean\n): FulfilledRouteCacheEntry {\n const segment = routeTree.segment\n\n let segmentAppearsInURL: boolean\n let paramName: string | null = null\n let paramType: DynamicParamTypesShort | null = null\n let staticSiblings: readonly string[] | null = null\n\n if (typeof segment === 'string') {\n segmentAppearsInURL = doesStaticSegmentAppearInURL(segment)\n } else {\n // Dynamic segment tuple: [paramName, paramCacheKey, paramType, staticSiblings]\n paramName = segment[0]\n paramType = segment[2]\n staticSiblings = segment[3]\n segmentAppearsInURL = true\n }\n\n let knownRoutePart: KnownRoutePart = parentKnownRoutePart\n let nextUrlPart: string | null = urlPart\n let nextRemainingParts: string[] = remainingParts\n\n if (segmentAppearsInURL) {\n // Check for mismatch: if this is a static segment, the URL part must match\n if (paramName === null && urlPart !== segment) {\n // URL doesn't match route structure (likely a rewrite).\n // Don't populate the known route tree, just write the route into the\n // cache and return immediately.\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // URL matches route structure. Build the known route tree.\n if (paramName !== null && paramType !== null) {\n // Dynamic segment\n knownRoutePart = discoverDynamicChild(\n parentKnownRoutePart,\n paramName,\n paramType\n )\n\n // Record static siblings as placeholder parts.\n // IMPORTANT: We use the null vs Map distinction to track whether\n // siblings are known at this level:\n // - staticChildren: null = siblings unknown (can't safely match dynamic)\n // - staticChildren: Map = siblings known (even if empty)\n // This matters in dev mode where webpack may not know all siblings yet.\n if (staticSiblings !== null) {\n // Siblings are known - ensure we have a Map (even if empty)\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n for (const sibling of staticSiblings) {\n if (!parentKnownRoutePart.staticChildren.has(sibling)) {\n parentKnownRoutePart.staticChildren.set(sibling, createEmptyPart())\n }\n }\n }\n } else {\n // Static segment\n if (parentKnownRoutePart.staticChildren === null) {\n parentKnownRoutePart.staticChildren = new Map()\n }\n let existingChild = parentKnownRoutePart.staticChildren.get(urlPart!)\n if (existingChild === undefined) {\n existingChild = createEmptyPart()\n parentKnownRoutePart.staticChildren.set(urlPart!, existingChild)\n }\n knownRoutePart = existingChild\n }\n\n // Advance to next URL part\n nextUrlPart = remainingParts.length > 0 ? remainingParts[0] : null\n nextRemainingParts =\n remainingParts.length > 0 ? remainingParts.slice(1) : []\n }\n // else: Transparent segment (route group, __PAGE__, etc.)\n // Stay at the same known route part, don't advance URL parts\n\n // Recurse into child routes. A route tree can have multiple parallel routes\n // (e.g., @modal alongside children). Each parallel route is a separate\n // branch, but they all share the same URL - we just need to traverse all\n // branches to build out the known route tree.\n const slots = routeTree.slots\n let resultFromChildren: FulfilledRouteCacheEntry | null = null\n if (slots !== null) {\n for (const parallelRouteKey in slots) {\n const childRouteTree = slots[parallelRouteKey]\n // Skip branches with refreshState set - these were reused from a\n // different route (e.g., a \"default\" parallel slot) and don't represent\n // the actual route structure for this URL.\n if (childRouteTree.refreshState !== null) {\n continue\n }\n const result = discoverKnownRoutePart(\n knownRoutePart,\n childRouteTree,\n nextUrlPart,\n nextRemainingParts,\n existingEntry,\n now,\n pathname,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching,\n hasDynamicRewrite\n )\n // All parallel route branches share the same URL, so they should all\n // reach compatible leaf nodes. We capture any result.\n resultFromChildren = result\n }\n if (resultFromChildren !== null) {\n return resultFromChildren\n }\n // Defensive fallback: no children returned a result. This shouldn't happen\n // for valid route trees, but handle it gracefully.\n if (existingEntry !== null) {\n return existingEntry\n }\n return writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n // Reached a page node. Create/get the route cache entry and store as a\n // pattern. First, check if there's already a pattern for this route.\n if (knownRoutePart.pattern !== null) {\n // If this route has a dynamic rewrite, mark the existing pattern.\n if (hasDynamicRewrite) {\n knownRoutePart.pattern.hasDynamicRewrite = true\n }\n return knownRoutePart.pattern\n }\n\n // Get or create the entry\n let entry: FulfilledRouteCacheEntry\n if (existingEntry !== null) {\n // Already have a fulfilled entry, use it directly. It's already in the\n // route cache map.\n entry = existingEntry\n } else {\n // Create the entry and insert it into the route cache map.\n entry = writeRouteIntoCache(\n now,\n pathname as NormalizedPathname,\n nextUrl,\n fullTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n }\n\n if (hasDynamicRewrite) {\n entry.hasDynamicRewrite = true\n }\n\n // Store as pattern\n knownRoutePart.pattern = entry\n return entry\n}\n\n/**\n * Attempts to match a URL against learned route patterns.\n *\n * Returns a synthetic FulfilledRouteCacheEntry if the URL matches a known\n * pattern, or null if no match is found (fall back to server resolution).\n */\nexport function matchKnownRoute(\n pathname: string,\n search: NormalizedSearch\n): FulfilledRouteCacheEntry | null {\n const pathnameParts = pathname.split('/').filter((p) => p !== '')\n const resolvedParams: ResolvedParams = new Map()\n const match = matchKnownRoutePart(\n knownRouteTreeRoot,\n pathnameParts,\n 0,\n resolvedParams\n )\n\n if (match === null) {\n return null\n }\n\n const matchedPart = match.part\n const pattern = match.pattern\n\n // If the pattern could be intercepted, we can't safely use it for prediction.\n // Interception routes resolve to different route trees depending on the\n // referrer (the Next-Url header), which means the same URL can map to\n // different page components depending on where the navigation originated.\n // Since the known route tree only stores a single pattern per URL shape, we\n // can't distinguish between the intercepted and non-intercepted cases, so we\n // bail out to server resolution.\n //\n // TODO: We could store interception behavior in the known route tree itself\n // (e.g., which segments use interception markers and what they resolve to).\n // With enough information embedded in the trie, we could match interception\n // routes entirely on the client without a server round-trip.\n if (pattern.couldBeIntercepted) {\n return null\n }\n\n // \"Reify\" the pattern: clone the template tree with concrete param values.\n // This substitutes resolved params (e.g., slug: \"hello\") into dynamic\n // segments and recomputes vary paths for correct segment cache keying.\n const acc: ReifyAccumulator = { metadataVaryPath: null }\n const reifiedTree = reifyRouteTree(\n pattern.tree,\n resolvedParams,\n search,\n null, // Start with null partial vary path at the root\n acc\n )\n\n // The metadata tree is a flat page node without the intermediate layout\n // structure. Clone it with the updated metadata vary path collected during\n // the main tree traversal.\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n // This shouldn't be reachable for a valid route tree.\n return null\n }\n const reifiedMetadata = createMetadataRouteTree(metadataVaryPath)\n\n // Create a synthetic (predicted) entry and store it as the new pattern.\n //\n // Why replace the pattern? We intentionally update the pattern with this\n // synthetic entry so that if our prediction was wrong (server returns a\n // different pathname due to dynamic rewrite), the entry gets marked with\n // hasDynamicRewrite. Future predictions for this route will see the flag\n // and bail out to server resolution instead of making the same mistake.\n const syntheticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: pathname + search,\n status: EntryStatus.Fulfilled,\n blockedTasks: null,\n tree: reifiedTree,\n metadata: reifiedMetadata,\n couldBeIntercepted: pattern.couldBeIntercepted,\n supportsPerSegmentPrefetching: pattern.supportsPerSegmentPrefetching,\n hasDynamicRewrite: false,\n renderedSearch: search,\n ref: null,\n size: pattern.size,\n staleAt: pattern.staleAt,\n version: pattern.version,\n }\n\n matchedPart.pattern = syntheticEntry\n\n return syntheticEntry\n}\n\n/**\n * Result of a successful match: the matched tree node and its pattern.\n * We return both because the caller needs to update the pattern after\n * creating a synthetic entry (for dynamic rewrite detection).\n */\ntype KnownRouteMatch = {\n part: KnownRoutePart\n pattern: FulfilledRouteCacheEntry\n} | null\n\n/**\n * Recursively matches a URL against the known route tree.\n *\n * Matching priority (most specific first):\n * 1. Static children - exact path segment match\n * 2. Dynamic child - [param], [...param], [[...param]]\n * 3. Direct pattern - when no more URL parts remain\n *\n * Collects resolved param values in resolvedParams as it traverses.\n * Returns null if no match found (caller should fall back to server).\n */\nfunction matchKnownRoutePart(\n part: KnownRoutePart,\n pathnameParts: string[],\n partIndex: number,\n resolvedParams: ResolvedParams\n): KnownRouteMatch {\n const urlPart =\n partIndex < pathnameParts.length ? pathnameParts[partIndex] : null\n\n // If staticChildren is null, we don't know what static routes exist at this\n // level. This happens in webpack dev mode where routes are compiled\n // on-demand. We can't safely match a dynamicChild because the URL part might\n // be a static sibling we haven't discovered yet. Example: We know\n // /blog/[slug] exists, but haven't compiled /blog/featured. A request for\n // /blog/featured would incorrectly match /blog/[slug].\n if (part.staticChildren === null) {\n // The only safe match is a direct pattern when no URL parts remain.\n if (urlPart === null) {\n const pattern = part.pattern\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n return null\n }\n\n // Static children take priority over dynamic. This ensures /blog/featured\n // matches its own route rather than /blog/[slug].\n if (urlPart !== null) {\n const staticChild = part.staticChildren.get(urlPart)\n if (staticChild !== undefined) {\n // Check if this is an \"unknown\" placeholder part. These are created when\n // we learn about static siblings (from the route tree's staticSiblings\n // field) but haven't prefetched them yet. We know the path exists but\n // don't know its structure, so we can't predict it.\n if (\n staticChild.pattern === null &&\n staticChild.dynamicChild === null &&\n staticChild.staticChildren === null\n ) {\n // Bail out - server must resolve this route.\n return null\n }\n const match = matchKnownRoutePart(\n staticChild,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n if (match !== null) {\n return match\n }\n // Static child is a real node (not a placeholder) but its subtree\n // didn't match the remaining URL parts. This means the route exists\n // in the static subtree but hasn't been fully discovered yet. Do not\n // fall through to try the dynamic child — the static match is\n // authoritative. Bail out to server resolution.\n return null\n }\n }\n\n // Try dynamic child\n if (part.dynamicChild !== null) {\n const dynamicPart = part.dynamicChild\n const paramName = part.dynamicChildParamName\n const paramType = part.dynamicChildParamType\n const dynamicPattern = dynamicPart.pattern\n\n switch (paramType) {\n case 'c':\n // Required catch-all [...param]: consumes 1+ URL parts\n if (\n dynamicPattern !== null &&\n !dynamicPattern.hasDynamicRewrite &&\n urlPart !== null\n ) {\n resolvedParams.set(paramName, pathnameParts.slice(partIndex))\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n break\n case 'oc':\n // Optional catch-all [[...param]]: consumes 0+ URL parts\n if (dynamicPattern !== null && !dynamicPattern.hasDynamicRewrite) {\n if (urlPart !== null) {\n resolvedParams.set(paramName, pathnameParts.slice(partIndex))\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n // urlPart is null - can match with zero parts, but a direct pattern\n // (e.g., page.tsx alongside [[...param]]) takes precedence.\n if (part.pattern === null || part.pattern.hasDynamicRewrite) {\n resolvedParams.set(paramName, [])\n return { part: dynamicPart, pattern: dynamicPattern }\n }\n }\n break\n case 'd':\n // Regular dynamic [param]: consumes exactly 1 URL part.\n // Unlike catch-all which terminates here, regular dynamic must\n // continue recursing to find the leaf pattern.\n if (urlPart !== null) {\n resolvedParams.set(paramName, urlPart)\n return matchKnownRoutePart(\n dynamicPart,\n pathnameParts,\n partIndex + 1,\n resolvedParams\n )\n }\n break\n // Intercepted routes use relative path markers like (.), (..), (...)\n // Their behavior depends on navigation context (soft vs hard nav),\n // so we can't predict them client-side. Defer to server.\n case 'ci(..)(..)':\n case 'ci(.)':\n case 'ci(..)':\n case 'ci(...)':\n case 'di(..)(..)':\n case 'di(.)':\n case 'di(..)':\n case 'di(...)':\n return null\n default:\n paramType satisfies never\n }\n }\n\n // No children matched. If we've consumed all URL parts, check for a direct\n // pattern at this node (the route terminates here).\n if (urlPart === null) {\n const pattern = part.pattern\n if (pattern !== null && !pattern.hasDynamicRewrite) {\n return { part, pattern }\n }\n }\n\n return null\n}\n\n/**\n * Accumulator for collecting data during reifyRouteTree traversal.\n * metadataVaryPath is collected from the first page node encountered\n * (parallel routes may have multiple pages, but metadata uses the first).\n */\ntype ReifyAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\n/**\n * \"Reify\" means to make concrete - we take an abstract pattern (the template\n * route tree) and produce a concrete instance with actual param values.\n *\n * This function clones a RouteTree, substituting dynamic segment values from\n * resolvedParams and computing new vary paths. The vary path encodes param\n * values so segment cache entries can be correctly keyed.\n *\n * Example: Pattern for /blog/[slug] with resolvedParams { slug: \"hello\" }\n * produces a tree where segment [slug] has cacheKey \"hello\".\n */\nfunction reifyRouteTree(\n pattern: RouteTree,\n resolvedParams: ResolvedParams,\n search: NormalizedSearch,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n acc: ReifyAccumulator\n): RouteTree {\n const originalSegment = pattern.segment\n\n let newSegment = originalSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n\n if (typeof originalSegment !== 'string') {\n // Dynamic segment: compute new cache key and append to partial vary path\n const paramName = originalSegment[0]\n const paramType = originalSegment[2]\n const staticSiblings = originalSegment[3]\n const newValue = resolvedParams.get(paramName)\n if (newValue !== undefined) {\n const newCacheKey = Array.isArray(newValue)\n ? newValue.join('/')\n : newValue\n newSegment = [paramName, newCacheKey, paramType, staticSiblings]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n newCacheKey,\n paramName\n )\n } else {\n // Param not found in resolvedParams - keep original and inherit partial\n // TODO: This should never happen. Bail out with null.\n partialVaryPath = parentPartialVaryPath\n }\n } else {\n // Static segment: inherit partial vary path from parent\n partialVaryPath = parentPartialVaryPath\n }\n\n // Recurse into children with the (possibly updated) partial vary path\n let newSlots: Record<string, RouteTree> | null = null\n if (pattern.slots !== null) {\n newSlots = {}\n for (const key in pattern.slots) {\n newSlots[key] = reifyRouteTree(\n pattern.slots[key],\n resolvedParams,\n search,\n partialVaryPath,\n acc\n )\n }\n }\n\n if (pattern.isPage) {\n // Page segment: finalize with search params\n const newVaryPath = finalizePageVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n // Collect metadata vary path (first page wins, same as original algorithm)\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n pattern.requestKey,\n search,\n partialVaryPath\n )\n }\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n refreshState: pattern.refreshState,\n slots: newSlots,\n\n prefetchHints: pattern.prefetchHints,\n isPage: true,\n varyPath: newVaryPath,\n }\n } else {\n // Layout segment: finalize without search params\n const newVaryPath = finalizeLayoutVaryPath(\n pattern.requestKey,\n partialVaryPath\n )\n return {\n requestKey: pattern.requestKey,\n segment: newSegment,\n refreshState: pattern.refreshState,\n slots: newSlots,\n\n prefetchHints: pattern.prefetchHints,\n isPage: false,\n varyPath: newVaryPath,\n }\n }\n}\n\n/**\n * Resets the known route tree. Called during development when routes may\n * change due to hot reloading.\n */\nexport function resetKnownRoutes(): void {\n knownRouteTreeRoot = createEmptyPart()\n}\n","import type {\n CacheNodeSeedData,\n FlightRouterState,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData, ScrollRef } from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport {\n PAGE_SEGMENT_KEY,\n DEFAULT_SEGMENT_KEY,\n NOT_FOUND_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\nimport { createHrefFromUrl } from './create-href-from-url'\nimport { fetchServerResponse } from './fetch-server-response'\nimport { dispatchAppRouterAction } from '../use-action-queue'\nimport {\n ACTION_SERVER_PATCH,\n type ServerPatchAction,\n} from './router-reducer-types'\nimport { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'\nimport { getLastCommittedTree } from './reducers/committed-state'\nimport {\n convertServerPatchToFullTree,\n type NavigationSeed,\n} from '../segment-cache/navigation'\nimport {\n type RouteTree,\n type RefreshState,\n type FulfilledRouteCacheEntry,\n convertReusedFlightRouterStateToRouteTree,\n readSegmentCacheEntry,\n waitForSegmentCacheEntry,\n markRouteEntryAsDynamicRewrite,\n invalidateRouteCacheEntries,\n getStaleAt,\n writeStaticStageResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n EntryStatus,\n} from '../segment-cache/cache'\nimport { FetchStrategy } from '../segment-cache/types'\nimport { discoverKnownRoute } from '../segment-cache/optimistic-routes'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport {\n getRenderedSearchFromVaryPath,\n type PageVaryPath,\n} from '../segment-cache/vary-path'\nimport {\n readFromBFCache,\n readFromBFCacheDuringRegularNavigation,\n writeToBFCache,\n writeHeadToBFCache,\n updateBFCacheEntryStaleAt,\n computeDynamicStaleAt,\n} from '../segment-cache/bfcache'\n\n// This is yet another tree type that is used to track pending promises that\n// need to be fulfilled once the dynamic data is received. The terminal nodes of\n// this tree represent the new Cache Node trees that were created during this\n// request. We can't use the Cache Node tree or Route State tree directly\n// because those include reused nodes, too. This tree is discarded as soon as\n// the navigation response is received.\nexport type NavigationTask = {\n status: NavigationTaskStatus\n // The router state that corresponds to the tree that this Task represents.\n route: FlightRouterState\n // The CacheNode that corresponds to the tree that this Task represents.\n node: CacheNode\n // The tree sent to the server during the dynamic request. If all the segments\n // are static, then this will be null, and no server request is required.\n // Otherwise, this is the same as `route`, except with the `refetch` marker\n // set on the top-most segment that needs to be fetched.\n dynamicRequestTree: FlightRouterState | null\n // The URL that should be used to fetch the dynamic data. This is only set\n // when the segment cannot be refetched from the current route, because it's\n // part of a \"default\" parallel slot that was reused during a navigation.\n refreshState: RefreshState | null\n children: Map<string, NavigationTask> | null\n}\n\nexport const enum FreshnessPolicy {\n Default,\n Hydration,\n HistoryTraversal,\n RefreshAll,\n HMRRefresh,\n Gesture,\n}\n\nconst enum NavigationTaskStatus {\n Pending,\n Fulfilled,\n Rejected,\n}\n\n/**\n * When a NavigationTask finishes, there may or may not be data still missing,\n * necessitating a retry.\n */\nconst enum NavigationTaskExitStatus {\n /**\n * No additional navigation is required.\n */\n Done = 0,\n /**\n * Some data failed to load, presumably due to a route tree mismatch. Perform\n * a soft retry to reload the entire tree.\n */\n SoftRetry = 1,\n /**\n * Some data failed to load in an unrecoverable way, e.g. in an inactive\n * parallel route. Fall back to a hard (MPA-style) retry.\n */\n HardRetry = 2,\n}\n\nexport type NavigationRequestAccumulation = {\n separateRefreshUrls: Set<string> | null\n /**\n * Set when a navigation creates new leaf segments that should be\n * scrolled to. Stays null when no new segments are created (e.g.\n * during a refresh where the route structure didn't change).\n */\n scrollRef: ScrollRef | null\n}\n\nconst noop = () => {}\n\nexport function createInitialCacheNodeForHydration(\n navigatedAt: number,\n initialTree: RouteTree,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData,\n seedDynamicStaleAt: number\n): NavigationTask {\n // Create the initial cache node tree, using the data embedded into the\n // HTML document.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n const task = createCacheNodeOnNavigation(\n navigatedAt,\n initialTree,\n null,\n FreshnessPolicy.Hydration,\n seedData,\n seedHead,\n seedDynamicStaleAt,\n false,\n accumulation\n )\n return task\n}\n\n// Creates a new Cache Node tree (i.e. copy-on-write) that represents the\n// optimistic result of a navigation, using both the current Cache Node tree and\n// data that was prefetched prior to navigation.\n//\n// At the moment we call this function, we haven't yet received the navigation\n// response from the server. It could send back something completely different\n// from the tree that was prefetched — due to rewrites, default routes, parallel\n// routes, etc.\n//\n// But in most cases, it will return the same tree that we prefetched, just with\n// the dynamic holes filled in. So we optimistically assume this will happen,\n// and accept that the real result could be arbitrarily different.\n//\n// We'll reuse anything that was already in the previous tree, since that's what\n// the server does.\n//\n// New segments (ones that don't appear in the old tree) are assigned an\n// unresolved promise. The data for these promises will be fulfilled later, when\n// the navigation response is received.\n//\n// The tree can be rendered immediately after it is created (that's why this is\n// a synchronous function). Any new trees that do not have prefetch data will\n// suspend during rendering, until the dynamic data streams in.\n//\n// Returns a Task object, which contains both the updated Cache Node and a path\n// to the pending subtrees that need to be resolved by the navigation response.\n//\n// A return value of `null` means there were no changes, and the previous tree\n// can be reused without initiating a server request.\nexport function startPPRNavigation(\n navigatedAt: number,\n oldUrl: URL,\n oldRenderedSearch: string,\n oldCacheNode: CacheNode | null,\n oldRouterState: FlightRouterState,\n newRouteTree: RouteTree,\n newMetadataVaryPath: PageVaryPath | null,\n freshness: FreshnessPolicy,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData | null,\n seedDynamicStaleAt: number,\n isSamePageNavigation: boolean,\n accumulation: NavigationRequestAccumulation\n): NavigationTask | null {\n const didFindRootLayout = false\n const parentNeedsDynamicRequest = false\n const parentRefreshState = null\n const oldRootRefreshState: RefreshState = {\n canonicalUrl: createHrefFromUrl(oldUrl),\n renderedSearch: oldRenderedSearch as NormalizedSearch,\n }\n return updateCacheNodeOnNavigation(\n navigatedAt,\n oldUrl,\n oldCacheNode !== null ? oldCacheNode : undefined,\n oldRouterState,\n newRouteTree,\n newMetadataVaryPath,\n freshness,\n didFindRootLayout,\n seedData,\n seedHead,\n seedDynamicStaleAt,\n isSamePageNavigation,\n parentNeedsDynamicRequest,\n oldRootRefreshState,\n parentRefreshState,\n accumulation\n )\n}\n\nfunction updateCacheNodeOnNavigation(\n navigatedAt: number,\n oldUrl: URL,\n oldCacheNode: CacheNode | void,\n oldRouterState: FlightRouterState,\n newRouteTree: RouteTree,\n newMetadataVaryPath: PageVaryPath | null,\n freshness: FreshnessPolicy,\n didFindRootLayout: boolean,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData | null,\n seedDynamicStaleAt: number,\n isSamePageNavigation: boolean,\n parentNeedsDynamicRequest: boolean,\n oldRootRefreshState: RefreshState,\n parentRefreshState: RefreshState | null,\n accumulation: NavigationRequestAccumulation\n): NavigationTask | null {\n // Check if this segment matches the one in the previous route.\n const oldSegment = oldRouterState[0]\n const newSegment = createSegmentFromRouteTree(newRouteTree)\n if (!matchSegment(newSegment, oldSegment)) {\n // This segment does not match the previous route. We're now entering the\n // new part of the target route. Switch to the \"create\" path.\n if (\n // Check if the route tree changed before we reached a layout. (The\n // highest-level layout in a route tree is referred to as the \"root\"\n // layout.) This could mean that we're navigating between two different\n // root layouts. When this happens, we perform a full-page (MPA-style)\n // navigation.\n //\n // However, the algorithm for deciding where to start rendering a route\n // (i.e. the one performed in order to reach this function) is stricter\n // than the one used to detect a change in the root layout. So just\n // because we're re-rendering a segment outside of the root layout does\n // not mean we should trigger a full-page navigation.\n //\n // Specifically, we handle dynamic parameters differently: two segments\n // are considered the same even if their parameter values are different.\n //\n // Refer to isNavigatingToNewRootLayout for details.\n //\n // Note that we only have to perform this extra traversal if we didn't\n // already discover a root layout in the part of the tree that is\n // unchanged. We also only need to compare the subtree that is not\n // shared. In the common case, this branch is skipped completely.\n (!didFindRootLayout &&\n isNavigatingToNewRootLayout(oldRouterState, newRouteTree)) ||\n // The global Not Found route (app/global-not-found.tsx) is a special\n // case, because it acts like a root layout, but in the router tree, it\n // is rendered in the same position as app/layout.tsx.\n //\n // Any navigation to the global Not Found route should trigger a\n // full-page navigation.\n //\n // TODO: We should probably model this by changing the key of the root\n // segment when this happens. Then the root layout check would work\n // as expected, without a special case.\n newSegment === NOT_FOUND_SEGMENT_KEY\n ) {\n return null\n }\n return createCacheNodeOnNavigation(\n navigatedAt,\n newRouteTree,\n newMetadataVaryPath,\n freshness,\n seedData,\n seedHead,\n seedDynamicStaleAt,\n parentNeedsDynamicRequest,\n accumulation\n )\n }\n\n const newSlots = newRouteTree.slots\n const oldRouterStateChildren = oldRouterState[1]\n const seedDataChildren = seedData !== null ? seedData[1] : null\n\n // We're currently traversing the part of the tree that was also part of\n // the previous route. If we discover a root layout, then we don't need to\n // trigger an MPA navigation.\n const childDidFindRootLayout =\n didFindRootLayout ||\n (newRouteTree.prefetchHints & PrefetchHint.IsRootLayout) !== 0\n\n let shouldRefreshDynamicData: boolean = false\n switch (freshness) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Hydration:\n case FreshnessPolicy.Gesture:\n shouldRefreshDynamicData = false\n break\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n shouldRefreshDynamicData = true\n break\n default:\n freshness satisfies never\n break\n }\n\n // TODO: We're not consistent about how we do this check. Some places\n // check if the segment starts with PAGE_SEGMENT_KEY, but most seem to\n // check if there any any children, which is why I'm doing it here. We\n // should probably encode an empty children set as `null` though. Either\n // way, we should update all the checks to be consistent.\n const isLeafSegment = newSlots === null\n\n // Get the data for this segment. Since it was part of the previous route,\n // usually we just clone the data from the old CacheNode. However, during a\n // refresh or a revalidation, there won't be any existing CacheNode. So we\n // may need to consult the prefetch cache, like we would for a new segment.\n let newCacheNode: CacheNode\n let needsDynamicRequest: boolean\n if (\n oldCacheNode !== undefined &&\n !shouldRefreshDynamicData &&\n // During a same-page navigation, we always refetch the page segments\n !(isLeafSegment && isSamePageNavigation)\n ) {\n // Reuse the existing CacheNode\n const dropPrefetchRsc = false\n newCacheNode = reuseSharedCacheNode(dropPrefetchRsc, oldCacheNode)\n needsDynamicRequest = false\n } else {\n // If this is part of a refresh, ignore the existing CacheNode and create a\n // new one.\n const seedRsc = seedData !== null ? seedData[0] : null\n const result = createCacheNodeForSegment(\n navigatedAt,\n newRouteTree,\n seedRsc,\n newMetadataVaryPath,\n seedHead,\n freshness,\n seedDynamicStaleAt\n )\n newCacheNode = result.cacheNode\n needsDynamicRequest = result.needsDynamicRequest\n\n // Carry forward the old node's scrollRef. This preserves scroll\n // intent when a prior navigation's cache node is replaced by a\n // refresh before the scroll handler has had a chance to fire —\n // e.g. when router.push() and router.refresh() are called in the\n // same startTransition batch.\n if (oldCacheNode !== undefined) {\n newCacheNode.scrollRef = oldCacheNode.scrollRef\n }\n }\n\n // During a refresh navigation, there's a special case that happens when\n // entering a \"default\" slot. The default slot may not be part of the\n // current route; it may have been reused from an older route. If so,\n // we need to fetch its data from the old route's URL rather than current\n // route's URL. Keep track of this as we traverse the tree.\n const maybeRefreshState = newRouteTree.refreshState\n const refreshState =\n maybeRefreshState !== undefined && maybeRefreshState !== null\n ? // This segment is not present in the current route. Track its\n // refresh URL as we continue traversing the tree.\n maybeRefreshState\n : // Inherit the refresh URL from the parent.\n parentRefreshState\n\n // If this segment itself needs to fetch new data from the server, then by\n // definition it is being refreshed. Track its refresh URL so we know which\n // URL to request the data from.\n if (needsDynamicRequest && refreshState !== null) {\n accumulateRefreshUrl(accumulation, refreshState)\n }\n\n // As we diff the trees, we may sometimes modify (copy-on-write, not mutate)\n // the Route Tree that was returned by the server — for example, in the case\n // of default parallel routes, we preserve the currently active segment. To\n // avoid mutating the original tree, we clone the router state children along\n // the return path.\n let patchedRouterStateChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let taskChildren = null\n\n // Most navigations require a request to fetch additional data from the\n // server, either because the data was not already prefetched, or because the\n // target route contains dynamic data that cannot be prefetched.\n //\n // However, if the target route is fully static, and it's already completely\n // loaded into the segment cache, then we can skip the server request.\n //\n // This starts off as `false`, and is set to `true` if any of the child\n // routes requires a dynamic request.\n let childNeedsDynamicRequest = false\n // As we traverse the children, we'll construct a FlightRouterState that can\n // be sent to the server to request the dynamic data. If it turns out that\n // nothing in the subtree is dynamic (i.e. childNeedsDynamicRequest is false\n // at the end), then this will be discarded.\n // TODO: We can probably optimize the format of this data structure to only\n // include paths that are dynamic. Instead of reusing the\n // FlightRouterState type.\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n\n let newCacheNodeSlots: Record<string, CacheNode> | null = null\n if (newSlots !== null) {\n const oldCacheNodeSlots =\n oldCacheNode !== undefined ? oldCacheNode.slots : null\n\n newCacheNode.slots = newCacheNodeSlots = {}\n taskChildren = new Map()\n for (let parallelRouteKey in newSlots) {\n let newRouteTreeChild: RouteTree = newSlots[parallelRouteKey]\n const oldRouterStateChild: FlightRouterState | void =\n oldRouterStateChildren[parallelRouteKey]\n if (oldRouterStateChild === undefined) {\n // This should never happen, but if it does, it suggests a malformed\n // server response. Trigger a full-page navigation.\n return null\n }\n\n let seedDataChild: CacheNodeSeedData | void | null =\n seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null\n\n const oldSegmentChild = oldRouterStateChild[0]\n let newSegmentChild = createSegmentFromRouteTree(newRouteTreeChild)\n let seedHeadChild = seedHead\n if (\n // Skip this branch during a history traversal. We restore the tree that\n // was stashed in the history entry as-is.\n freshness !== FreshnessPolicy.HistoryTraversal &&\n newSegmentChild === DEFAULT_SEGMENT_KEY &&\n oldSegmentChild !== DEFAULT_SEGMENT_KEY\n ) {\n // This is a \"default\" segment. These are never sent by the server during\n // a soft navigation; instead, the client reuses whatever segment was\n // already active in that slot on the previous route.\n newRouteTreeChild = reuseActiveSegmentInDefaultSlot(\n newRouteTree,\n parallelRouteKey,\n oldRootRefreshState,\n oldRouterStateChild\n )\n newSegmentChild = createSegmentFromRouteTree(newRouteTreeChild)\n\n // Since we're switching to a different route tree, these are no\n // longer valid, because they correspond to the outer tree.\n seedDataChild = null\n seedHeadChild = null\n }\n\n const oldCacheNodeChild =\n oldCacheNodeSlots !== null\n ? oldCacheNodeSlots[parallelRouteKey]\n : undefined\n\n const taskChild = updateCacheNodeOnNavigation(\n navigatedAt,\n oldUrl,\n oldCacheNodeChild,\n oldRouterStateChild,\n newRouteTreeChild,\n newMetadataVaryPath,\n freshness,\n childDidFindRootLayout,\n seedDataChild ?? null,\n seedHeadChild,\n seedDynamicStaleAt,\n isSamePageNavigation,\n parentNeedsDynamicRequest || needsDynamicRequest,\n oldRootRefreshState,\n refreshState,\n accumulation\n )\n\n if (taskChild === null) {\n // One of the child tasks discovered a change to the root layout.\n // Immediately unwind from this recursive traversal. This will trigger a\n // full-page navigation.\n return null\n }\n\n // Recursively propagate up the child tasks.\n taskChildren.set(parallelRouteKey, taskChild)\n newCacheNodeSlots[parallelRouteKey] = taskChild.node\n\n // The child tree's route state may be different from the prefetched\n // route sent by the server. We need to clone it as we traverse back up\n // the tree.\n const taskChildRoute = taskChild.route\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n if (dynamicRequestTreeChild !== null) {\n // Something in the child tree is dynamic.\n childNeedsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n }\n }\n }\n\n const newFlightRouterState: FlightRouterState = [\n createSegmentFromRouteTree(newRouteTree),\n patchedRouterStateChildren,\n refreshState !== null\n ? [refreshState.canonicalUrl, refreshState.renderedSearch]\n : null,\n null,\n newRouteTree.prefetchHints,\n ]\n\n return {\n status: needsDynamicRequest\n ? NavigationTaskStatus.Pending\n : NavigationTaskStatus.Fulfilled,\n route: newFlightRouterState,\n node: newCacheNode,\n dynamicRequestTree: createDynamicRequestTree(\n newFlightRouterState,\n dynamicRequestTreeChildren,\n needsDynamicRequest,\n childNeedsDynamicRequest,\n parentNeedsDynamicRequest\n ),\n refreshState,\n children: taskChildren,\n }\n}\n\n/**\n * Assigns a ScrollRef to a new leaf CacheNode so the scroll handler\n * knows to scroll to it after navigation. All leaves in the same\n * navigation share the same ScrollRef — the first segment to scroll\n * consumes it, preventing others from also scrolling.\n *\n * This is only called inside `createCacheNodeOnNavigation`, which only\n * runs when segments diverge from the previous route. So for a refresh\n * where the route structure stays the same, segments match, the update\n * path is taken, and this function is never called — no scroll ref is\n * assigned. A scroll ref is only assigned when the route actually\n * changed (e.g. a redirect, or a dynamic condition on the server that\n * produces a different route).\n *\n * Skipped during hydration (initial render should not scroll) and\n * history traversal (scroll restoration is handled separately).\n */\nfunction accumulateScrollRef(\n freshness: FreshnessPolicy,\n cacheNode: CacheNode,\n accumulation: NavigationRequestAccumulation\n): void {\n switch (freshness) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.Gesture:\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n if (accumulation.scrollRef === null) {\n accumulation.scrollRef = { current: true }\n }\n cacheNode.scrollRef = accumulation.scrollRef\n break\n case FreshnessPolicy.Hydration:\n // Initial render — no scroll.\n break\n case FreshnessPolicy.HistoryTraversal:\n // Back/forward — scroll restoration is handled separately.\n break\n default:\n freshness satisfies never\n break\n }\n}\n\nfunction createCacheNodeOnNavigation(\n navigatedAt: number,\n newRouteTree: RouteTree,\n newMetadataVaryPath: PageVaryPath | null,\n freshness: FreshnessPolicy,\n seedData: CacheNodeSeedData | null,\n seedHead: HeadData | null,\n seedDynamicStaleAt: number,\n parentNeedsDynamicRequest: boolean,\n accumulation: NavigationRequestAccumulation\n): NavigationTask {\n // Same traversal as updateCacheNodeNavigation, but simpler. We switch to this\n // path once we reach the part of the tree that was not in the previous route.\n // We don't need to diff against the old tree, we just need to create a new\n // one. We also don't need to worry about any refresh-related logic.\n //\n // For the most part, this is a subset of updateCacheNodeOnNavigation, so any\n // change that happens in this function likely needs to be applied to that\n // one, too. However there are some places where the behavior intentionally\n // diverges, which is why we keep them separate.\n\n const newSegment = createSegmentFromRouteTree(newRouteTree)\n\n const newSlots = newRouteTree.slots\n const seedDataChildren = seedData !== null ? seedData[1] : null\n\n const seedRsc = seedData !== null ? seedData[0] : null\n const result = createCacheNodeForSegment(\n navigatedAt,\n newRouteTree,\n seedRsc,\n newMetadataVaryPath,\n seedHead,\n freshness,\n seedDynamicStaleAt\n )\n const newCacheNode = result.cacheNode\n const needsDynamicRequest = result.needsDynamicRequest\n\n const isLeafSegment = newSlots === null\n if (isLeafSegment) {\n accumulateScrollRef(freshness, newCacheNode, accumulation)\n }\n\n let patchedRouterStateChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n let taskChildren = null\n\n let childNeedsDynamicRequest = false\n let dynamicRequestTreeChildren: {\n [parallelRouteKey: string]: FlightRouterState\n } = {}\n\n let newCacheNodeSlots: Record<string, CacheNode> | null = null\n if (newSlots !== null) {\n newCacheNode.slots = newCacheNodeSlots = {}\n taskChildren = new Map()\n for (let parallelRouteKey in newSlots) {\n const newRouteTreeChild: RouteTree = newSlots[parallelRouteKey]\n const seedDataChild: CacheNodeSeedData | void | null =\n seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null\n\n const taskChild = createCacheNodeOnNavigation(\n navigatedAt,\n newRouteTreeChild,\n newMetadataVaryPath,\n freshness,\n seedDataChild ?? null,\n seedHead,\n seedDynamicStaleAt,\n parentNeedsDynamicRequest || needsDynamicRequest,\n accumulation\n )\n\n taskChildren.set(parallelRouteKey, taskChild)\n newCacheNodeSlots[parallelRouteKey] = taskChild.node\n\n const taskChildRoute = taskChild.route\n patchedRouterStateChildren[parallelRouteKey] = taskChildRoute\n\n const dynamicRequestTreeChild = taskChild.dynamicRequestTree\n if (dynamicRequestTreeChild !== null) {\n childNeedsDynamicRequest = true\n dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild\n } else {\n dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute\n }\n }\n }\n\n const newFlightRouterState: FlightRouterState = [\n newSegment,\n patchedRouterStateChildren,\n null,\n null,\n newRouteTree.prefetchHints,\n ]\n\n return {\n status: needsDynamicRequest\n ? NavigationTaskStatus.Pending\n : NavigationTaskStatus.Fulfilled,\n route: newFlightRouterState,\n node: newCacheNode,\n dynamicRequestTree: createDynamicRequestTree(\n newFlightRouterState,\n dynamicRequestTreeChildren,\n needsDynamicRequest,\n childNeedsDynamicRequest,\n parentNeedsDynamicRequest\n ),\n // This route is not part of the current tree, so there's no reason to\n // track the refresh URL.\n refreshState: null,\n children: taskChildren,\n }\n}\n\nfunction createSegmentFromRouteTree(newRouteTree: RouteTree): Segment {\n if (newRouteTree.isPage) {\n // In a dynamic server response, the server embeds the search params into\n // the segment key, but in a static one it's omitted. The client handles\n // this inconsistency by adding the search params back right at the end.\n //\n // TODO: The only thing this is used for is to create a cache key for\n // ChildSegmentMap. But we already track the `renderedSearch` everywhere as\n // part of the varyPath. The plan is get rid of ChildSegmentMap and\n // store the page data in a CacheMap using the varyPath, like we do\n // for prefetches. Then we can remove it from the segment key.\n //\n // As an incremental step, we can grab the search params from the varyPath.\n const renderedSearch = getRenderedSearchFromVaryPath(newRouteTree.varyPath)\n if (renderedSearch === null) {\n return PAGE_SEGMENT_KEY\n }\n // This is based on equivalent logic in addSearchParamsIfPageSegment, used\n // on the server.\n const stringifiedQuery = JSON.stringify(\n Object.fromEntries(new URLSearchParams(renderedSearch))\n )\n return stringifiedQuery !== '{}'\n ? PAGE_SEGMENT_KEY + '?' + stringifiedQuery\n : PAGE_SEGMENT_KEY\n }\n return newRouteTree.segment\n}\n\nfunction patchRouterStateWithNewChildren(\n baseRouterState: FlightRouterState,\n newChildren: { [parallelRouteKey: string]: FlightRouterState }\n): FlightRouterState {\n const clone: FlightRouterState = [baseRouterState[0], newChildren]\n // Based on equivalent logic in apply-router-state-patch-to-tree, but should\n // confirm whether we need to copy all of these fields. Not sure the server\n // ever sends, e.g. the refetch marker.\n if (2 in baseRouterState) {\n clone[2] = baseRouterState[2]\n }\n if (3 in baseRouterState) {\n clone[3] = baseRouterState[3]\n }\n if (4 in baseRouterState) {\n clone[4] = baseRouterState[4]\n }\n return clone\n}\n\nfunction createDynamicRequestTree(\n newRouterState: FlightRouterState,\n dynamicRequestTreeChildren: Record<string, FlightRouterState>,\n needsDynamicRequest: boolean,\n childNeedsDynamicRequest: boolean,\n parentNeedsDynamicRequest: boolean\n): FlightRouterState | null {\n // Create a FlightRouterState that instructs the server how to render the\n // requested segment.\n //\n // Or, if neither this segment nor any of the children require a new data,\n // then we return `null` to skip the request.\n let dynamicRequestTree: FlightRouterState | null = null\n if (needsDynamicRequest) {\n dynamicRequestTree = patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\n // The \"refetch\" marker is set on the top-most segment that requires new\n // data. We can omit it if a parent was already marked.\n if (!parentNeedsDynamicRequest) {\n dynamicRequestTree[3] = 'refetch'\n }\n } else if (childNeedsDynamicRequest) {\n // This segment does not request new data, but at least one of its\n // children does.\n dynamicRequestTree = patchRouterStateWithNewChildren(\n newRouterState,\n dynamicRequestTreeChildren\n )\n } else {\n dynamicRequestTree = null\n }\n return dynamicRequestTree\n}\n\nfunction accumulateRefreshUrl(\n accumulation: NavigationRequestAccumulation,\n refreshState: RefreshState\n) {\n // This is a refresh navigation, and we're inside a \"default\" slot that's\n // not part of the current route; it was reused from an older route. In\n // order to get fresh data for this reused route, we need to issue a\n // separate request using the old route's URL.\n //\n // Track these extra URLs in the accumulated result. Later, we'll construct\n // an appropriate request for each unique URL in the final set. The reason\n // we don't do it immediately here is so we can deduplicate multiple\n // instances of the same URL into a single request. See\n // listenForDynamicRequest for more details.\n const refreshUrl = refreshState.canonicalUrl\n const separateRefreshUrls = accumulation.separateRefreshUrls\n if (separateRefreshUrls === null) {\n accumulation.separateRefreshUrls = new Set([refreshUrl])\n } else {\n separateRefreshUrls.add(refreshUrl)\n }\n}\n\nfunction reuseActiveSegmentInDefaultSlot(\n parentRouteTree: RouteTree,\n parallelRouteKey: string,\n oldRootRefreshState: RefreshState,\n oldRouterState: FlightRouterState\n): RouteTree {\n // This is a \"default\" segment. These are never sent by the server during a\n // soft navigation; instead, the client reuses whatever segment was already\n // active in that slot on the previous route. This means if we later need to\n // refresh the segment, it will have to be refetched from the previous route's\n // URL. We store it in the Flight Router State.\n\n let reusedUrl: string\n let reusedRenderedSearch: NormalizedSearch\n const oldRefreshState = oldRouterState[2]\n if (oldRefreshState !== undefined && oldRefreshState !== null) {\n // This segment was already reused from an even older route. Keep its\n // existing URL and refresh state.\n reusedUrl = oldRefreshState[0]\n reusedRenderedSearch = oldRefreshState[1] as NormalizedSearch\n } else {\n // Since this route didn't already have a refresh state, it must have been\n // reachable from the root of the old route. So we use the refresh state\n // that represents the old route.\n reusedUrl = oldRootRefreshState.canonicalUrl\n reusedRenderedSearch = oldRootRefreshState.renderedSearch\n }\n\n const acc = { metadataVaryPath: null }\n const reusedRouteTree = convertReusedFlightRouterStateToRouteTree(\n parentRouteTree,\n parallelRouteKey,\n oldRouterState,\n reusedRenderedSearch,\n acc\n )\n reusedRouteTree.refreshState = {\n canonicalUrl: reusedUrl,\n renderedSearch: reusedRenderedSearch,\n }\n return reusedRouteTree\n}\n\nfunction reuseSharedCacheNode(\n dropPrefetchRsc: boolean,\n existingCacheNode: CacheNode\n): CacheNode {\n // Clone the CacheNode that was already present in the previous tree.\n // Carry forward the scrollRef so scroll intent from a prior navigation\n // survives tree rebuilds (e.g. push + refresh in the same batch).\n return createCacheNode(\n existingCacheNode.rsc,\n dropPrefetchRsc ? null : existingCacheNode.prefetchRsc,\n existingCacheNode.head,\n dropPrefetchRsc ? null : existingCacheNode.prefetchHead,\n existingCacheNode.scrollRef\n )\n}\n\nfunction createCacheNodeForSegment(\n now: number,\n tree: RouteTree,\n seedRsc: React.ReactNode | null,\n metadataVaryPath: PageVaryPath | null,\n seedHead: HeadData | null,\n freshness: FreshnessPolicy,\n dynamicStaleAt: number\n): { cacheNode: CacheNode; needsDynamicRequest: boolean } {\n // Construct a new CacheNode using data from the BFCache, the client's\n // Segment Cache, or seeded from a server response.\n //\n // If there's a cache miss, or if we only have a partial hit, we'll render\n // the partial state immediately, and spawn a request to the server to fill\n // in the missing data.\n //\n // If the segment is fully cached on the client already, we can omit this\n // segment from the server request.\n //\n // If we already have a dynamic data response associated with this navigation,\n // as in the case of a Server Action-initiated redirect or refresh, we may\n // also be able to use that data without spawning a new request. (This is\n // referred to as the \"seed\" data.)\n\n const isPage = tree.isPage\n\n // During certain kinds of navigations, we may be able to render from\n // the BFCache.\n switch (freshness) {\n case FreshnessPolicy.Default: {\n // Check BFCache during regular navigations. The entry's staleAt\n // determines whether it's still fresh. This is used when\n // staleTimes.dynamic is configured globally or when a page exports\n // unstable_dynamicStaleTime for per-page control.\n const bfcacheEntry = readFromBFCacheDuringRegularNavigation(\n now,\n tree.varyPath\n )\n if (bfcacheEntry !== null) {\n return {\n cacheNode: createCacheNode(\n bfcacheEntry.rsc,\n bfcacheEntry.prefetchRsc,\n bfcacheEntry.head,\n bfcacheEntry.prefetchHead\n ),\n needsDynamicRequest: false,\n }\n }\n break\n }\n case FreshnessPolicy.Hydration: {\n // This is not related to the BFCache but it is a special case.\n //\n // We should never spawn network requests during hydration. We must treat\n // the initial payload as authoritative, because the initial page load is\n // used as a last-ditch mechanism for recovering the app.\n //\n // This is also an important safety check because if this leaks into the\n // server rendering path (which theoretically it never should because the\n // server payload should be consistent), the server would hang because these\n // promises would never resolve.\n //\n // TODO: There is an existing case where the global \"not found\" boundary\n // triggers this path. But it does render correctly despite that. That's an\n // unusual render path so it's not surprising, but we should look into\n // modeling it in a more consistent way. See also the /_notFound special\n // case in updateCacheNodeOnNavigation.\n const rsc = seedRsc\n const prefetchRsc = null\n const head = isPage ? seedHead : null\n const prefetchHead = null\n writeToBFCache(\n now,\n tree.varyPath,\n rsc,\n prefetchRsc,\n head,\n prefetchHead,\n dynamicStaleAt\n )\n if (isPage && metadataVaryPath !== null) {\n writeHeadToBFCache(\n now,\n metadataVaryPath,\n head,\n prefetchHead,\n dynamicStaleAt\n )\n }\n return {\n cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),\n needsDynamicRequest: false,\n }\n }\n case FreshnessPolicy.HistoryTraversal:\n const bfcacheEntry = readFromBFCache(tree.varyPath)\n if (bfcacheEntry !== null) {\n // Only show prefetched data if the dynamic data is still pending. This\n // avoids a flash back to the prefetch state in a case where it's highly\n // likely to have already streamed in.\n //\n // Tehnically, what we're actually checking is whether the dynamic\n // network response was received. But since it's a streaming response,\n // this does not mean that all the dynamic data has fully streamed in.\n // It just means that _some_ of the dynamic data was received. But as a\n // heuristic, we assume that the rest dynamic data will stream in\n // quickly, so it's still better to skip the prefetch state.\n const oldRsc = bfcacheEntry.rsc\n const oldRscDidResolve =\n !isDeferredRsc(oldRsc) || oldRsc.status !== 'pending'\n const dropPrefetchRsc = oldRscDidResolve\n return {\n cacheNode: createCacheNode(\n bfcacheEntry.rsc,\n dropPrefetchRsc ? null : bfcacheEntry.prefetchRsc,\n bfcacheEntry.head,\n dropPrefetchRsc ? null : bfcacheEntry.prefetchHead\n ),\n needsDynamicRequest: false,\n }\n }\n break\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n case FreshnessPolicy.Gesture:\n // Don't consult the BFCache.\n break\n default:\n freshness satisfies never\n break\n }\n\n let cachedRsc: React.ReactNode | null = null\n let isCachedRscPartial: boolean = true\n\n const segmentEntry = readSegmentCacheEntry(now, tree.varyPath)\n if (segmentEntry !== null) {\n switch (segmentEntry.status) {\n case EntryStatus.Fulfilled: {\n // Happy path: a cache hit\n cachedRsc = segmentEntry.rsc\n isCachedRscPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Pending: {\n // We haven't received data for this segment yet, but there's already\n // an in-progress request. Since it's extremely likely to arrive\n // before the dynamic data response, we might as well use it.\n const promiseForFulfilledEntry = waitForSegmentCacheEntry(segmentEntry)\n cachedRsc = promiseForFulfilledEntry.then((entry) =>\n entry !== null ? entry.rsc : null\n )\n // Because the request is still pending, we typically don't know yet\n // whether the response will be partial. We shouldn't skip this segment\n // during the dynamic navigation request. Otherwise, we might need to\n // do yet another request to fill in the remaining data, creating\n // a waterfall.\n //\n // The one exception is if this segment is being fetched with via\n // prefetch={true} (i.e. the \"force stale\" or \"full\" strategy). If so,\n // we can assume the response will be full. This field is set to `false`\n // for such segments.\n isCachedRscPartial = segmentEntry.isPartial\n break\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected: {\n break\n }\n default: {\n segmentEntry satisfies never\n break\n }\n }\n }\n\n // Now combine the cached data with the seed data to determine what we can\n // render immediately, versus what needs to stream in later.\n\n // A partial state to show immediately while we wait for the final data to\n // arrive. If `rsc` is already a complete value (not partial), or if we\n // don't have any useful partial state, this will be `null`.\n let prefetchRsc: React.ReactNode | null\n // The final, resolved segment data. If the data is missing, this will be a\n // promise that resolves to the eventual data. A resolved value of `null`\n // means the data failed to load; the LayoutRouter will suspend indefinitely\n // until the router updates again (refer to finishNavigationTask).\n let rsc: React.ReactNode | null\n let doesSegmentNeedDynamicRequest: boolean\n\n if (seedRsc !== null) {\n // We already have a dynamic server response for this segment.\n if (isCachedRscPartial) {\n // The seed data may still be streaming in, so it's worth showing the\n // partial cached state in the meantime.\n prefetchRsc = cachedRsc\n rsc = seedRsc\n } else {\n // We already have a completely cached segment. Ignore the seed data,\n // which may still be streaming in. This shouldn't happen in the normal\n // case because the client will inform the server which segments are\n // already fully cached, and the server will skip rendering them.\n prefetchRsc = null\n rsc = cachedRsc\n }\n doesSegmentNeedDynamicRequest = false\n } else {\n if (isCachedRscPartial) {\n // The cached data contains dynamic holes, or it's missing entirely. We'll\n // show the partial state immediately (if available), and stream in the\n // final data.\n //\n // Create a pending promise that we can later write to when the\n // data arrives from the server.\n prefetchRsc = cachedRsc\n rsc = createDeferredRsc()\n } else {\n // The data is fully cached.\n prefetchRsc = null\n rsc = cachedRsc\n }\n doesSegmentNeedDynamicRequest = isCachedRscPartial\n }\n\n // If this is a page segment, we need to do the same for the head. This\n // follows analogous logic to the segment data above.\n // TODO: We don't need to store the head on the page segment's CacheNode; we\n // can lift it to the main state object. Then we can also delete\n // findHeadCache.\n\n let prefetchHead: HeadData | null = null\n let head: React.ReactNode | null = null\n let doesHeadNeedDynamicRequest: boolean = isPage\n\n if (isPage) {\n let cachedHead: HeadData | null = null\n let isCachedHeadPartial: boolean = true\n if (metadataVaryPath !== null) {\n const metadataEntry = readSegmentCacheEntry(now, metadataVaryPath)\n if (metadataEntry !== null) {\n switch (metadataEntry.status) {\n case EntryStatus.Fulfilled: {\n cachedHead = metadataEntry.rsc\n isCachedHeadPartial = metadataEntry.isPartial\n break\n }\n case EntryStatus.Pending: {\n cachedHead = waitForSegmentCacheEntry(metadataEntry).then(\n (entry) => (entry !== null ? entry.rsc : null)\n )\n isCachedHeadPartial = metadataEntry.isPartial\n break\n }\n case EntryStatus.Empty:\n case EntryStatus.Rejected: {\n break\n }\n default: {\n metadataEntry satisfies never\n break\n }\n }\n }\n }\n\n if (process.env.__NEXT_OPTIMISTIC_ROUTING && isCachedHeadPartial) {\n // TODO: When optimistic routing is enabled, don't block on waiting for\n // the viewport to resolve. This is a temporary workaround until Vary\n // Params are tracked when rendering the metadata. We'll fix it before\n // this feature is stable. However, it's not a critical issue because 1)\n // it will stream in eventually anyway 2) metadata is wrapped in an\n // internal Suspense boundary, so is always non-blocking; this only\n // affects the viewport node, which is meant to blocking, however... 3)\n // before Segment Cache landed this wasn't always the case, anyway, so\n // it's unlikely that many people are relying on this behavior. Still,\n // will be fixed before stable. It's the very next step in the sequence of\n // work on this project.\n //\n // This line of code works because the App Router treats `null` as\n // \"no renderable head available\", rather than an empty head. React treats\n // an empty string as empty.\n cachedHead = ''\n }\n\n if (seedHead !== null) {\n if (isCachedHeadPartial) {\n prefetchHead = cachedHead\n head = seedHead\n } else {\n prefetchHead = null\n head = cachedHead\n }\n doesHeadNeedDynamicRequest = false\n } else {\n if (isCachedHeadPartial) {\n prefetchHead = cachedHead\n head = createDeferredRsc()\n } else {\n prefetchHead = null\n head = cachedHead\n }\n doesHeadNeedDynamicRequest = isCachedHeadPartial\n }\n }\n\n // Now that we're creating a new segment, write its data to the BFCache. A\n // subsequent back/forward navigation will reuse this same data, until or\n // unless it's cleared by a refresh/revalidation.\n //\n // Skip BFCache writes for optimistic navigations since they are transient\n // and will be replaced by the canonical navigation.\n if (freshness !== FreshnessPolicy.Gesture) {\n writeToBFCache(\n now,\n tree.varyPath,\n rsc,\n prefetchRsc,\n head,\n prefetchHead,\n dynamicStaleAt\n )\n if (isPage && metadataVaryPath !== null) {\n writeHeadToBFCache(\n now,\n metadataVaryPath,\n head,\n prefetchHead,\n dynamicStaleAt\n )\n }\n }\n\n return {\n cacheNode: createCacheNode(rsc, prefetchRsc, head, prefetchHead),\n // TODO: We should store this field on the CacheNode itself. I think we can\n // probably unify NavigationTask, CacheNode, and DeferredRsc into a\n // single type. Or at least CacheNode and DeferredRsc.\n needsDynamicRequest:\n doesSegmentNeedDynamicRequest || doesHeadNeedDynamicRequest,\n }\n}\n\nfunction createCacheNode(\n rsc: React.ReactNode | null,\n prefetchRsc: React.ReactNode | null,\n head: React.ReactNode | null,\n prefetchHead: HeadData | null,\n scrollRef: ScrollRef | null = null\n): CacheNode {\n return {\n rsc,\n prefetchRsc,\n head,\n prefetchHead,\n slots: null,\n scrollRef,\n }\n}\n\n// Represents whether the previuos navigation resulted in a route tree mismatch.\n// A mismatch results in a refresh of the page. If there are two successive\n// mismatches, we will fall back to an MPA navigation, to prevent a retry loop.\nlet previousNavigationDidMismatch = false\n\n// Writes a dynamic server response into the tree created by\n// updateCacheNodeOnNavigation. All pending promises that were spawned by the\n// navigation will be resolved, either with dynamic data from the server, or\n// `null` to indicate that the data is missing.\n//\n// A `null` value will trigger a lazy fetch during render, which will then patch\n// up the tree using the same mechanism as the non-PPR implementation\n// (serverPatchReducer).\n//\n// Usually, the server will respond with exactly the subset of data that we're\n// waiting for — everything below the nearest shared layout. But technically,\n// the server can return anything it wants.\n//\n// This does _not_ create a new tree; it modifies the existing one in place.\n// Which means it must follow the Suspense rules of cache safety.\nexport function spawnDynamicRequests(\n task: NavigationTask,\n primaryUrl: URL,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n accumulation: NavigationRequestAccumulation,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname than expected (indicating\n // dynamic rewrite behavior that varies by param value).\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n // The original navigation's push/replace intent. Threaded through to the\n // server-patch retry logic so it can inherit the intent if the original\n // transition hasn't committed yet.\n navigateType: 'push' | 'replace'\n): void {\n const dynamicRequestTree = task.dynamicRequestTree\n if (dynamicRequestTree === null) {\n // This navigation was fully cached. There are no dynamic requests to spawn.\n previousNavigationDidMismatch = false\n return\n }\n\n // This is intentionally not an async function to discourage the caller from\n // awaiting the result. Any subsequent async operations spawned by this\n // function should result in a separate navigation task, rather than\n // block the original one.\n //\n // In this function we spawn (but do not await) all the network requests that\n // block the navigation, and collect the promises. The next function,\n // `finishNavigationTask`, can await the promises in any order without\n // accidentally introducing a network waterfall.\n const primaryRequestPromise = fetchMissingDynamicData(\n task,\n dynamicRequestTree,\n primaryUrl,\n nextUrl,\n freshnessPolicy,\n routeCacheEntry\n )\n\n const separateRefreshUrls = accumulation.separateRefreshUrls\n let refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null = null\n if (separateRefreshUrls !== null) {\n // There are multiple URLs that we need to request the data from. This\n // happens when a \"default\" parallel route slot is present in the tree, and\n // its data cannot be fetched from the current route. We need to split the\n // combined dynamic request tree into separate requests per URL.\n\n // TODO: Create a scoped dynamic request tree that omits anything that\n // is not relevant to the given URL. Without doing this, the server may\n // sometimes render more data than necessary; this is not a regression\n // compared to the pre-Segment Cache implementation, though, just an\n // optimization we can make in the future.\n\n // Construct a request tree for each additional refresh URL. This will\n // prune away everything except the parts of the tree that match the\n // given refresh URL.\n refreshRequestPromises = []\n const canonicalUrl = createHrefFromUrl(primaryUrl)\n for (const refreshUrl of separateRefreshUrls) {\n if (refreshUrl === canonicalUrl) {\n // We already initiated a request for the this URL, above. Skip it.\n // TODO: This only happens because the main URL is not tracked as\n // part of the separateRefreshURLs set. There's probably a better way\n // to structure this so this case doesn't happen.\n continue\n }\n // TODO: Create a scoped dynamic request tree that omits anything that\n // is not relevant to the given URL. Without doing this, the server may\n // sometimes render more data than necessary; this is not a regression\n // compared to the pre-Segment Cache implementation, though, just an\n // optimization we can make in the future.\n // const scopedDynamicRequestTree = splitTaskByURL(task, refreshUrl)\n const scopedDynamicRequestTree = dynamicRequestTree\n if (scopedDynamicRequestTree !== null) {\n refreshRequestPromises.push(\n fetchMissingDynamicData(\n task,\n scopedDynamicRequestTree,\n new URL(refreshUrl, location.origin),\n // TODO: Just noticed that this should actually the Next-Url at the\n // time the refresh URL was set, not the current Next-Url. Need to\n // start tracking this alongside the refresh URL. In the meantime,\n // if a refresh fails due to a mismatch, it will trigger a\n // hard refresh.\n nextUrl,\n freshnessPolicy,\n routeCacheEntry\n )\n )\n }\n }\n }\n\n // Further async operations are moved into this separate function to\n // discourage sequential network requests.\n const voidPromise = finishNavigationTask(\n task,\n nextUrl,\n primaryRequestPromise,\n refreshRequestPromises,\n routeCacheEntry,\n navigateType\n )\n // `finishNavigationTask` is responsible for error handling, so we can attach\n // noop callbacks to this promise.\n voidPromise.then(noop, noop)\n}\n\nasync function finishNavigationTask(\n task: NavigationTask,\n nextUrl: string | null,\n primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null,\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n navigateType: 'push' | 'replace'\n): Promise<void> {\n // Wait for all the requests to finish, or for the first one to fail.\n let exitStatus = await waitForRequestsToFinish(\n primaryRequestPromise,\n refreshRequestPromises\n )\n\n // Once the all the requests have finished, check the tree for any remaining\n // pending tasks. If anything is still pending, it means the server response\n // does not match the client, and we must refresh to get back to a consistent\n // state. We can skip this step if we already detected a mismatch during the\n // first phase; it doesn't matter in that case because we're going to refresh\n // the whole tree regardless.\n if (exitStatus === NavigationTaskExitStatus.Done) {\n exitStatus = abortRemainingPendingTasks(task, null, null)\n }\n\n switch (exitStatus) {\n case NavigationTaskExitStatus.Done: {\n // The task has completely finished. There's no missing data. Exit.\n previousNavigationDidMismatch = false\n return\n }\n case NavigationTaskExitStatus.SoftRetry: {\n // Some data failed to finish loading. Trigger a soft retry.\n // TODO: As an extra precaution against soft retry loops, consider\n // tracking whether a navigation was itself triggered by a retry. If two\n // happen in a row, fall back to a hard retry.\n const isHardRetry = false\n const primaryRequestResult = await primaryRequestPromise\n dispatchRetryDueToTreeMismatch(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n task.route,\n routeCacheEntry,\n navigateType\n )\n return\n }\n case NavigationTaskExitStatus.HardRetry: {\n // Some data failed to finish loading in a non-recoverable way, such as a\n // network error. Trigger an MPA navigation.\n //\n // Hard navigating/refreshing is how we prevent an infinite retry loop\n // caused by a network error — when the network fails, we fall back to the\n // browser behavior for offline navigations. In the future, Next.js may\n // introduce its own custom handling of offline navigations, but that\n // doesn't exist yet.\n const isHardRetry = true\n const primaryRequestResult = await primaryRequestPromise\n dispatchRetryDueToTreeMismatch(\n isHardRetry,\n primaryRequestResult.url,\n nextUrl,\n primaryRequestResult.seed,\n task.route,\n routeCacheEntry,\n navigateType\n )\n return\n }\n default: {\n return exitStatus satisfies never\n }\n }\n}\n\nfunction waitForRequestsToFinish(\n primaryRequestPromise: ReturnType<typeof fetchMissingDynamicData>,\n refreshRequestPromises: Array<\n ReturnType<typeof fetchMissingDynamicData>\n > | null\n) {\n // Custom async combinator logic. This could be replaced by Promise.any but\n // we don't assume that's available.\n //\n // Each promise resolves once the server responsds and the data is written\n // into the CacheNode tree. Resolve the combined promise once all the\n // requests finish.\n //\n // Or, resolve as soon as one of the requests fails, without waiting for the\n // others to finish.\n return new Promise<NavigationTaskExitStatus>((resolve) => {\n const onFulfill = (result: { exitStatus: NavigationTaskExitStatus }) => {\n if (result.exitStatus === NavigationTaskExitStatus.Done) {\n remainingCount--\n if (remainingCount === 0) {\n // All the requests finished successfully.\n resolve(NavigationTaskExitStatus.Done)\n }\n } else {\n // One of the requests failed. Exit with a failing status.\n // NOTE: It's possible for one of the requests to fail with SoftRetry\n // and a later one to fail with HardRetry. In this case, we choose to\n // retry immediately, rather than delay the retry until all the requests\n // finish. If it fails again, we will hard retry on the next\n // attempt, anyway.\n resolve(result.exitStatus)\n }\n }\n // onReject shouldn't ever be called because fetchMissingDynamicData's\n // entire body is wrapped in a try/catch. This is just defensive.\n const onReject = () => resolve(NavigationTaskExitStatus.HardRetry)\n\n // Attach the listeners to the promises.\n let remainingCount = 1\n primaryRequestPromise.then(onFulfill, onReject)\n if (refreshRequestPromises !== null) {\n remainingCount += refreshRequestPromises.length\n refreshRequestPromises.forEach((refreshRequestPromise) =>\n refreshRequestPromise.then(onFulfill, onReject)\n )\n }\n })\n}\n\nfunction dispatchRetryDueToTreeMismatch(\n isHardRetry: boolean,\n retryUrl: URL,\n retryNextUrl: string | null,\n seed: NavigationSeed | null,\n baseTree: FlightRouterState,\n // The route cache entry used for this navigation, if it came from route\n // prediction. If the navigation results in a mismatch, we mark it as having\n // a dynamic rewrite so future predictions bail out.\n routeCacheEntry: FulfilledRouteCacheEntry | null,\n // The original navigation's push/replace intent.\n originalNavigateType: 'push' | 'replace'\n) {\n // If the navigation used a route prediction, mark it as having a dynamic\n // rewrite since it resulted in a mismatch.\n if (routeCacheEntry !== null) {\n markRouteEntryAsDynamicRewrite(routeCacheEntry)\n } else if (seed !== null) {\n // Even without a direct reference to the route cache entry, we can still\n // mark the route as having a dynamic rewrite by traversing the known route\n // tree. This handles cases where the navigation didn't originate from a\n // route prediction, but still needs to mark the pattern.\n const metadataVaryPath = seed.metadataVaryPath\n if (metadataVaryPath !== null) {\n const now = Date.now()\n discoverKnownRoute(\n now,\n retryUrl.pathname,\n retryNextUrl,\n null,\n seed.routeTree,\n metadataVaryPath,\n false, // couldBeIntercepted - doesn't matter, we're just marking hasDynamicRewrite\n createHrefFromUrl(retryUrl),\n false, // supportsPerSegmentPrefetching - doesn't matter, we're just marking hasDynamicRewrite\n true // hasDynamicRewrite\n )\n }\n }\n\n // Invalidate all route cache entries. Other entries may have been derived\n // from the template before we knew it had a dynamic rewrite. This also\n // triggers re-prefetching of visible links.\n invalidateRouteCacheEntries(retryNextUrl, baseTree)\n\n // If this is the second time in a row that a navigation resulted in a\n // mismatch, fall back to a hard (MPA) refresh.\n isHardRetry = isHardRetry || previousNavigationDidMismatch\n previousNavigationDidMismatch = true\n\n // If the original navigation hasn't committed to the browser history yet\n // (the transition suspended before React committed), inherit its push/replace\n // intent. Otherwise, the pushState already ran, so use 'replace' to avoid\n // creating a duplicate history entry.\n //\n // This works because React entangles the retry's state update with the\n // original pending transition — they commit together as a single batch,\n // so the navigate type from the retry is what HistoryUpdater ultimately sees.\n //\n // TODO: Ideally this check would happen right before we schedule the React\n // update (i.e., closer to where the action is dispatched into the queue),\n // not here where the action is constructed. But the current action queue\n // doesn't provide a natural place for that. Revisit when we refactor the\n // action queue into a more reactive navigation model.\n const lastCommitted = getLastCommittedTree()\n const retryNavigateType: 'push' | 'replace' =\n lastCommitted !== null && baseTree !== lastCommitted\n ? originalNavigateType\n : 'replace'\n\n const retryAction: ServerPatchAction = {\n type: ACTION_SERVER_PATCH,\n previousTree: baseTree,\n url: retryUrl,\n nextUrl: retryNextUrl,\n seed,\n mpa: isHardRetry,\n navigateType: retryNavigateType,\n }\n dispatchAppRouterAction(retryAction)\n}\n\nasync function fetchMissingDynamicData(\n task: NavigationTask,\n dynamicRequestTree: FlightRouterState,\n url: URL,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n routeCacheEntry: FulfilledRouteCacheEntry | null\n): Promise<{\n exitStatus: NavigationTaskExitStatus\n url: URL\n seed: NavigationSeed | null\n}> {\n try {\n const result = await fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n isHmrRefresh: freshnessPolicy === FreshnessPolicy.HMRRefresh,\n })\n if (typeof result === 'string') {\n // fetchServerResponse will return an href to indicate that the SPA\n // navigation failed. For example, if the server triggered a hard\n // redirect, or the fetch request errored. Initiate an MPA navigation\n // to the given href.\n return {\n exitStatus: NavigationTaskExitStatus.HardRetry,\n url: new URL(result, location.origin),\n seed: null,\n }\n }\n const now = Date.now()\n\n const seed = convertServerPatchToFullTree(\n now,\n task.route,\n result.flightData,\n result.renderedSearch,\n result.dynamicStaleTime\n )\n\n // If the navigation lock is active, wait for it to be released before\n // writing the dynamic data. This allows tests to assert on the prefetched\n // UI state.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n await waitForNavigationLock()\n }\n\n if (routeCacheEntry !== null && result.staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n result.staticStageData\n\n getStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n result.responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n writeStaticStageResponseIntoCache(\n now,\n staticStageResponse.f,\n buildId,\n staticStageResponse.h,\n staleAt,\n dynamicRequestTree,\n result.renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n result.runtimePrefetchStream,\n dynamicRequestTree,\n result.renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n\n // result.dynamicStaleTime is in seconds (from the server's `d` field).\n // Convert to an absolute timestamp using the centralized helper.\n const dynamicStaleAt = computeDynamicStaleAt(now, result.dynamicStaleTime)\n\n const didReceiveUnknownParallelRoute = writeDynamicDataIntoNavigationTask(\n task,\n seed.routeTree,\n seed.data,\n seed.head,\n dynamicStaleAt,\n result.debugInfo\n )\n\n return {\n exitStatus: didReceiveUnknownParallelRoute\n ? NavigationTaskExitStatus.SoftRetry\n : NavigationTaskExitStatus.Done,\n url: new URL(result.canonicalUrl, location.origin),\n seed,\n }\n } catch {\n // This shouldn't happen because fetchServerResponse's entire body is\n // wrapped in a try/catch. If it does, though, it implies the server failed\n // to respond with any tree at all. So we must fall back to a hard retry.\n return {\n exitStatus: NavigationTaskExitStatus.HardRetry,\n url: url,\n seed: null,\n }\n }\n}\n\nfunction writeDynamicDataIntoNavigationTask(\n task: NavigationTask,\n serverRouteTree: RouteTree,\n dynamicData: CacheNodeSeedData | null,\n dynamicHead: HeadData,\n dynamicStaleAt: number,\n debugInfo: Array<any> | null\n): boolean {\n if (task.status === NavigationTaskStatus.Pending && dynamicData !== null) {\n task.status = NavigationTaskStatus.Fulfilled\n finishPendingCacheNode(task.node, dynamicData, dynamicHead, debugInfo)\n\n // Update the BFCache entry's staleAt for this segment with the value\n // from the dynamic response. This applies the per-page\n // unstable_dynamicStaleTime if set, or the default DYNAMIC_STALETIME_MS.\n // We only update segments that received dynamic data — static segments\n // are unaffected.\n updateBFCacheEntryStaleAt(serverRouteTree.varyPath, dynamicStaleAt)\n }\n\n const taskChildren = task.children\n const serverChildren = serverRouteTree.slots\n const dynamicDataChildren = dynamicData !== null ? dynamicData[1] : null\n\n // Detect whether the server sends a parallel route slot that the client\n // doesn't know about.\n let didReceiveUnknownParallelRoute = false\n\n if (taskChildren !== null) {\n if (serverChildren !== null) {\n for (const parallelRouteKey in serverChildren) {\n const serverRouteTreeChild: RouteTree = serverChildren[parallelRouteKey]\n const dynamicDataChild: CacheNodeSeedData | null | void =\n dynamicDataChildren !== null\n ? dynamicDataChildren[parallelRouteKey]\n : null\n\n const taskChild = taskChildren.get(parallelRouteKey)\n if (taskChild === undefined) {\n // The server sent a child segment that the client doesn't know about.\n //\n // When we receive an unknown parallel route, we must consider it a\n // mismatch. This is unlike the case where the segment itself\n // mismatches, because multiple routes can be active simultaneously.\n // But a given layout should never have a mismatching set of\n // child slots.\n //\n // Theoretically, this should only happen in development during an HMR\n // refresh, because the set of parallel routes for a layout does not\n // change over the lifetime of a build/deployment. In production, we\n // should have already mismatched on either the build id or the segment\n // path. But as an extra precaution, we validate in prod, too.\n didReceiveUnknownParallelRoute = true\n } else {\n const taskSegment = taskChild.route[0]\n const serverSegment = createSegmentFromRouteTree(serverRouteTreeChild)\n if (\n matchSegment(serverSegment, taskSegment) &&\n dynamicDataChild !== null &&\n dynamicDataChild !== undefined\n ) {\n // Found a match for this task. Keep traversing down the task tree.\n const childDidReceiveUnknownParallelRoute =\n writeDynamicDataIntoNavigationTask(\n taskChild,\n serverRouteTreeChild,\n dynamicDataChild,\n dynamicHead,\n dynamicStaleAt,\n debugInfo\n )\n if (childDidReceiveUnknownParallelRoute) {\n didReceiveUnknownParallelRoute = true\n }\n }\n }\n }\n } else {\n if (serverChildren !== null) {\n // The server sent a child segment that the client doesn't know about.\n didReceiveUnknownParallelRoute = true\n }\n }\n }\n\n return didReceiveUnknownParallelRoute\n}\n\nfunction finishPendingCacheNode(\n cacheNode: CacheNode,\n dynamicData: CacheNodeSeedData,\n dynamicHead: HeadData,\n debugInfo: Array<any> | null\n): void {\n // Writes a dynamic response into an existing Cache Node tree. This does _not_\n // create a new tree, it updates the existing tree in-place. So it must follow\n // the Suspense rules of cache safety — it can resolve pending promises, but\n // it cannot overwrite existing data. It can add segments to the tree (because\n // a missing segment will cause the layout router to suspend).\n // but it cannot delete them.\n //\n // We must resolve every promise in the tree, or else it will suspend\n // indefinitely. If we did not receive data for a segment, we will resolve its\n // data promise to `null` to trigger a lazy fetch during render.\n\n // Use the dynamic data from the server to fulfill the deferred RSC promise\n // on the Cache Node.\n const rsc = cacheNode.rsc\n const dynamicSegmentData = dynamicData[0]\n\n if (dynamicSegmentData === null) {\n // This is an empty CacheNode; this particular server request did not\n // render this segment. There may be a separate pending request that will,\n // though, so we won't abort the task until all pending requests finish.\n return\n }\n\n if (rsc === null) {\n // This is a lazy cache node. We can overwrite it. This is only safe\n // because we know that the LayoutRouter suspends if `rsc` is `null`.\n cacheNode.rsc = dynamicSegmentData\n } else if (isDeferredRsc(rsc)) {\n // This is a deferred RSC promise. We can fulfill it with the data we just\n // received from the server. If it was already resolved by a different\n // navigation, then this does nothing because we can't overwrite data.\n rsc.resolve(dynamicSegmentData, debugInfo)\n } else {\n // This is not a deferred RSC promise, nor is it empty, so it must have\n // been populated by a different navigation. We must not overwrite it.\n }\n\n // Check if this is a leaf segment. If so, it will have a `head` property with\n // a pending promise that needs to be resolved with the dynamic head from\n // the server.\n const head = cacheNode.head\n if (isDeferredRsc(head)) {\n head.resolve(dynamicHead, debugInfo)\n }\n}\n\nfunction abortRemainingPendingTasks(\n task: NavigationTask,\n error: any,\n debugInfo: Array<any> | null\n): NavigationTaskExitStatus {\n let exitStatus\n if (task.status === NavigationTaskStatus.Pending) {\n // The data for this segment is still missing.\n task.status = NavigationTaskStatus.Rejected\n abortPendingCacheNode(task.node, error, debugInfo)\n\n // If the server failed to fulfill the data for this segment, it implies\n // that the route tree received from the server mismatched the tree that\n // was previously prefetched.\n //\n // In an app with fully static routes and no proxy-driven redirects or\n // rewrites, this should never happen, because the route for a URL would\n // always be the same across multiple requests. So, this implies that some\n // runtime routing condition changed, likely in a proxy, without being\n // pushed to the client.\n //\n // When this happens, we treat this the same as a refresh(). The entire\n // tree will be re-rendered from the root.\n if (task.refreshState === null) {\n // Trigger a \"soft\" refresh. Essentially the same as calling `refresh()`\n // in a Server Action.\n exitStatus = NavigationTaskExitStatus.SoftRetry\n } else {\n // The mismatch was discovered inside an inactive parallel route. This\n // implies the inactive parallel route is no longer reachable at the URL\n // that originally rendered it. Fall back to an MPA refresh.\n // TODO: An alternative could be to trigger a soft refresh but to _not_\n // re-use the inactive parallel routes this time. Similar to what would\n // happen if were to do a hard refrehs, but without the HTML page.\n exitStatus = NavigationTaskExitStatus.HardRetry\n }\n } else {\n // This segment finished. (An error here is treated as Done because they are\n // surfaced to the application during render.)\n exitStatus = NavigationTaskExitStatus.Done\n }\n\n const taskChildren = task.children\n if (taskChildren !== null) {\n for (const [, taskChild] of taskChildren) {\n const childExitStatus = abortRemainingPendingTasks(\n taskChild,\n error,\n debugInfo\n )\n // Propagate the exit status up the tree. The statuses are ordered by\n // their precedence.\n if (childExitStatus > exitStatus) {\n exitStatus = childExitStatus\n }\n }\n }\n\n return exitStatus\n}\n\nfunction abortPendingCacheNode(\n cacheNode: CacheNode,\n error: any,\n debugInfo: Array<any> | null\n): void {\n const rsc = cacheNode.rsc\n if (isDeferredRsc(rsc)) {\n if (error === null) {\n // This will trigger a lazy fetch during render.\n rsc.resolve(null, debugInfo)\n } else {\n // This will trigger an error during rendering.\n rsc.reject(error, debugInfo)\n }\n }\n\n // Check if this is a leaf segment. If so, it will have a `head` property with\n // a pending promise that needs to be resolved. If an error was provided, we\n // will not resolve it with an error, since this is rendered at the root of\n // the app. We want the segment to error, not the entire app.\n const head = cacheNode.head\n if (isDeferredRsc(head)) {\n head.resolve(null, debugInfo)\n }\n}\n\nconst DEFERRED = Symbol()\n\ntype PendingDeferredRsc<T> = Promise<T> & {\n status: 'pending'\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype FulfilledDeferredRsc<T> = Promise<T> & {\n status: 'fulfilled'\n value: T\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype RejectedDeferredRsc<T> = Promise<T> & {\n status: 'rejected'\n reason: any\n resolve: (value: T, debugInfo: Array<any> | null) => void\n reject: (error: any, debugInfo: Array<any> | null) => void\n tag: Symbol\n _debugInfo: Array<any>\n}\n\ntype DeferredRsc<T extends React.ReactNode = React.ReactNode> =\n | PendingDeferredRsc<T>\n | FulfilledDeferredRsc<T>\n | RejectedDeferredRsc<T>\n\n// This type exists to distinguish a DeferredRsc from a Flight promise. It's a\n// compromise to avoid adding an extra field on every Cache Node, which would be\n// awkward because the pre-PPR parts of codebase would need to account for it,\n// too. We can remove it once type Cache Node type is more settled.\nexport function isDeferredRsc(value: any): value is DeferredRsc {\n return value && typeof value === 'object' && value.tag === DEFERRED\n}\n\nfunction createDeferredRsc<\n T extends React.ReactNode = React.ReactNode,\n>(): PendingDeferredRsc<T> {\n // Create an unresolved promise that represents data derived from a Flight\n // response. The promise will be resolved later as soon as we start receiving\n // data from the server, i.e. as soon as the Flight client decodes and returns\n // the top-level response object.\n\n // The `_debugInfo` field contains profiling information. Promises that are\n // created by Flight already have this info added by React; for any derived\n // promise created by the router, we need to transfer the Flight debug info\n // onto the derived promise.\n //\n // The debug info represents the latency between the start of the navigation\n // and the start of rendering. (It does not represent the time it takes for\n // whole stream to finish.)\n const debugInfo: Array<any> = []\n\n let resolve: any\n let reject: any\n const pendingRsc = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n }) as PendingDeferredRsc<T>\n pendingRsc.status = 'pending'\n pendingRsc.resolve = (value: T, responseDebugInfo: Array<any> | null) => {\n if (pendingRsc.status === 'pending') {\n const fulfilledRsc: FulfilledDeferredRsc<T> = pendingRsc as any\n fulfilledRsc.status = 'fulfilled'\n fulfilledRsc.value = value\n if (responseDebugInfo !== null) {\n // Transfer the debug info to the derived promise.\n debugInfo.push.apply(debugInfo, responseDebugInfo)\n }\n resolve(value)\n }\n }\n pendingRsc.reject = (error: any, responseDebugInfo: Array<any> | null) => {\n if (pendingRsc.status === 'pending') {\n const rejectedRsc: RejectedDeferredRsc<T> = pendingRsc as any\n rejectedRsc.status = 'rejected'\n rejectedRsc.reason = error\n if (responseDebugInfo !== null) {\n // Transfer the debug info to the derived promise.\n debugInfo.push.apply(debugInfo, responseDebugInfo)\n }\n reject(error)\n }\n }\n pendingRsc.tag = DEFERRED\n pendingRsc._debugInfo = debugInfo\n\n return pendingRsc\n}\n\n/**\n * Helper for the Instant Navigation Testing API. Waits for the navigation lock\n * to be released before returning. The network request has already completed by\n * the time this is called, so this only delays writing the dynamic data.\n *\n * Not exposed in production builds by default.\n */\nasync function waitForNavigationLock(): Promise<void> {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { waitForNavigationLockIfActive } =\n require('../segment-cache/navigation-testing-lock') as typeof import('../segment-cache/navigation-testing-lock')\n await waitForNavigationLockIfActive()\n }\n}\n","/**\n * For a given page path, this function ensures that there is a leading slash.\n * If there is not a leading slash, one is added, otherwise it is noop.\n */\nexport function ensureLeadingSlash(path: string) {\n return path.startsWith('/') ? path : `/${path}`\n}\n","import { ensureLeadingSlash } from '../../page-path/ensure-leading-slash'\nimport { isGroupSegment } from '../../segment'\n\n/**\n * Normalizes an app route so it represents the actual request path. Essentially\n * performing the following transformations:\n *\n * - `/(dashboard)/user/[id]/page` to `/user/[id]`\n * - `/(dashboard)/account/page` to `/account`\n * - `/user/[id]/page` to `/user/[id]`\n * - `/account/page` to `/account`\n * - `/page` to `/`\n * - `/(dashboard)/user/[id]/route` to `/user/[id]`\n * - `/(dashboard)/account/route` to `/account`\n * - `/user/[id]/route` to `/user/[id]`\n * - `/account/route` to `/account`\n * - `/route` to `/`\n * - `/` to `/`\n *\n * @param route the app route to normalize\n * @returns the normalized pathname\n */\nexport function normalizeAppPath(route: string) {\n return ensureLeadingSlash(\n route.split('/').reduce((pathname, segment, index, segments) => {\n // Empty segments are ignored.\n if (!segment) {\n return pathname\n }\n\n // Groups are ignored.\n if (isGroupSegment(segment)) {\n return pathname\n }\n\n // Parallel segments are ignored.\n if (segment[0] === '@') {\n return pathname\n }\n\n // The last segment (if it's a leaf) should be ignored.\n if (\n (segment === 'page' || segment === 'route') &&\n index === segments.length - 1\n ) {\n return pathname\n }\n\n return `${pathname}/${segment}`\n }, '')\n )\n}\n\n/**\n * Comparator for sorting app paths so that parallel slot paths (containing\n * `/@`) come before the children/root page path. This ensures the last item\n * is always the children page, which is what `renderPageComponent` reads via\n * `appPaths[appPaths.length - 1]`.\n *\n * Without this, route group prefixes like `(group)` (char code 0x28) sort\n * before `@` (0x40), causing the children page to sort first instead of last\n * and leading to a manifest mismatch / 404 in webpack dev mode.\n */\nexport function compareAppPaths(a: string, b: string): number {\n const aHasSlot = a.includes('/@')\n const bHasSlot = b.includes('/@')\n if (aHasSlot && !bHasSlot) return -1\n if (!aHasSlot && bHasSlot) return 1\n return a.localeCompare(b)\n}\n\n/**\n * Strips the `.rsc` extension if it's in the pathname.\n * Since this function is used on full urls it checks `?` for searchParams handling.\n */\nexport function normalizeRscURL(url: string) {\n return url.replace(\n /\\.rsc($|\\?)/,\n // $1 ensures `?` is preserved\n '$1'\n )\n}\n","import { normalizeAppPath } from './app-paths'\n\n// order matters here, the first match will be used\nexport const INTERCEPTION_ROUTE_MARKERS = [\n '(..)(..)',\n '(.)',\n '(..)',\n '(...)',\n] as const\n\nexport type InterceptionMarker = (typeof INTERCEPTION_ROUTE_MARKERS)[number]\n\nexport function isInterceptionRouteAppPath(path: string): boolean {\n // TODO-APP: add more serious validation\n return (\n path\n .split('/')\n .find((segment) =>\n INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n ) !== undefined\n )\n}\n\ntype InterceptionRouteInformation = {\n /**\n * The intercepting route. This is the route that is being intercepted or the\n * route that the user was coming from. This is matched by the Next-Url\n * header.\n */\n interceptingRoute: string\n\n /**\n * The intercepted route. This is the route that is being intercepted or the\n * route that the user is going to. This is matched by the request pathname.\n */\n interceptedRoute: string\n}\n\nexport function extractInterceptionRouteInformation(\n path: string\n): InterceptionRouteInformation {\n let interceptingRoute: string | undefined\n let marker: (typeof INTERCEPTION_ROUTE_MARKERS)[number] | undefined\n let interceptedRoute: string | undefined\n\n for (const segment of path.split('/')) {\n marker = INTERCEPTION_ROUTE_MARKERS.find((m) => segment.startsWith(m))\n if (marker) {\n ;[interceptingRoute, interceptedRoute] = path.split(marker, 2)\n break\n }\n }\n\n if (!interceptingRoute || !marker || !interceptedRoute) {\n throw new Error(\n `Invalid interception route: ${path}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`\n )\n }\n\n interceptingRoute = normalizeAppPath(interceptingRoute) // normalize the path, e.g. /(blog)/feed -> /feed\n\n switch (marker) {\n case '(.)':\n // (.) indicates that we should match with sibling routes, so we just need to append the intercepted route to the intercepting route\n if (interceptingRoute === '/') {\n interceptedRoute = `/${interceptedRoute}`\n } else {\n interceptedRoute = interceptingRoute + '/' + interceptedRoute\n }\n break\n case '(..)':\n // (..) indicates that we should match at one level up, so we need to remove the last segment of the intercepting route\n if (interceptingRoute === '/') {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..) marker at the root level, use (.) instead.`\n )\n }\n interceptedRoute = interceptingRoute\n .split('/')\n .slice(0, -1)\n .concat(interceptedRoute)\n .join('/')\n break\n case '(...)':\n // (...) will match the route segment in the root directory, so we need to use the root directory to prepend the intercepted route\n interceptedRoute = '/' + interceptedRoute\n break\n case '(..)(..)':\n // (..)(..) indicates that we should match at two levels up, so we need to remove the last two segments of the intercepting route\n\n const splitInterceptingRoute = interceptingRoute.split('/')\n if (splitInterceptingRoute.length <= 2) {\n throw new Error(\n `Invalid interception route: ${path}. Cannot use (..)(..) marker at the root level or one level up.`\n )\n }\n\n interceptedRoute = splitInterceptingRoute\n .slice(0, -2)\n .concat(interceptedRoute)\n .join('/')\n break\n default:\n throw new Error('Invariant: unexpected marker')\n }\n\n return { interceptingRoute, interceptedRoute }\n}\n","import type {\n FlightRouterState,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { INTERCEPTION_ROUTE_MARKERS } from '../../../shared/lib/router/utils/interception-routes'\nimport type { Params } from '../../../server/request/params'\nimport {\n isGroupSegment,\n DEFAULT_SEGMENT_KEY,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport { matchSegment } from '../match-segments'\n\nconst removeLeadingSlash = (segment: string): string => {\n return segment[0] === '/' ? segment.slice(1) : segment\n}\n\nconst segmentToPathname = (segment: Segment): string => {\n if (typeof segment === 'string') {\n // 'children' is not a valid path -- it's technically a parallel route that corresponds with the current segment's page\n // if we don't skip it, then the computed pathname might be something like `/children` which doesn't make sense.\n if (segment === 'children') return ''\n\n return segment\n }\n\n return segment[1]\n}\n\nconst segmentToSourcePagePathname = (segment: Segment): string => {\n if (typeof segment === 'string') {\n if (segment === 'children') return ''\n if (segment.startsWith(PAGE_SEGMENT_KEY)) return 'page'\n return segment\n }\n\n const [paramName, , dynamicParamType] = segment\n\n switch (dynamicParamType) {\n case 'c':\n return `[...${paramName}]`\n case 'ci(..)(..)':\n return `(..)(..)[...${paramName}]`\n case 'ci(.)':\n return `(.)[...${paramName}]`\n case 'ci(..)':\n return `(..)[...${paramName}]`\n case 'ci(...)':\n return `(...)[...${paramName}]`\n case 'oc':\n return `[[...${paramName}]]`\n case 'd':\n return `[${paramName}]`\n case 'di(..)(..)':\n return `(..)(..)[${paramName}]`\n case 'di(.)':\n return `(.)[${paramName}]`\n case 'di(..)':\n return `(..)[${paramName}]`\n case 'di(...)':\n return `(...)[${paramName}]`\n default:\n dynamicParamType satisfies never\n return `[${paramName}]`\n }\n}\n\nfunction normalizeSegments(segments: string[]): string {\n return (\n segments.reduce((acc, segment) => {\n segment = removeLeadingSlash(segment)\n if (segment === '' || isGroupSegment(segment)) {\n return acc\n }\n\n return `${acc}/${segment}`\n }, '') || '/'\n )\n}\n\nexport function extractPathFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string | undefined {\n const segment = Array.isArray(flightRouterState[0])\n ? flightRouterState[0][1]\n : flightRouterState[0]\n\n if (\n segment === DEFAULT_SEGMENT_KEY ||\n INTERCEPTION_ROUTE_MARKERS.some((m) => segment.startsWith(m))\n )\n return undefined\n\n if (segment.startsWith(PAGE_SEGMENT_KEY)) return ''\n\n const segments = [segmentToPathname(segment)]\n const parallelRoutes = flightRouterState[1] ?? {}\n\n const childrenPath = parallelRoutes.children\n ? extractPathFromFlightRouterState(parallelRoutes.children)\n : undefined\n\n if (childrenPath !== undefined) {\n segments.push(childrenPath)\n } else {\n for (const [key, value] of Object.entries(parallelRoutes)) {\n if (key === 'children') continue\n\n const childPath = extractPathFromFlightRouterState(value)\n\n if (childPath !== undefined) {\n segments.push(childPath)\n }\n }\n }\n\n return normalizeSegments(segments)\n}\n\nfunction extractSourcePageSegmentsFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string[] | undefined {\n const segment = segmentToSourcePagePathname(flightRouterState[0])\n\n if (segment === DEFAULT_SEGMENT_KEY) {\n return undefined\n }\n\n if (segment === 'page') {\n return [segment]\n }\n\n const parallelRoutes = flightRouterState[1] ?? {}\n\n const childrenPath = parallelRoutes.children\n ? extractSourcePageSegmentsFromFlightRouterState(parallelRoutes.children)\n : undefined\n\n if (childrenPath !== undefined) {\n return segment === ''\n ? childrenPath\n : [removeLeadingSlash(segment), ...childrenPath]\n }\n\n for (const [key, value] of Object.entries(parallelRoutes)) {\n if (key === 'children') continue\n\n const childPath = extractSourcePageSegmentsFromFlightRouterState(value)\n\n if (childPath !== undefined) {\n return segment === ''\n ? childPath\n : [removeLeadingSlash(segment), ...childPath]\n }\n }\n\n return undefined\n}\n\nexport function extractSourcePageFromFlightRouterState(\n flightRouterState: FlightRouterState\n): string | undefined {\n const sourcePageSegments =\n extractSourcePageSegmentsFromFlightRouterState(flightRouterState)\n\n return sourcePageSegments ? `/${sourcePageSegments.join('/')}` : undefined\n}\n\nfunction computeChangedPathImpl(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const [segmentA, parallelRoutesA] = treeA\n const [segmentB, parallelRoutesB] = treeB\n\n const normalizedSegmentA = segmentToPathname(segmentA)\n const normalizedSegmentB = segmentToPathname(segmentB)\n\n if (\n INTERCEPTION_ROUTE_MARKERS.some(\n (m) =>\n normalizedSegmentA.startsWith(m) || normalizedSegmentB.startsWith(m)\n )\n ) {\n return ''\n }\n\n if (!matchSegment(segmentA, segmentB)) {\n // once we find where the tree changed, we compute the rest of the path by traversing the tree\n return extractPathFromFlightRouterState(treeB) ?? ''\n }\n\n for (const parallelRouterKey in parallelRoutesA) {\n if (parallelRoutesB[parallelRouterKey]) {\n const changedPath = computeChangedPathImpl(\n parallelRoutesA[parallelRouterKey],\n parallelRoutesB[parallelRouterKey]\n )\n if (changedPath !== null) {\n return `${segmentToPathname(segmentB)}/${changedPath}`\n }\n }\n }\n\n return null\n}\n\nexport function computeChangedPath(\n treeA: FlightRouterState,\n treeB: FlightRouterState\n): string | null {\n const changedPath = computeChangedPathImpl(treeA, treeB)\n\n if (changedPath == null || changedPath === '/') {\n return changedPath\n }\n\n // lightweight normalization to remove route groups\n return normalizeSegments(changedPath.split('/'))\n}\n\n/**\n * Recursively extracts dynamic parameters from FlightRouterState.\n */\nexport function getSelectedParams(\n currentTree: FlightRouterState,\n params: Params = {}\n): Params {\n const parallelRoutes = currentTree[1]\n\n for (const parallelRoute of Object.values(parallelRoutes)) {\n const segment = parallelRoute[0]\n const isDynamicParameter = Array.isArray(segment)\n const segmentValue = isDynamicParameter ? segment[1] : segment\n if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue\n\n // Ensure catchAll and optional catchall are turned into an array\n const isCatchAll =\n isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')\n\n if (isCatchAll) {\n params[segment[0]] = segment[1].split('/')\n } else if (isDynamicParameter) {\n params[segment[0]] = segment[1]\n }\n\n params = getSelectedParams(parallelRoute, params)\n }\n\n return params\n}\n","// Adapted from React's sanitizeURL function found here: https://github.com/facebook/react/blob/b565373afd0cc1988497e1107106e851e8cfb261/packages/react-dom-bindings/src/shared/sanitizeURL.js\n\n// A javascript: URL can contain leading C0 control or \\u0020 SPACE,\n// and any newline or tab are filtered out as if they're not part of the URL.\n// https://url.spec.whatwg.org/#url-parsing\n// Tab or newline are defined as \\r\\n\\t:\n// https://infra.spec.whatwg.org/#ascii-tab-or-newline\n// A C0 control is a code point in the range \\u0000 NULL to \\u001F\n// INFORMATION SEPARATOR ONE, inclusive:\n// https://infra.spec.whatwg.org/#c0-control-or-space\n\nconst isJavaScriptProtocol =\n // eslint-disable-next-line no-control-regex\n /^[\\u0000-\\u001F ]*j[\\r\\n\\t]*a[\\r\\n\\t]*v[\\r\\n\\t]*a[\\r\\n\\t]*s[\\r\\n\\t]*c[\\r\\n\\t]*r[\\r\\n\\t]*i[\\r\\n\\t]*p[\\r\\n\\t]*t[\\r\\n\\t]*:/i\n\nexport function isJavaScriptURLString(url: string): boolean {\n return isJavaScriptProtocol.test('' + (url as unknown as string))\n}\n","/**\n * Navigation lock for the Instant Navigation Testing API.\n *\n * Manages the in-memory lock (a promise) that gates dynamic data writes\n * during instant navigation captures, and owns all cookie state\n * transitions (pending → captured-MPA, pending → captured-SPA).\n *\n * External actors (Playwright, devtools) set [0] to start a lock scope\n * and delete the cookie to end one. Next.js writes captured values.\n * The CookieStore handler distinguishes them by value: pending = external,\n * captured = self-write (ignored).\n */\n\nimport type { FlightRouterState } from '../../../shared/lib/app-router-types'\nimport { NEXT_INSTANT_TEST_COOKIE } from '../app-router-headers'\nimport { refreshOnInstantNavigationUnlock } from '../use-action-queue'\n\ntype InstantNavCookieState = 'pending' | 'mpa' | 'spa'\n\ntype InstantCookie =\n // pending (waiting to capture)\n | [captured: 0, id: string]\n // captured MPA page load\n | [captured: 1, id: string, state: null]\n // captured SPA navigation (from/to route trees)\n | [\n captured: 1,\n id: string,\n state: { from: FlightRouterState; to: FlightRouterState | null },\n ]\n\nfunction parseCookieValue(raw: string): InstantNavCookieState {\n try {\n const parsed = JSON.parse(raw)\n if (Array.isArray(parsed) && parsed.length >= 3) {\n const rawState = parsed[2]\n return rawState === null ? 'mpa' : 'spa'\n }\n } catch {}\n return 'pending'\n}\n\nfunction writeCookieValue(value: InstantCookie): void {\n if (typeof cookieStore === 'undefined') {\n return\n }\n // Read the existing cookie to preserve its attributes (domain, path),\n // then write back with the new value. This updates the same cookie\n // entry that the external actor created, regardless of how it was\n // scoped.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((existing: any) => {\n if (existing) {\n const options: any = {\n name: NEXT_INSTANT_TEST_COOKIE,\n value: JSON.stringify(value),\n path: existing.path ?? '/',\n }\n if (existing.domain) {\n options.domain = existing.domain\n }\n cookieStore.set(options)\n }\n })\n}\n\ntype NavigationLockState = {\n promise: Promise<void>\n resolve: () => void\n}\n\nlet lockState: NavigationLockState | null = null\n\nfunction acquireLock(): void {\n if (lockState !== null) {\n return\n }\n let resolve: () => void\n const promise = new Promise<void>((r) => {\n resolve = r\n })\n lockState = { promise, resolve: resolve! }\n}\n\nfunction releaseLock(): void {\n if (lockState !== null) {\n lockState.resolve()\n lockState = null\n }\n}\n\n/**\n * Sets up the cookie-based lock. Handles the initial page load state and\n * registers a CookieStore listener for runtime changes.\n *\n * Called once during page initialization from app-globals.ts.\n */\nexport function startListeningForInstantNavigationCookie(): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n // If the server served a static shell, this is an MPA page load\n // while the lock is held. Transition to captured-MPA and acquire.\n if (self.__next_instant_test) {\n if (typeof cookieStore !== 'undefined') {\n // If the cookie was already cleared during the MPA page\n // transition, reload to get the full dynamic page.\n cookieStore.get(NEXT_INSTANT_TEST_COOKIE).then((cookie: any) => {\n if (!cookie) {\n window.location.reload()\n }\n })\n }\n\n writeCookieValue([1, `c${Math.random()}`, null])\n acquireLock()\n }\n\n if (typeof cookieStore === 'undefined') {\n return\n }\n\n cookieStore.addEventListener('change', (event: CookieChangeEvent) => {\n for (const cookie of event.changed) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n const state = parseCookieValue(cookie.value ?? '')\n\n if (state !== 'pending') {\n // Captured value — our own transition. Ignore.\n return\n }\n\n // Pending value — external actor starting a new lock scope.\n if (lockState !== null) {\n releaseLock()\n }\n acquireLock()\n return\n }\n }\n\n for (const cookie of event.deleted) {\n if (cookie.name === NEXT_INSTANT_TEST_COOKIE) {\n releaseLock()\n refreshOnInstantNavigationUnlock()\n return\n }\n }\n })\n }\n}\n\n/**\n * Transitions the cookie from pending to captured-SPA. Called when a\n * client-side navigation is captured by the lock.\n *\n * @param fromTree - The flight router state of the from-route\n * @param toTree - The flight router state of the to-route (null if not yet known)\n */\nexport function transitionToCapturedSPA(\n fromTree: FlightRouterState,\n toTree: FlightRouterState | null\n): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n }\n}\n\n/**\n * Updates the captured-SPA cookie with the resolved route trees.\n * Called after the prefetch resolves and the target route tree is known.\n */\nexport function updateCapturedSPAToTree(\n fromTree: FlightRouterState,\n toTree: FlightRouterState\n): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n writeCookieValue([1, `c${Math.random()}`, { from: fromTree, to: toTree }])\n }\n}\n\n/**\n * Returns true if the navigation lock is currently active.\n */\nexport function isNavigationLocked(): boolean {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n return lockState !== null\n }\n return false\n}\n\n/**\n * Waits for the navigation lock to be released, if it's currently held.\n * No-op if the lock is not acquired.\n */\nexport async function waitForNavigationLockIfActive(): Promise<void> {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n if (lockState !== null) {\n await lockState.promise\n }\n }\n}\n","import type {\n CacheNodeSeedData,\n FlightRouterState,\n FlightSegmentPath,\n ScrollRef,\n} from '../../../shared/lib/app-router-types'\nimport type { CacheNode } from '../../../shared/lib/app-router-types'\nimport type { HeadData } from '../../../shared/lib/app-router-types'\nimport type { NormalizedFlightData } from '../../flight-data-helpers'\nimport { fetchServerResponse } from '../router-reducer/fetch-server-response'\nimport {\n startPPRNavigation,\n spawnDynamicRequests,\n FreshnessPolicy,\n type NavigationRequestAccumulation,\n} from '../router-reducer/ppr-navigations'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport {\n EntryStatus,\n readRouteCacheEntry,\n deprecated_requestOptimisticRouteCacheEntry,\n convertRootFlightRouterStateToRouteTree,\n getStaleAt,\n writeStaticStageResponseIntoCache,\n processRuntimePrefetchStream,\n writeDynamicRenderResponseIntoCache,\n type RouteTree,\n type FulfilledRouteCacheEntry,\n} from './cache'\nimport { discoverKnownRoute } from './optimistic-routes'\nimport { createCacheKey, type NormalizedSearch } from './cache-key'\nimport { schedulePrefetchTask } from './scheduler'\nimport { PrefetchPriority, FetchStrategy } from './types'\nimport { getLinkForCurrentNavigation } from '../links'\nimport type { PageVaryPath } from './vary-path'\nimport type { AppRouterState } from '../router-reducer/router-reducer-types'\nimport { ScrollBehavior } from '../router-reducer/router-reducer-types'\nimport { computeChangedPath } from '../router-reducer/compute-changed-path'\nimport { isJavaScriptURLString } from '../../lib/javascript-url'\nimport { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'\n\n/**\n * Navigate to a new URL, using the Segment Cache to construct a response.\n *\n * To allow for synchronous navigations whenever possible, this is not an async\n * function. It returns a promise only if there's no matching prefetch in\n * the cache. Otherwise it returns an immediate result and uses Suspense/RSC to\n * stream in any missing data.\n */\nexport function navigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n // Instant Navigation Testing API: when the lock is active, ensure a\n // prefetch task has been initiated before proceeding with the navigation.\n // This guarantees that segment data requests are at least pending, even\n // for routes that already have a cached route tree. Without this, the\n // static shell might be incomplete because some segments were never\n // requested.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n return ensurePrefetchThenNavigate(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\n }\n }\n\n return navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\n}\n\nfunction navigateImpl(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): AppRouterState | Promise<AppRouterState> {\n const now = Date.now()\n const href = url.href\n\n const cacheKey = createCacheKey(href, nextUrl)\n const route = readRouteCacheEntry(now, cacheKey)\n if (route !== null && route.status === EntryStatus.Fulfilled) {\n // We have a matching prefetch.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n route\n )\n }\n\n // There was no matching route tree in the cache. Let's see if we can\n // construct an \"optimistic\" route tree using the deprecated search-params\n // based matching. This is only used when the new optimisticRouting flag is\n // disabled.\n //\n // Do not construct an optimistic route tree if there was a cache hit, but\n // the entry has a rejected status, since it may have been rejected due to a\n // rewrite or redirect based on the search params.\n //\n // TODO: There are multiple reasons a prefetch might be rejected; we should\n // track them explicitly and choose what to do here based on that.\n if (!process.env.__NEXT_OPTIMISTIC_ROUTING) {\n if (route === null || route.status !== EntryStatus.Rejected) {\n const optimisticRoute = deprecated_requestOptimisticRouteCacheEntry(\n now,\n url,\n nextUrl\n )\n if (optimisticRoute !== null) {\n // We have an optimistic route tree. Proceed with the normal flow.\n return navigateUsingPrefetchedRouteTree(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType,\n optimisticRoute\n )\n }\n }\n }\n\n // There's no matching prefetch for this route in the cache. We must lazily\n // fetch it from the server before we can perform the navigation.\n //\n // TODO: If this is a gesture navigation, instead of performing a\n // dynamic request, we should do a runtime prefetch.\n return navigateToUnknownRoute(\n now,\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n nextUrl,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n ).catch(() => {\n // If the navigation fails, return the current state\n return state\n })\n}\n\nexport function navigateToKnownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n canonicalUrl: string,\n navigationSeed: NavigationSeed,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n nextUrl: string | null,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n debugInfo: Array<unknown> | null,\n // The route cache entry used for this navigation, if it came from route\n // prediction. Passed through so it can be marked as having a dynamic rewrite\n // if the server returns a different pathname (indicating dynamic rewrite\n // behavior).\n //\n // When null, the navigation did not use route prediction - either because\n // the route was already fully cached, or it's a navigation that doesn't\n // involve prediction (refresh, history traversal, server action, etc.).\n // In these cases, if a mismatch occurs, we still mark the route as having a\n // dynamic rewrite by traversing the known route tree (see\n // dispatchRetryDueToTreeMismatch).\n routeCacheEntry: FulfilledRouteCacheEntry | null\n): AppRouterState {\n // A version of navigate() that accepts the target route tree as an argument\n // rather than reading it from the prefetch cache.\n const accumulation: NavigationRequestAccumulation = {\n separateRefreshUrls: null,\n scrollRef: null,\n }\n // We special case navigations to the exact same URL as the current location.\n // It's a common UI pattern for apps to refresh when you click a link to the\n // current page. So when this happens, we refresh the dynamic data in the page\n // segments.\n //\n // Note that this does not apply if the any part of the hash or search query\n // has changed. This might feel a bit weird but it makes more sense when you\n // consider that the way to trigger this behavior is to click the same link\n // multiple times.\n //\n // TODO: We should probably refresh the *entire* route when this case occurs,\n // not just the page segments. Essentially treating it the same as a refresh()\n // triggered by an action, which is the more explicit way of modeling the UI\n // pattern described above.\n //\n // Also note that this only refreshes the dynamic data, not static/ cached\n // data. If the page segment is fully static and prefetched, the request is\n // skipped. (This is also how refresh() works.)\n const isSamePageNavigation = url.href === currentUrl.href\n const task = startPPRNavigation(\n now,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n navigationSeed.routeTree,\n navigationSeed.metadataVaryPath,\n freshnessPolicy,\n navigationSeed.data,\n navigationSeed.head,\n navigationSeed.dynamicStaleAt,\n isSamePageNavigation,\n accumulation\n )\n if (task !== null) {\n if (freshnessPolicy !== FreshnessPolicy.Gesture) {\n spawnDynamicRequests(\n task,\n url,\n nextUrl,\n freshnessPolicy,\n accumulation,\n routeCacheEntry,\n navigateType\n )\n }\n return completeSoftNavigation(\n state,\n url,\n nextUrl,\n task.route,\n task.node,\n navigationSeed.renderedSearch,\n canonicalUrl,\n navigateType,\n scrollBehavior,\n accumulation.scrollRef,\n debugInfo\n )\n }\n // Could not perform a SPA navigation. Revert to a full-page (MPA) navigation.\n return completeHardNavigation(state, url, navigateType)\n}\n\nfunction navigateUsingPrefetchedRouteTree(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace',\n route: FulfilledRouteCacheEntry\n): AppRouterState {\n const routeTree = route.tree\n const canonicalUrl = route.canonicalUrl + url.hash\n const renderedSearch = route.renderedSearch\n const prefetchSeed: NavigationSeed = {\n renderedSearch,\n routeTree,\n metadataVaryPath: route.metadata.varyPath as any,\n data: null,\n head: null,\n dynamicStaleAt: computeDynamicStaleAt(now, UnknownDynamicStaleTime),\n }\n return navigateToKnownRoute(\n now,\n state,\n url,\n canonicalUrl,\n prefetchSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n null,\n route\n )\n}\n\n// Used to request all the dynamic data for a route, rather than just a subset,\n// e.g. during a refresh or a revalidation. Typically this gets constructed\n// during the normal flow when diffing the route tree, but for an unprefetched\n// navigation, where we don't know the structure of the target route, we use\n// this instead.\nconst DynamicRequestTreeForEntireRoute: FlightRouterState = [\n '',\n {},\n null,\n 'refetch',\n]\n\nasync function navigateToUnknownRoute(\n now: number,\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n nextUrl: string | null,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): Promise<AppRouterState> {\n // Runs when a navigation happens but there's no cached prefetch we can use.\n // Don't bother to wait for a prefetch response; go straight to a full\n // navigation that contains both static and dynamic data in a single stream.\n // (This is unlike the old navigation implementation, which instead blocks\n // the dynamic request until a prefetch request is received.)\n //\n // To avoid duplication of logic, we're going to pretend that the tree\n // returned by the dynamic request is, in fact, a prefetch tree. Then we can\n // use the same server response to write the actual data into the CacheNode\n // tree. So it's the same flow as the \"happy path\" (prefetch, then\n // navigation), except we use a single server response for both stages.\n\n let dynamicRequestTree: FlightRouterState\n switch (freshnessPolicy) {\n case FreshnessPolicy.Default:\n case FreshnessPolicy.HistoryTraversal:\n case FreshnessPolicy.Gesture:\n dynamicRequestTree = currentFlightRouterState\n break\n case FreshnessPolicy.Hydration: // <- shouldn't happen during client nav\n case FreshnessPolicy.RefreshAll:\n case FreshnessPolicy.HMRRefresh:\n dynamicRequestTree = DynamicRequestTreeForEntireRoute\n break\n default:\n freshnessPolicy satisfies never\n dynamicRequestTree = currentFlightRouterState\n break\n }\n\n const promiseForDynamicServerResponse = fetchServerResponse(url, {\n flightRouterState: dynamicRequestTree,\n nextUrl,\n })\n const result = await promiseForDynamicServerResponse\n if (typeof result === 'string') {\n // This is an MPA navigation.\n const redirectUrl = new URL(result, location.origin)\n return completeHardNavigation(state, redirectUrl, navigateType)\n }\n\n const {\n flightData,\n canonicalUrl,\n renderedSearch,\n couldBeIntercepted,\n supportsPerSegmentPrefetching,\n dynamicStaleTime,\n staticStageData,\n runtimePrefetchStream,\n responseHeaders,\n debugInfo,\n } = result\n\n // Since the response format of dynamic requests and prefetches is slightly\n // different, we'll need to massage the data a bit. Create FlightRouterState\n // tree that simulates what we'd receive as the result of a prefetch.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n currentFlightRouterState,\n flightData,\n renderedSearch,\n dynamicStaleTime\n )\n\n // Learn the route pattern so we can predict it for future navigations.\n // hasDynamicRewrite is false because this is a fresh navigation to an\n // unknown route - any rewrite detection happens during the traversal inside\n // discoverKnownRoute. The hasDynamicRewrite param is only set to true when\n // retrying after a tree mismatch (see dispatchRetryDueToTreeMismatch).\n const metadataVaryPath = navigationSeed.metadataVaryPath\n if (metadataVaryPath !== null) {\n discoverKnownRoute(\n now,\n url.pathname,\n nextUrl,\n null, // No pending entry\n navigationSeed.routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n createHrefFromUrl(canonicalUrl),\n supportsPerSegmentPrefetching,\n false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal\n )\n\n if (staticStageData !== null) {\n const { response: staticStageResponse, isResponsePartial } =\n staticStageData\n\n // Write the static stage of the response into the segment cache so that\n // subsequent navigations can serve cached static segments instantly.\n getStaleAt(now, staticStageResponse.s)\n .then((staleAt) => {\n const buildId =\n responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n staticStageResponse.b\n\n writeStaticStageResponseIntoCache(\n now,\n staticStageResponse.f,\n buildId,\n staticStageResponse.h,\n staleAt,\n currentFlightRouterState,\n renderedSearch,\n isResponsePartial\n )\n })\n .catch(() => {\n // The static stage processing failed. Not fatal — the navigation\n // completed normally, we just won't write into the cache.\n })\n }\n\n if (runtimePrefetchStream !== null) {\n processRuntimePrefetchStream(\n now,\n runtimePrefetchStream,\n currentFlightRouterState,\n renderedSearch\n )\n .then((processed) => {\n if (processed !== null) {\n writeDynamicRenderResponseIntoCache(\n now,\n FetchStrategy.PPRRuntime,\n processed.flightDatas,\n processed.buildId,\n processed.isResponsePartial,\n processed.headVaryParams,\n processed.staleAt,\n processed.navigationSeed,\n null\n )\n }\n })\n .catch(() => {\n // The runtime prefetch cache write failed. Not fatal — the\n // navigation completed normally, we just won't cache runtime data.\n })\n }\n }\n\n return navigateToKnownRoute(\n now,\n state,\n url,\n createHrefFromUrl(canonicalUrl),\n navigationSeed,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n freshnessPolicy,\n nextUrl,\n scrollBehavior,\n navigateType,\n debugInfo,\n // Unknown route navigations don't use route prediction - the route tree\n // came directly from the server. If a mismatch occurs during dynamic data\n // fetch, the retry handler will traverse the known route tree to mark the\n // entry as having a dynamic rewrite.\n null\n )\n}\n\nexport function completeHardNavigation(\n state: AppRouterState,\n url: URL,\n navigateType: 'push' | 'replace'\n): AppRouterState {\n if (isJavaScriptURLString(url.href)) {\n console.error(\n 'Next.js has blocked a javascript: URL as a security precaution.'\n )\n return state\n }\n const newState: AppRouterState = {\n canonicalUrl:\n url.origin === location.origin ? createHrefFromUrl(url) : url.href,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: true,\n preserveCustomHistoryState: false,\n },\n // TODO: None of the rest of these values are consistent with the incoming\n // navigation. We rely on the fact that AppRouter will suspend and trigger\n // a hard navigation before it accesses any of these values. But instead\n // we should trigger the hard navigation and blocking any subsequent\n // router updates without updating React.\n renderedSearch: state.renderedSearch,\n focusAndScrollRef: state.focusAndScrollRef,\n cache: state.cache,\n tree: state.tree,\n nextUrl: state.nextUrl,\n previousNextUrl: state.previousNextUrl,\n debugInfo: null,\n }\n return newState\n}\n\nexport function completeSoftNavigation(\n oldState: AppRouterState,\n url: URL,\n referringNextUrl: string | null,\n tree: FlightRouterState,\n cache: CacheNode,\n renderedSearch: string,\n canonicalUrl: string,\n navigateType: 'push' | 'replace',\n scrollBehavior: ScrollBehavior,\n scrollRef: ScrollRef | null,\n collectedDebugInfo: Array<unknown> | null\n) {\n // The \"Next-Url\" is a special representation of the URL that Next.js\n // uses to implement interception routes.\n // TODO: Get rid of this extra traversal by computing this during the\n // same traversal that computes the tree itself. We should also figure out\n // what is the minimum information needed for the server to correctly\n // intercept the route.\n const changedPath = computeChangedPath(oldState.tree, tree)\n const nextUrlForNewRoute = changedPath ? changedPath : oldState.nextUrl\n\n // This value is stored on the state as `previousNextUrl`; the naming is\n // confusing. What it represents is the \"Next-Url\" header that was used to\n // fetch the incoming route. It's essentially the refererer URL, but in a\n // Next.js specific format. During refreshes, this is sent back to the server\n // instead of the current route's \"Next-Url\" so that the same interception\n // logic is applied as during the original navigation.\n const previousNextUrl = referringNextUrl\n\n // Check if the only thing that changed was the hash fragment.\n const oldUrl = new URL(oldState.canonicalUrl, url)\n const onlyHashChange =\n // We don't need to compare the origins, because client-driven\n // navigations are always same-origin.\n url.pathname === oldUrl.pathname &&\n url.search === oldUrl.search &&\n url.hash !== oldUrl.hash\n\n // Determine whether and how the page should scroll after this\n // navigation.\n //\n // By default, we scroll to the segments that were navigated to — i.e.\n // segments in the new part of the route, as opposed to shared segments\n // that were already part of the previous route. All newly navigated\n // segments share a single ScrollRef. When they mount, the first one\n // to mount initiates the scroll. They share a ref so that only one\n // scroll happens per navigation.\n //\n // If a subsequent navigation produces new segments, those supersede\n // any pending scroll from the previous navigation by invalidating its\n // ScrollRef. If a navigation doesn't produce any new segments (e.g.\n // a refresh where the route structure didn't change), any pending\n // scrolls from previous navigations are unaffected.\n //\n // The branches below handle special cases layered on top of this\n // default model.\n let activeScrollRef: ScrollRef | null\n let forceScroll: boolean\n if (scrollBehavior === ScrollBehavior.NoScroll) {\n // The user explicitly opted out of scrolling (e.g. scroll={false}\n // on a Link or router.push).\n //\n // If this navigation created new scroll targets (scrollRef !== null),\n // neutralize them. If it didn't, any prior scroll targets carried\n // forward on the cache nodes via reuseSharedCacheNode remain active.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = oldState.focusAndScrollRef.scrollRef\n forceScroll = false\n } else if (onlyHashChange) {\n // Hash-only navigations should scroll regardless of per-node state.\n // Create a fresh ref so the first segment to scroll consumes it.\n //\n // Invalidate any scroll ref from a prior navigation that hasn't\n // been consumed yet.\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n // Also invalidate any per-node refs that were accumulated during\n // this navigation's tree construction — the hash-only ref\n // supersedes them.\n if (scrollRef !== null) {\n scrollRef.current = false\n }\n activeScrollRef = { current: true }\n forceScroll = true\n } else {\n // Default case. Use the accumulated scrollRef (may be null if no\n // new segments were created). The handler checks per-node refs, so\n // unchanged parallel route slots won't scroll.\n activeScrollRef = scrollRef\n\n // If this navigation created new scroll targets, invalidate any\n // pending scroll from a previous navigation.\n if (scrollRef !== null) {\n const oldScrollRef = oldState.focusAndScrollRef.scrollRef\n if (oldScrollRef !== null) {\n oldScrollRef.current = false\n }\n }\n forceScroll = false\n }\n\n const newState: AppRouterState = {\n canonicalUrl,\n renderedSearch,\n pushRef: {\n pendingPush: navigateType === 'push',\n mpaNavigation: false,\n preserveCustomHistoryState: false,\n },\n focusAndScrollRef: {\n scrollRef: activeScrollRef,\n forceScroll,\n onlyHashChange,\n hashFragment:\n // Remove leading # and decode hash to make non-latin hashes work.\n //\n // Empty hash should trigger default behavior of scrolling layout into\n // view. #top is handled in layout-router.\n //\n // Refer to `ScrollAndFocusHandler` for details on how this is used.\n scrollBehavior !== ScrollBehavior.NoScroll && url.hash !== ''\n ? decodeURIComponent(url.hash.slice(1))\n : oldState.focusAndScrollRef.hashFragment,\n },\n cache,\n tree,\n nextUrl: nextUrlForNewRoute,\n previousNextUrl,\n debugInfo: collectedDebugInfo,\n }\n return newState\n}\n\nexport function completeTraverseNavigation(\n state: AppRouterState,\n url: URL,\n renderedSearch: string,\n cache: CacheNode,\n tree: FlightRouterState,\n nextUrl: string | null\n) {\n return {\n // Set canonical url\n canonicalUrl: createHrefFromUrl(url),\n renderedSearch,\n pushRef: {\n pendingPush: false,\n mpaNavigation: false,\n // Ensures that the custom history state that was set is preserved when applying this update.\n preserveCustomHistoryState: true,\n },\n focusAndScrollRef: state.focusAndScrollRef,\n cache,\n // Restore provided tree\n tree,\n nextUrl,\n // TODO: We need to restore previousNextUrl, too, which represents the\n // Next-Url that was used to fetch the data. Anywhere we fetch using the\n // canonical URL, there should be a corresponding Next-Url.\n previousNextUrl: null,\n debugInfo: null,\n }\n}\n\n// TODO: The rest of this file is related to converting the server response into\n// the data structures used by the client. Probably should move to a\n// separate module.\n\nexport type NavigationSeed = {\n renderedSearch: string\n routeTree: RouteTree\n metadataVaryPath: PageVaryPath | null\n data: CacheNodeSeedData | null\n head: HeadData | null\n dynamicStaleAt: number\n}\n\nexport function convertServerPatchToFullTree(\n now: number,\n currentTree: FlightRouterState,\n flightData: Array<NormalizedFlightData> | null,\n renderedSearch: string,\n dynamicStaleTimeSeconds: number\n): NavigationSeed {\n // During a client navigation or prefetch, the server sends back only a patch\n // for the parts of the tree that have changed.\n //\n // This applies the patch to the base tree to create a full representation of\n // the resulting tree.\n //\n // The return type includes a full FlightRouterState tree and a full\n // CacheNodeSeedData tree. (Conceptually these are the same tree, and should\n // eventually be unified, but there's still lots of existing code that\n // operates on FlightRouterState trees alone without the CacheNodeSeedData.)\n //\n // TODO: This similar to what apply-router-state-patch-to-tree does. It\n // will eventually fully replace it. We should get rid of all the remaining\n // places where we iterate over the server patch format. This should also\n // eventually replace normalizeFlightData.\n\n let baseTree: FlightRouterState = currentTree\n let baseData: CacheNodeSeedData | null = null\n let head: HeadData | null = null\n if (flightData !== null) {\n for (const {\n segmentPath,\n tree: treePatch,\n seedData: dataPatch,\n head: headPatch,\n } of flightData) {\n const result = convertServerPatchToFullTreeImpl(\n baseTree,\n baseData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n 0\n )\n baseTree = result.tree\n baseData = result.data\n // This is the same for all patches per response, so just pick an\n // arbitrary one\n head = headPatch\n }\n }\n\n const finalFlightRouterState = baseTree\n\n // Convert the final FlightRouterState into a RouteTree type.\n //\n // TODO: Eventually, FlightRouterState will evolve to being a transport format\n // only. The RouteTree type will become the main type used for dealing with\n // routes on the client, and we'll store it in the state directly.\n const acc = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n finalFlightRouterState,\n renderedSearch as NormalizedSearch,\n acc\n )\n\n return {\n routeTree,\n metadataVaryPath: acc.metadataVaryPath,\n data: baseData,\n renderedSearch,\n head,\n dynamicStaleAt: computeDynamicStaleAt(now, dynamicStaleTimeSeconds),\n }\n}\n\nfunction convertServerPatchToFullTreeImpl(\n baseRouterState: FlightRouterState,\n baseData: CacheNodeSeedData | null,\n treePatch: FlightRouterState,\n dataPatch: CacheNodeSeedData | null,\n segmentPath: FlightSegmentPath,\n renderedSearch: string,\n index: number\n): { tree: FlightRouterState; data: CacheNodeSeedData | null } {\n if (index === segmentPath.length) {\n // We reached the part of the tree that we need to patch.\n return {\n tree: treePatch,\n data: dataPatch,\n }\n }\n\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n //\n // This path tells us which part of the base tree to apply the tree patch.\n //\n // NOTE: We receive the FlightRouterState patch in the same request as the\n // seed data patch. Therefore we don't need to worry about diffing the segment\n // values; we can assume the server sent us a correct result.\n const updatedParallelRouteKey: string = segmentPath[index]\n // const segment: Segment = segmentPath[index + 1] <-- Not used, see note above\n\n const baseTreeChildren = baseRouterState[1]\n const baseSeedDataChildren = baseData !== null ? baseData[1] : null\n const newTreeChildren: Record<string, FlightRouterState> = {}\n const newSeedDataChildren: Record<string, CacheNodeSeedData | null> = {}\n for (const parallelRouteKey in baseTreeChildren) {\n const childBaseRouterState = baseTreeChildren[parallelRouteKey]\n const childBaseSeedData =\n baseSeedDataChildren !== null\n ? (baseSeedDataChildren[parallelRouteKey] ?? null)\n : null\n if (parallelRouteKey === updatedParallelRouteKey) {\n const result = convertServerPatchToFullTreeImpl(\n childBaseRouterState,\n childBaseSeedData,\n treePatch,\n dataPatch,\n segmentPath,\n renderedSearch,\n // Advance the index by two and keep cloning until we reach\n // the end of the segment path.\n index + 2\n )\n\n newTreeChildren[parallelRouteKey] = result.tree\n newSeedDataChildren[parallelRouteKey] = result.data\n } else {\n // This child is not being patched. Copy it over as-is.\n newTreeChildren[parallelRouteKey] = childBaseRouterState\n newSeedDataChildren[parallelRouteKey] = childBaseSeedData\n }\n }\n\n let clonedTree: FlightRouterState\n let clonedSeedData: CacheNodeSeedData\n // Clone all the fields except the children.\n\n // Clone the FlightRouterState tree. Based on equivalent logic in\n // apply-router-state-patch-to-tree, but should confirm whether we need to\n // copy all of these fields. Not sure the server ever sends, e.g. the\n // refetch marker.\n clonedTree = [baseRouterState[0], newTreeChildren]\n if (2 in baseRouterState) {\n const compressedRefreshState = baseRouterState[2]\n if (\n compressedRefreshState !== undefined &&\n compressedRefreshState !== null\n ) {\n // Since this part of the tree was patched with new data, any parent\n // refresh states should be updated to reflect the new rendered search\n // value. (The refresh state acts like a \"context provider\".) All pages\n // within the same server response share the same renderedSearch value,\n // but the same RouteTree could be composed from multiple different\n // routes, and multiple responses.\n clonedTree[2] = [compressedRefreshState[0], renderedSearch]\n }\n }\n if (3 in baseRouterState) {\n clonedTree[3] = baseRouterState[3]\n }\n if (4 in baseRouterState) {\n clonedTree[4] = baseRouterState[4]\n }\n\n // Clone the CacheNodeSeedData tree.\n const isEmptySeedDataPartial = true\n clonedSeedData = [\n null,\n newSeedDataChildren,\n null,\n isEmptySeedDataPartial,\n null,\n ]\n\n return {\n tree: clonedTree,\n data: clonedSeedData,\n }\n}\n\n/**\n * Instant Navigation Testing API: ensures a prefetch task has been initiated\n * and completed before proceeding with the navigation. This guarantees that\n * segment data requests are at least pending, even for routes whose route\n * tree is already cached.\n *\n * After the prefetch completes, delegates to the normal navigation flow.\n */\nasync function ensurePrefetchThenNavigate(\n state: AppRouterState,\n url: URL,\n currentUrl: URL,\n currentRenderedSearch: string,\n currentCacheNode: CacheNode | null,\n currentFlightRouterState: FlightRouterState,\n nextUrl: string | null,\n freshnessPolicy: FreshnessPolicy,\n scrollBehavior: ScrollBehavior,\n navigateType: 'push' | 'replace'\n): Promise<AppRouterState> {\n const link = getLinkForCurrentNavigation()\n const fetchStrategy = link !== null ? link.fetchStrategy : FetchStrategy.PPR\n\n // Transition the cookie to captured-SPA immediately, before waiting\n // for the prefetch. This ensures the devtools panel can update its UI\n // right away, even if the prefetch takes time (e.g. dev compilation).\n // The \"to\" tree starts as null and is filled in after the prefetch\n // resolves and the navigation produces a new router state.\n const { transitionToCapturedSPA, updateCapturedSPAToTree } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n transitionToCapturedSPA(currentFlightRouterState, null)\n\n const cacheKey = createCacheKey(url.href, nextUrl)\n\n await new Promise<void>((resolve) => {\n schedulePrefetchTask(\n cacheKey,\n currentFlightRouterState,\n fetchStrategy,\n PrefetchPriority.Default,\n null, // onInvalidate\n resolve // _onComplete callback\n )\n })\n\n // Prefetch is complete. Proceed with the normal navigation flow, which\n // will now find the route in the cache.\n const result = await navigateImpl(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n currentCacheNode,\n currentFlightRouterState,\n nextUrl,\n freshnessPolicy,\n scrollBehavior,\n navigateType\n )\n\n // Update the cookie with the resolved \"to\" tree so the devtools\n // panel can display both routes immediately.\n updateCapturedSPAToTree(currentFlightRouterState, result.tree)\n\n return result\n}\n","import type {\n NavigateAction,\n ReadonlyReducerState,\n ReducerState,\n} from '../router-reducer-types'\n\nimport {\n completeHardNavigation,\n navigate as navigateUsingSegmentCache,\n} from '../../segment-cache/navigation'\nimport { getStaleTimeMs } from '../../segment-cache/cache'\nimport { FreshnessPolicy } from '../ppr-navigations'\n\n// These values are set by `define-env-plugin` (based on `nextConfig.experimental.staleTimes`)\n// and default to 5 minutes (static) / 0 seconds (dynamic)\nexport const DYNAMIC_STALETIME_MS =\n Number(process.env.__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME) * 1000\n\nexport const STATIC_STALETIME_MS = getStaleTimeMs(\n Number(process.env.__NEXT_CLIENT_ROUTER_STATIC_STALETIME)\n)\n\nexport function navigateReducer(\n state: ReadonlyReducerState,\n action: NavigateAction\n): ReducerState {\n const { url, isExternalUrl, navigateType, scrollBehavior } = action\n\n if (isExternalUrl) {\n return completeHardNavigation(state, url, navigateType)\n }\n\n // Handles case where `<meta http-equiv=\"refresh\">` tag is present,\n // which will trigger an MPA navigation.\n if (document.getElementById('__next-page-redirect')) {\n return completeHardNavigation(state, url, navigateType)\n }\n\n // Temporary glue code between the router reducer and the new navigation\n // implementation. Eventually we'll rewrite the router reducer to a\n // state machine.\n const currentUrl = new URL(state.canonicalUrl, location.origin)\n const currentRenderedSearch = state.renderedSearch\n return navigateUsingSegmentCache(\n state,\n url,\n currentUrl,\n currentRenderedSearch,\n state.cache,\n state.tree,\n state.nextUrl,\n FreshnessPolicy.Default,\n scrollBehavior,\n navigateType\n )\n}\n","import { DYNAMIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport type { SegmentVaryPath } from './vary-path'\n\n/**\n * Sentinel value indicating that no per-page dynamic stale time was provided.\n * When this is the dynamicStaleTime, the default DYNAMIC_STALETIME_MS is used.\n */\nexport const UnknownDynamicStaleTime = -1\n\n/**\n * Converts a dynamic stale time (in seconds, as sent by the server in the `d`\n * field of the Flight response) to an absolute staleAt timestamp. When the\n * value is unknown, falls back to the global DYNAMIC_STALETIME_MS.\n */\nexport function computeDynamicStaleAt(\n now: number,\n dynamicStaleTimeSeconds: number\n): number {\n return dynamicStaleTimeSeconds !== UnknownDynamicStaleTime\n ? now + dynamicStaleTimeSeconds * 1000\n : now + DYNAMIC_STALETIME_MS\n}\nimport {\n setInCacheMap,\n getFromCacheMap,\n type UnknownMapEntry,\n type CacheMap,\n createCacheMap,\n} from './cache-map'\n\nexport type BFCacheEntry = {\n rsc: React.ReactNode | null\n prefetchRsc: React.ReactNode | null\n head: React.ReactNode | null\n prefetchHead: React.ReactNode | null\n\n ref: UnknownMapEntry | null\n size: number\n // The time at which this data was received. Used to compute the stale time\n // for dynamic prefetches (which use STATIC_STALETIME_MS instead of\n // DYNAMIC_STALETIME_MS). Stored explicitly because staleAt may be\n // overridden by a per-page unstable_dynamicStaleTime, which would break\n // any reverse calculation from staleAt.\n navigatedAt: number\n staleAt: number\n version: number\n}\n\nconst bfcacheMap: CacheMap<BFCacheEntry> = createCacheMap()\n\nlet currentBfCacheVersion = 0\n\nexport function invalidateBfCache(): void {\n if (typeof window === 'undefined') {\n return\n }\n currentBfCacheVersion++\n}\n\nexport function writeToBFCache(\n now: number,\n varyPath: SegmentVaryPath,\n rsc: React.ReactNode,\n prefetchRsc: React.ReactNode,\n head: React.ReactNode,\n prefetchHead: React.ReactNode,\n dynamicStaleAt: number\n): void {\n if (typeof window === 'undefined') {\n return\n }\n\n const entry: BFCacheEntry = {\n rsc,\n prefetchRsc,\n\n // TODO: These fields will be removed from both BFCacheEntry and\n // SegmentCacheEntry. The head has its own separate cache entry.\n head,\n prefetchHead,\n\n ref: null,\n // TODO: This is just a heuristic. Getting the actual size of the segment\n // isn't feasible because it's part of a larger streaming response. The\n // LRU will still evict it, we just won't have a fully accurate total\n // LRU size. However, we'll probably remove the size tracking from the LRU\n // entirely and use memory pressure events instead.\n size: 100,\n\n navigatedAt: now,\n\n // A back/forward navigation will disregard the stale time. This field is\n // only relevant when staleTimes.dynamic is enabled or unstable_dynamicStaleTime\n // is exported by a page.\n staleAt: dynamicStaleAt,\n version: currentBfCacheVersion,\n }\n const isRevalidation = false\n setInCacheMap(bfcacheMap, varyPath, entry, isRevalidation)\n}\n\nexport function writeHeadToBFCache(\n now: number,\n varyPath: SegmentVaryPath,\n head: React.ReactNode,\n prefetchHead: React.ReactNode,\n dynamicStaleAt: number\n): void {\n // Read the special \"segment\" that represents the head data.\n writeToBFCache(now, varyPath, head, prefetchHead, null, null, dynamicStaleAt)\n}\n\n/**\n * Update the staleAt of an existing BFCache entry. Used after a dynamic\n * response arrives with a per-page stale time from `unstable_dynamicStaleTime`.\n * The per-page value is authoritative — it overrides whatever staleAt was set\n * by the default DYNAMIC_STALETIME_MS.\n */\nexport function updateBFCacheEntryStaleAt(\n varyPath: SegmentVaryPath,\n newStaleAt: number\n): void {\n if (typeof window === 'undefined') {\n return\n }\n const isRevalidation = false\n // Read with staleness bypass (-1) so we can update even stale entries\n const entry = getFromCacheMap(\n -1,\n currentBfCacheVersion,\n bfcacheMap,\n varyPath,\n isRevalidation\n )\n if (entry !== null) {\n entry.staleAt = newStaleAt\n }\n}\n\nexport function readFromBFCache(\n varyPath: SegmentVaryPath\n): BFCacheEntry | null {\n if (typeof window === 'undefined') {\n return null\n }\n const isRevalidation = false\n return getFromCacheMap(\n // During a back/forward navigation, it doesn't matter how stale the data\n // might be. Pass -1 instead of the actual current time to bypass\n // staleness checks.\n -1,\n currentBfCacheVersion,\n bfcacheMap,\n varyPath,\n isRevalidation\n )\n}\n\nexport function readFromBFCacheDuringRegularNavigation(\n now: number,\n varyPath: SegmentVaryPath\n): BFCacheEntry | null {\n if (typeof window === 'undefined') {\n return null\n }\n const isRevalidation = false\n return getFromCacheMap(\n now,\n currentBfCacheVersion,\n bfcacheMap,\n varyPath,\n isRevalidation\n )\n}\n","'use client'\n\n// TODO: Explicitly import from client.browser\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n createFromReadableStream as createFromReadableStreamBrowser,\n createFromFetch as createFromFetchBrowser,\n} from 'react-server-dom-webpack/client'\n\nimport { InvariantError } from '../../../shared/lib/invariant-error'\nimport type {\n FlightRouterState,\n InitialRSCPayload,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\n\nimport {\n type NEXT_ROUTER_PREFETCH_HEADER,\n type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n type NEXT_INSTANT_PREFETCH_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_RSC_UNION_QUERY,\n NEXT_URL,\n RSC_HEADER,\n RSC_CONTENT_TYPE_HEADER,\n NEXT_HMR_REFRESH_HEADER,\n NEXT_DID_POSTPONE_HEADER,\n NEXT_HTML_REQUEST_ID_HEADER,\n NEXT_REQUEST_ID_HEADER,\n} from '../app-router-headers'\nimport { callServer } from '../../app-call-server'\nimport { findSourceMapURL } from '../../app-find-source-map-url'\nimport {\n normalizeFlightData,\n prepareFlightRouterStateForRequest,\n type NormalizedFlightData,\n} from '../../flight-data-helpers'\nimport { setCacheBustingSearchParam } from './set-cache-busting-search-param'\nimport { urlToUrlWithoutFlightMarker } from '../../route-params'\nimport type { NormalizedSearch } from '../segment-cache/cache-key'\nimport { getDeploymentId } from '../../../shared/lib/deployment-id'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\nimport { stripIsPartialByte } from '../segment-cache/cache'\nimport { UnknownDynamicStaleTime } from '../segment-cache/bfcache'\n\nconst createFromReadableStream =\n createFromReadableStreamBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromReadableStream']\nconst createFromFetch =\n createFromFetchBrowser as (typeof import('react-server-dom-webpack/client.browser'))['createFromFetch']\n\nlet createDebugChannel:\n | typeof import('../../dev/debug-channel').createDebugChannel\n | undefined\n\nif (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {\n createDebugChannel = (\n require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')\n ).createDebugChannel\n}\n\nexport interface FetchServerResponseOptions {\n readonly flightRouterState: FlightRouterState\n readonly nextUrl: string | null\n readonly isHmrRefresh?: boolean\n}\n\nexport type StaticStageData<\n T extends\n | NavigationFlightResponse\n | InitialRSCPayload = NavigationFlightResponse,\n> = {\n readonly response: T\n readonly isResponsePartial: boolean\n}\n\ntype SpaFetchServerResponseResult = {\n flightData: NormalizedFlightData[]\n canonicalUrl: URL\n renderedSearch: NormalizedSearch\n couldBeIntercepted: boolean\n supportsPerSegmentPrefetching: boolean\n postponed: boolean\n dynamicStaleTime: number\n staticStageData: StaticStageData | null\n runtimePrefetchStream: ReadableStream<Uint8Array> | null\n responseHeaders: Headers\n debugInfo: Array<any> | null\n}\n\ntype MpaFetchServerResponseResult = string\n\nexport type FetchServerResponseResult =\n | MpaFetchServerResponseResult\n | SpaFetchServerResponseResult\n\nexport type RequestHeaders = {\n [RSC_HEADER]?: '1'\n [NEXT_ROUTER_STATE_TREE_HEADER]?: string\n [NEXT_URL]?: string\n [NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2'\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string\n 'x-deployment-id'?: string\n [NEXT_HMR_REFRESH_HEADER]?: '1'\n // A header that is only added in test mode to assert on fetch priority\n 'Next-Test-Fetch-Priority'?: RequestInit['priority']\n [NEXT_HTML_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_REQUEST_ID_HEADER]?: string // dev-only\n [NEXT_INSTANT_PREFETCH_HEADER]?: '1' // testing API only\n}\n\nfunction doMpaNavigation(url: string): FetchServerResponseResult {\n return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()\n}\n\nlet isPageUnloading = false\n\nif (typeof window !== 'undefined') {\n // Track when the page is unloading, e.g. due to reloading the page or\n // performing hard navigations. This allows us to suppress error logging when\n // the browser cancels in-flight requests during page unload.\n window.addEventListener('pagehide', () => {\n isPageUnloading = true\n })\n\n // Reset the flag on pageshow, e.g. when navigating back and the JavaScript\n // execution context is restored by the browser.\n window.addEventListener('pageshow', () => {\n isPageUnloading = false\n })\n}\n\n/**\n * Fetch the flight data for the provided url. Takes in the current router state\n * to decide what to render server-side.\n */\nexport async function fetchServerResponse(\n url: URL,\n options: FetchServerResponseOptions\n): Promise<FetchServerResponseResult> {\n const { flightRouterState, nextUrl } = options\n\n const headers: RequestHeaders = {\n // Enable flight response\n [RSC_HEADER]: '1',\n // Provide the current router state\n [NEXT_ROUTER_STATE_TREE_HEADER]: prepareFlightRouterStateForRequest(\n flightRouterState,\n options.isHmrRefresh\n ),\n }\n\n if (process.env.NODE_ENV === 'development' && options.isHmrRefresh) {\n headers[NEXT_HMR_REFRESH_HEADER] = '1'\n }\n\n if (nextUrl) {\n headers[NEXT_URL] = nextUrl\n }\n\n // In static export mode, we need to modify the URL to request the .txt file,\n // but we should preserve the original URL for the canonical URL and error handling.\n const originalUrl = url\n\n try {\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n // In \"output: export\" mode, we can't rely on headers to distinguish\n // between HTML and RSC requests. Instead, we append an extra prefix\n // to the request.\n url = new URL(url)\n if (url.pathname.endsWith('/')) {\n url.pathname += 'index.txt'\n } else {\n url.pathname += '.txt'\n }\n }\n }\n\n // Typically, during a navigation, we decode the response using Flight's\n // `createFromFetch` API, which accepts a `fetch` promise.\n // TODO: Remove this check once the old PPR flag is removed\n const isLegacyPPR =\n process.env.__NEXT_PPR && !process.env.__NEXT_CACHE_COMPONENTS\n const shouldImmediatelyDecode = !isLegacyPPR\n const res = await createFetch<NavigationFlightResponse>(\n url,\n headers,\n 'auto',\n shouldImmediatelyDecode\n )\n\n const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))\n const canonicalUrl = res.redirected ? responseUrl : originalUrl\n\n const contentType = res.headers.get('content-type') || ''\n const interception = !!res.headers.get('vary')?.includes(NEXT_URL)\n const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)\n let isFlightResponse = contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n\n if (process.env.NODE_ENV === 'production') {\n if (process.env.__NEXT_CONFIG_OUTPUT === 'export') {\n if (!isFlightResponse) {\n isFlightResponse = contentType.startsWith('text/plain')\n }\n }\n }\n\n // If fetch returns something different than flight response handle it like a mpa navigation\n // If the fetch was not 200, we also handle it like a mpa navigation\n if (!isFlightResponse || !res.ok || !res.body) {\n // in case the original URL came with a hash, preserve it before redirecting to the new URL\n if (url.hash) {\n responseUrl.hash = url.hash\n }\n\n return doMpaNavigation(responseUrl.toString())\n }\n\n // We may navigate to a page that requires a different Webpack runtime.\n // In prod, every page will have the same Webpack runtime.\n // In dev, the Webpack runtime is minimal for each page.\n // We need to ensure the Webpack runtime is updated before executing client-side JS of the new page.\n // TODO: This needs to happen in the Flight Client.\n // Or Webpack needs to include the runtime update in the Flight response as\n // a blocking script.\n if (process.env.NODE_ENV !== 'production' && !process.env.TURBOPACK) {\n await (\n require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')\n ).waitForWebpackRuntimeHotUpdate()\n }\n\n let flightResponsePromise = res.flightResponsePromise\n if (flightResponsePromise === null) {\n // Typically, `createFetch` would have already started decoding the\n // Flight response. If it hasn't, though, we need to decode it now.\n // TODO: This should only be reachable if legacy PPR is enabled (i.e. PPR\n // without Cache Components). Remove this branch once legacy PPR\n // is deleted.\n flightResponsePromise =\n createFromNextReadableStream<NavigationFlightResponse>(\n res.body,\n headers,\n { allowPartialStream: postponed }\n )\n }\n\n const [flightResponse, cacheData] = await Promise.all([\n flightResponsePromise,\n res.cacheData,\n ])\n\n if (\n (res.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? flightResponse.b) !==\n getNavigationBuildId()\n ) {\n // The server build does not match the client build.\n return doMpaNavigation(res.url)\n }\n\n const normalizedFlightData = normalizeFlightData(flightResponse.f)\n if (typeof normalizedFlightData === 'string') {\n return doMpaNavigation(normalizedFlightData)\n }\n\n const staticStageData =\n cacheData !== null\n ? await resolveStaticStageData(cacheData, flightResponse, headers)\n : null\n\n return {\n flightData: normalizedFlightData,\n canonicalUrl: canonicalUrl,\n // TODO: We should be able to read this from the rewrite header, not the\n // Flight response. Theoretically they should always agree, but there are\n // currently some cases where it's incorrect for interception routes. We\n // can always trust the value in the response body. However, per-segment\n // prefetch responses don't embed the value in the body; they rely on the\n // header alone. So we need to investigate why the header is sometimes\n // wrong for interception routes.\n renderedSearch: flightResponse.q as NormalizedSearch,\n couldBeIntercepted: interception,\n supportsPerSegmentPrefetching: flightResponse.S,\n postponed,\n // The dynamicStaleTime is only present in the response body when\n // a page exports unstable_dynamicStaleTime and this is a dynamic render.\n // When absent (UnknownDynamicStaleTime), the client falls back to the\n // global DYNAMIC_STALETIME_MS. The value is in seconds.\n dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,\n staticStageData,\n runtimePrefetchStream: flightResponse.p ?? null,\n responseHeaders: res.headers,\n debugInfo: flightResponsePromise._debugInfo ?? null,\n }\n } catch (err) {\n if (!isPageUnloading) {\n console.error(\n `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,\n err\n )\n }\n\n // If fetch fails handle it like a mpa navigation\n // TODO-APP: Add a test for the case where a CORS request fails, e.g. external url redirect coming from the response.\n // See https://github.com/vercel/next.js/issues/43605#issuecomment-1451617521 for a reproduction.\n return originalUrl.toString()\n }\n}\n\n// This is a subset of the standard Response type. We use a custom type for\n// this so we can limit which details about the response leak into the rest of\n// the codebase. For example, there's some custom logic for manually following\n// redirects, so \"redirected\" in this type could be a composite of multiple\n// browser fetch calls; however, this fact should not leak to the caller.\nexport type RSCResponse<T> = {\n ok: boolean\n redirected: boolean\n headers: Headers\n body: ReadableStream<Uint8Array> | null\n status: number\n url: string\n flightResponsePromise: (Promise<T> & { _debugInfo?: Array<any> }) | null\n cacheData: Promise<FetchResponseCacheData | null>\n}\n\ntype FetchResponseCacheData = {\n isResponsePartial: boolean\n responseBodyClone?: ReadableStream<Uint8Array>\n}\n\n/**\n * Strips the leading isPartial byte from an RSC navigation response and\n * clones the body for segment cache extraction.\n *\n * When cache components is enabled, the server prepends a single byte:\n * '~' (0x7e) for partial, '#' (0x23) for complete. This must be stripped\n * before Flight decoding because it's not valid RSC data. The body is\n * cloned before Flight can consume it so the clone is available for later use.\n *\n * When cache components is disabled, returns the original response with\n * cacheData: null.\n */\nexport async function processFetch(response: Response): Promise<{\n response: Response\n cacheData: FetchResponseCacheData | null\n}> {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (!response.body) {\n throw new InvariantError(\n 'Expected RSC navigation response to have a body'\n )\n }\n\n const { stream, isPartial } = await stripIsPartialByte(response.body)\n\n let responseStream: ReadableStream<Uint8Array>\n let cacheData: FetchResponseCacheData\n\n if (process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS) {\n const [stream1, stream2] = stream.tee()\n responseStream = stream1\n cacheData = { isResponsePartial: isPartial, responseBodyClone: stream2 }\n } else {\n responseStream = stream\n cacheData = { isResponsePartial: isPartial }\n }\n\n const strippedResponse = new Response(responseStream, {\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n })\n\n // The Response constructor doesn't preserve `url` or `redirected` from\n // the original. We need both: `url` for React DevTools and `redirected`\n // for the redirect replay logic below.\n Object.defineProperty(strippedResponse, 'url', { value: response.url })\n Object.defineProperty(strippedResponse, 'redirected', {\n value: response.redirected,\n })\n\n return { response: strippedResponse, cacheData }\n }\n\n return { response, cacheData: null }\n}\n\n/**\n * Resolves the static stage response from the raw `processFetch` outputs and\n * the decoded flight response, for writing into the segment cache.\n *\n * - Fully static: use the decoded flight response as-is, no truncation needed.\n * - Not fully static + `l` field: truncate the body clone at the static stage\n * byte boundary and decode.\n * - Otherwise: no cache-worthy data.\n */\nexport async function resolveStaticStageData<\n T extends NavigationFlightResponse | InitialRSCPayload,\n>(\n cacheData: FetchResponseCacheData,\n flightResponse: T,\n headers: RequestHeaders | undefined\n): Promise<StaticStageData<T> | null> {\n const { isResponsePartial, responseBodyClone } = cacheData\n\n if (responseBodyClone) {\n if (!isResponsePartial) {\n // Fully static — cache the entire decoded response as-is.\n responseBodyClone.cancel()\n\n return { response: flightResponse, isResponsePartial: false }\n }\n\n if (flightResponse.l !== undefined) {\n // Partially static — truncate the body clone at the byte boundary and\n // decode it.\n const response = await decodeStaticStage<T>(\n responseBodyClone,\n flightResponse.l,\n headers\n )\n\n return { response, isResponsePartial: true }\n }\n\n // No caching — cancel the unused clone.\n responseBodyClone.cancel()\n }\n\n return null\n}\n\n/**\n * Truncates a Flight stream clone at the given byte boundary and decodes the\n * static stage prefix. Used by both the navigation path and the initial HTML\n * hydration path.\n */\nexport async function decodeStaticStage<T>(\n responseBodyClone: ReadableStream<Uint8Array>,\n staticStageByteLengthPromise: Promise<number>,\n headers: RequestHeaders | undefined\n): Promise<T> {\n const staticStageByteLength = await staticStageByteLengthPromise\n\n const truncatedStream = truncateStream(\n responseBodyClone,\n staticStageByteLength\n )\n\n return createFromNextReadableStream<T>(truncatedStream, headers, {\n allowPartialStream: true,\n })\n}\n\nexport async function createFetch<T>(\n url: URL,\n headers: RequestHeaders,\n fetchPriority: 'auto' | 'high' | 'low' | null,\n shouldImmediatelyDecode: boolean,\n signal?: AbortSignal\n): Promise<RSCResponse<T>> {\n // TODO: In output: \"export\" mode, the headers do nothing. Omit them (and the\n // cache busting search param) from the request so they're\n // maximally cacheable.\n\n if (process.env.__NEXT_TEST_MODE && fetchPriority !== null) {\n headers['Next-Test-Fetch-Priority'] = fetchPriority\n }\n\n const deploymentId = getDeploymentId()\n if (deploymentId) {\n headers['x-deployment-id'] = deploymentId\n }\n\n if (process.env.__NEXT_DEV_SERVER) {\n if (self.__next_r) {\n headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r\n }\n\n // Create a new request ID for the server action request. The server uses\n // this to tag debug information sent via WebSocket to the client, which\n // then routes those chunks to the debug channel associated with this ID.\n headers[NEXT_REQUEST_ID_HEADER] = crypto\n .getRandomValues(new Uint32Array(1))[0]\n .toString(16)\n }\n\n const fetchOptions: RequestInit = {\n // Backwards compat for older browsers. `same-origin` is the default in modern browsers.\n credentials: 'same-origin',\n headers,\n priority: fetchPriority || undefined,\n signal,\n }\n // `fetchUrl` is slightly different from `url` because we add a cache-busting\n // search param to it. This should not leak outside of this function, so we\n // track them separately.\n let fetchUrl = new URL(url)\n setCacheBustingSearchParam(fetchUrl, headers)\n let processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n let fetchPromise = processed.then(({ response }) => response)\n\n // Immediately pass the fetch promise to the Flight client so that the debug\n // info includes the latency from the client to the server. The internal timer\n // in React starts as soon as `createFromFetch` is called.\n //\n // The only case where we don't do this is during a prefetch, because a\n // top-level prefetch response never blocks a navigation; if it hasn't already\n // been written into the cache by the time the navigation happens, the router\n // will go straight to a dynamic request.\n let flightResponsePromise = shouldImmediatelyDecode\n ? createFromNextFetch<T>(fetchPromise, headers)\n : null\n let browserResponse = await fetchPromise\n\n // If the server responds with a redirect (e.g. 307), and the redirected\n // location does not contain the cache busting search param set in the\n // original request, the response is likely invalid — when following the\n // redirect, the browser forwards the request headers, but since the cache\n // busting search param is missing, the server will reject the request due to\n // a mismatch.\n //\n // Ideally, we would be able to intercept the redirect response and perform it\n // manually, instead of letting the browser automatically follow it, but this\n // is not allowed by the fetch API.\n //\n // So instead, we must \"replay\" the redirect by fetching the new location\n // again, but this time we'll append the cache busting search param to prevent\n // a mismatch.\n //\n // TODO: We can optimize Next.js's built-in middleware APIs by returning a\n // custom status code, to prevent the browser from automatically following it.\n //\n // This does not affect Server Action-based redirects; those are encoded\n // differently, as part of the Flight body. It only affects redirects that\n // occur in a middleware or a third-party proxy.\n\n let redirected = browserResponse.redirected\n if (process.env.__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS) {\n // This is to prevent a redirect loop. Same limit used by Chrome.\n const MAX_REDIRECTS = 20\n for (let n = 0; n < MAX_REDIRECTS; n++) {\n if (!browserResponse.redirected) {\n // The server did not perform a redirect.\n break\n }\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n if (responseUrl.origin !== fetchUrl.origin) {\n // The server redirected to an external URL. The rest of the logic below\n // is not relevant, because it only applies to internal redirects.\n break\n }\n if (\n responseUrl.searchParams.get(NEXT_RSC_UNION_QUERY) ===\n fetchUrl.searchParams.get(NEXT_RSC_UNION_QUERY)\n ) {\n // The redirected URL already includes the cache busting search param.\n // This was probably intentional. Regardless, there's no reason to\n // issue another request to this URL because it already has the param\n // value that we would have added below.\n break\n }\n // The RSC request was redirected. Assume the response is invalid.\n //\n // Append the cache busting search param to the redirected URL and\n // fetch again.\n // TODO: We should abort the previous request.\n fetchUrl = new URL(responseUrl)\n setCacheBustingSearchParam(fetchUrl, headers)\n processed = fetch(fetchUrl, fetchOptions).then(processFetch)\n fetchPromise = processed.then(({ response }) => response)\n flightResponsePromise = shouldImmediatelyDecode\n ? createFromNextFetch<T>(fetchPromise, headers)\n : null\n browserResponse = await fetchPromise\n // We just performed a manual redirect, so this is now true.\n redirected = true\n }\n }\n\n // Remove the cache busting search param from the response URL, to prevent it\n // from leaking outside of this function.\n const responseUrl = new URL(browserResponse.url, fetchUrl)\n responseUrl.searchParams.delete(NEXT_RSC_UNION_QUERY)\n\n const rscResponse: RSCResponse<T> = {\n url: responseUrl.href,\n\n // This is true if any redirects occurred, either automatically by the\n // browser, or manually by us. So it's different from\n // `browserResponse.redirected`, which only tells us whether the browser\n // followed a redirect, and only for the last response in the chain.\n redirected,\n\n // These can be copied from the last browser response we received. We\n // intentionally only expose the subset of fields that are actually used\n // elsewhere in the codebase.\n ok: browserResponse.ok,\n headers: browserResponse.headers,\n body: browserResponse.body,\n status: browserResponse.status,\n\n // This is the exact promise returned by `createFromFetch`. It contains\n // debug information that we need to transfer to any derived promises that\n // are later rendered by React.\n flightResponsePromise: flightResponsePromise,\n\n cacheData: processed.then(({ cacheData }) => cacheData),\n }\n\n return rscResponse\n}\n\nexport function createFromNextReadableStream<T>(\n flightStream: ReadableStream<Uint8Array>,\n requestHeaders: RequestHeaders | undefined,\n options?: { allowPartialStream?: boolean }\n): Promise<T> {\n return createFromReadableStream(flightStream, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n unstable_allowPartialStream: options?.allowPartialStream,\n })\n}\n\nfunction createFromNextFetch<T>(\n promiseForResponse: Promise<Response>,\n requestHeaders: RequestHeaders\n): Promise<T> & { _debugInfo?: Array<any> } {\n return createFromFetch(promiseForResponse, {\n callServer,\n findSourceMapURL,\n debugChannel: createDebugChannel && createDebugChannel(requestHeaders),\n })\n}\n\nfunction truncateStream(\n stream: ReadableStream<Uint8Array>,\n byteLength: number\n): ReadableStream<Uint8Array> {\n const reader = stream.getReader()\n let remaining = byteLength\n\n return new ReadableStream({\n async pull(controller) {\n if (remaining <= 0) {\n reader.cancel()\n controller.close()\n return\n }\n\n const { done, value } = await reader.read()\n\n if (done) {\n controller.close()\n return\n }\n\n if (value.byteLength <= remaining) {\n controller.enqueue(value)\n remaining -= value.byteLength\n } else {\n controller.enqueue(value.subarray(0, remaining))\n remaining = 0\n reader.cancel()\n controller.close()\n }\n },\n cancel() {\n reader.cancel()\n },\n })\n}\n","export function createPromiseWithResolvers<T>(): PromiseWithResolvers<T> {\n // Shim of Stage 4 Promise.withResolvers proposal\n let resolve: (value: T | PromiseLike<T>) => void\n let reject: (reason: any) => void\n const promise = new Promise<T>((res, rej) => {\n resolve = res\n reject = rej\n })\n return { resolve: resolve!, reject: reject!, promise }\n}\n","import type {\n TreePrefetch,\n RootTreePrefetch,\n SegmentPrefetch,\n InlinedPrefetchResponse,\n InlinedSegmentPrefetch,\n} from '../../../server/app-render/collect-segment-data'\nimport type {\n CacheNodeSeedData,\n FlightData,\n Segment as FlightRouterStateSegment,\n} from '../../../shared/lib/app-router-types'\nimport {\n readVaryParams,\n type VaryParams,\n type VaryParamsThenable,\n} from '../../../shared/lib/segment-cache/vary-params-decoding'\nimport {\n NEXT_DID_POSTPONE_HEADER,\n NEXT_INSTANT_PREFETCH_HEADER,\n NEXT_ROUTER_PREFETCH_HEADER,\n NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,\n NEXT_ROUTER_STALE_TIME_HEADER,\n NEXT_ROUTER_STATE_TREE_HEADER,\n NEXT_URL,\n RSC_CONTENT_TYPE_HEADER,\n RSC_HEADER,\n} from '../app-router-headers'\nimport {\n createFetch,\n createFromNextReadableStream,\n type RSCResponse,\n type RequestHeaders,\n} from '../router-reducer/fetch-server-response'\nimport {\n pingPrefetchTask,\n isPrefetchTaskDirty,\n type PrefetchTask,\n type PrefetchSubtaskResult,\n} from './scheduler'\nimport {\n type RouteVaryPath,\n type SegmentVaryPath,\n type PartialSegmentVaryPath,\n getRouteVaryPath,\n getFulfilledRouteVaryPath,\n getFulfilledSegmentVaryPath,\n getSegmentVaryPathForRequest,\n appendLayoutVaryPath,\n finalizeLayoutVaryPath,\n finalizePageVaryPath,\n clonePageVaryPathWithNewSearchParams,\n type PageVaryPath,\n type LayoutVaryPath,\n finalizeMetadataVaryPath,\n getPartialPageVaryPath,\n getPartialLayoutVaryPath,\n getRenderedSearchFromVaryPath,\n} from './vary-path'\nimport { createHrefFromUrl } from '../router-reducer/create-href-from-url'\nimport type {\n NormalizedPathname,\n NormalizedSearch,\n NormalizedNextUrl,\n RouteCacheKey,\n} from './cache-key'\nimport { createCacheKey as createPrefetchRequestKey } from './cache-key'\nimport {\n doesStaticSegmentAppearInURL,\n getCacheKeyForDynamicParam,\n getRenderedPathname,\n getRenderedSearch,\n parseDynamicParamFromURLPart,\n} from '../../route-params'\nimport {\n createCacheMap,\n getFromCacheMap,\n setInCacheMap,\n setSizeInCacheMap,\n deleteFromCacheMap,\n isValueExpired,\n type CacheMap,\n type UnknownMapEntry,\n} from './cache-map'\nimport {\n appendSegmentRequestKeyPart,\n convertSegmentPathToStaticExportFilename,\n createSegmentRequestKeyPart,\n HEAD_REQUEST_KEY,\n ROOT_SEGMENT_REQUEST_KEY,\n type SegmentRequestKey,\n} from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport type {\n FlightRouterState,\n NavigationFlightResponse,\n} from '../../../shared/lib/app-router-types'\nimport {\n type NormalizedFlightData,\n normalizeFlightData,\n prepareFlightRouterStateForRequest,\n} from '../../flight-data-helpers'\nimport { STATIC_STALETIME_MS } from '../router-reducer/reducers/navigate-reducer'\nimport { pingVisibleLinks } from '../links'\nimport { PAGE_SEGMENT_KEY } from '../../../shared/lib/segment'\nimport { FetchStrategy } from './types'\nimport { createPromiseWithResolvers } from '../../../shared/lib/promise-with-resolvers'\nimport { readFromBFCache, UnknownDynamicStaleTime } from './bfcache'\nimport { discoverKnownRoute, matchKnownRoute } from './optimistic-routes'\nimport { convertServerPatchToFullTree, type NavigationSeed } from './navigation'\nimport { getNavigationBuildId } from '../../navigation-build-id'\nimport { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'\n\n/**\n * Ensures a minimum stale time of 30s to avoid issues where the server sends a too\n * short-lived stale time, which would prevent anything from being prefetched.\n */\nexport function getStaleTimeMs(staleTimeSeconds: number): number {\n return Math.max(staleTimeSeconds, 30) * 1000\n}\n\n// A note on async/await when working in the prefetch cache:\n//\n// Most async operations in the prefetch cache should *not* use async/await,\n// Instead, spawn a subtask that writes the results to a cache entry, and attach\n// a \"ping\" listener to notify the prefetch queue to try again.\n//\n// The reason is we need to be able to access the segment cache and traverse its\n// data structures synchronously. For example, if there's a synchronous update\n// we can take an immediate snapshot of the cache to produce something we can\n// render. Limiting the use of async/await also makes it easier to avoid race\n// conditions, which is especially important because is cache is mutable.\n//\n// Another reason is that while we're performing async work, it's possible for\n// existing entries to become stale, or for Link prefetches to be removed from\n// the queue. For optimal scheduling, we need to be able to \"cancel\" subtasks\n// that are no longer needed. So, when a segment is received from the server, we\n// restart from the root of the tree that's being prefetched, to confirm all the\n// parent segments are still cached. If the segment is no longer reachable from\n// the root, then it's effectively canceled. This is similar to the design of\n// Rust Futures, or React Suspense.\n\ntype RouteTreeShared = {\n requestKey: SegmentRequestKey\n // TODO: Remove the `segment` field, now that it can be reconstructed\n // from `param`.\n segment: FlightRouterStateSegment\n refreshState: RefreshState | null\n slots: null | {\n [parallelRouteKey: string]: RouteTree\n }\n // Bitmask of PrefetchHint flags. Encodes route structure metadata:\n // root layout, loading boundaries, instant configs, and runtime prefetch\n // hints.\n prefetchHints: number\n}\n\nexport type RefreshState = {\n canonicalUrl: string\n renderedSearch: NormalizedSearch\n}\n\ntype LayoutRouteTree = RouteTreeShared & {\n isPage: false\n varyPath: LayoutVaryPath\n}\n\ntype PageRouteTree = RouteTreeShared & {\n isPage: true\n varyPath: PageVaryPath\n}\n\nexport type RouteTree = LayoutRouteTree | PageRouteTree\n\ntype RouteCacheEntryShared = {\n // This is false only if we're certain the route cannot be intercepted. It's\n // true in all other cases, including on initialization when we haven't yet\n // received a response from the server.\n couldBeIntercepted: boolean\n\n // Map-related fields.\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\n/**\n * Tracks the status of a cache entry as it progresses from no data (Empty),\n * waiting for server data (Pending), and finished (either Fulfilled or\n * Rejected depending on the response from the server.\n */\nexport const enum EntryStatus {\n Empty = 0,\n Pending = 1,\n Fulfilled = 2,\n Rejected = 3,\n}\n\nexport type PendingRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Empty | EntryStatus.Pending\n blockedTasks: Set<PrefetchTask> | null\n canonicalUrl: null\n renderedSearch: null\n tree: null\n metadata: null\n supportsPerSegmentPrefetching: false\n}\n\ntype RejectedRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Rejected\n blockedTasks: Set<PrefetchTask> | null\n canonicalUrl: null\n renderedSearch: null\n tree: null\n metadata: null\n supportsPerSegmentPrefetching: boolean\n}\n\nexport type FulfilledRouteCacheEntry = RouteCacheEntryShared & {\n status: EntryStatus.Fulfilled\n blockedTasks: null\n canonicalUrl: string\n renderedSearch: NormalizedSearch\n tree: RouteTree\n metadata: RouteTree\n supportsPerSegmentPrefetching: boolean\n // When true, this entry should not be used as a template for route\n // prediction. Set when we discover that the URL was rewritten by middleware\n // to a different route structure (e.g., /foo was rewritten to /bar). Since\n // rewrite behavior can vary by param value, we can't safely predict the\n // route structure for other URLs matching this pattern.\n hasDynamicRewrite: boolean\n}\n\nexport type RouteCacheEntry =\n | PendingRouteCacheEntry\n | FulfilledRouteCacheEntry\n | RejectedRouteCacheEntry\n\ntype SegmentCacheEntryShared = {\n fetchStrategy: FetchStrategy\n\n // Map-related fields.\n ref: UnknownMapEntry | null\n size: number\n staleAt: number\n version: number\n}\n\nexport type EmptySegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Empty\n rsc: null\n isPartial: true\n promise: null\n}\n\nexport type PendingSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Pending\n rsc: null\n isPartial: boolean\n promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>\n}\n\ntype RejectedSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Rejected\n rsc: null\n isPartial: true\n promise: null\n}\n\nexport type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {\n status: EntryStatus.Fulfilled\n rsc: React.ReactNode | null\n isPartial: boolean\n promise: null\n}\n\nexport type SegmentCacheEntry =\n | EmptySegmentCacheEntry\n | PendingSegmentCacheEntry\n | RejectedSegmentCacheEntry\n | FulfilledSegmentCacheEntry\n\nexport type NonEmptySegmentCacheEntry = Exclude<\n SegmentCacheEntry,\n EmptySegmentCacheEntry\n>\n\nconst isOutputExportMode =\n process.env.NODE_ENV === 'production' &&\n process.env.__NEXT_CONFIG_OUTPUT === 'export'\n\nconst MetadataOnlyRequestTree: FlightRouterState = [\n '',\n {},\n null,\n 'metadata-only',\n]\n\nlet routeCacheMap: CacheMap<RouteCacheEntry> = createCacheMap()\nlet segmentCacheMap: CacheMap<SegmentCacheEntry> = createCacheMap()\n\n// All invalidation listeners for the whole cache are tracked in single set.\n// Since we don't yet support tag or path-based invalidation, there's no point\n// tracking them any more granularly than this. Once we add granular\n// invalidation, that may change, though generally the model is to just notify\n// the listeners and allow the caller to poll the prefetch cache with a new\n// prefetch task if desired.\nlet invalidationListeners: Set<PrefetchTask> | null = null\n\n// Incrementing counters used to track cache invalidations. Route and segment\n// caches have separate versions so they can be invalidated independently.\n// Invalidation does not eagerly evict anything from the cache; entries are\n// lazily evicted when read.\nlet currentRouteCacheVersion = 0\nlet currentSegmentCacheVersion = 0\n\nexport function getCurrentRouteCacheVersion(): number {\n return currentRouteCacheVersion\n}\n\nexport function getCurrentSegmentCacheVersion(): number {\n return currentSegmentCacheVersion\n}\n\n/**\n * Invalidates all prefetch cache entries (both route and segment caches).\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateEntirePrefetchCache(\n nextUrl: string | null,\n tree: FlightRouterState\n): void {\n currentRouteCacheVersion++\n currentSegmentCacheVersion++\n\n pingVisibleLinks(nextUrl, tree)\n pingInvalidationListeners(nextUrl, tree)\n}\n\n/**\n * Invalidates all route cache entries. Route entries contain the tree structure\n * (which segments exist at a given URL) but not the segment data itself.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateRouteCacheEntries(\n nextUrl: string | null,\n tree: FlightRouterState\n): void {\n currentRouteCacheVersion++\n\n pingVisibleLinks(nextUrl, tree)\n pingInvalidationListeners(nextUrl, tree)\n}\n\n/**\n * Invalidates all segment cache entries. Segment entries contain the actual\n * RSC data for each segment.\n *\n * After invalidation, triggers re-prefetching of visible links and notifies\n * invalidation listeners.\n */\nexport function invalidateSegmentCacheEntries(\n nextUrl: string | null,\n tree: FlightRouterState\n): void {\n currentSegmentCacheVersion++\n\n pingVisibleLinks(nextUrl, tree)\n pingInvalidationListeners(nextUrl, tree)\n}\n\nfunction attachInvalidationListener(task: PrefetchTask): void {\n // This function is called whenever a prefetch task reads a cache entry. If\n // the task has an onInvalidate function associated with it — i.e. the one\n // optionally passed to router.prefetch(onInvalidate) — then we attach that\n // listener to the every cache entry that the task reads. Then, if an entry\n // is invalidated, we call the function.\n if (task.onInvalidate !== null) {\n if (invalidationListeners === null) {\n invalidationListeners = new Set([task])\n } else {\n invalidationListeners.add(task)\n }\n }\n}\n\nfunction notifyInvalidationListener(task: PrefetchTask): void {\n const onInvalidate = task.onInvalidate\n if (onInvalidate !== null) {\n // Clear the callback from the task object to guarantee it's not called more\n // than once.\n task.onInvalidate = null\n\n // This is a user-space function, so we must wrap in try/catch.\n try {\n onInvalidate()\n } catch (error) {\n if (typeof reportError === 'function') {\n reportError(error)\n } else {\n console.error(error)\n }\n }\n }\n}\n\nexport function pingInvalidationListeners(\n nextUrl: string | null,\n tree: FlightRouterState\n): void {\n // The rough equivalent of pingVisibleLinks, but for onInvalidate callbacks.\n // This is called when the Next-Url or the base tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n if (invalidationListeners !== null) {\n const tasks = invalidationListeners\n invalidationListeners = null\n for (const task of tasks) {\n if (isPrefetchTaskDirty(task, nextUrl, tree)) {\n notifyInvalidationListener(task)\n }\n }\n }\n}\n\nexport function readRouteCacheEntry(\n now: number,\n key: RouteCacheKey\n): RouteCacheEntry | null {\n const varyPath: RouteVaryPath = getRouteVaryPath(\n key.pathname,\n key.search,\n key.nextUrl\n )\n const isRevalidation = false\n const existingEntry = getFromCacheMap(\n now,\n getCurrentRouteCacheVersion(),\n routeCacheMap,\n varyPath,\n isRevalidation\n )\n if (existingEntry !== null) {\n return existingEntry\n }\n\n // No cache hit. Attempt to construct from template using the new\n // optimistic routing mechanism (pattern-based matching).\n if (process.env.__NEXT_OPTIMISTIC_ROUTING) {\n return matchKnownRoute(key.pathname, key.search)\n }\n\n return null\n}\n\nexport function readSegmentCacheEntry(\n now: number,\n varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n const isRevalidation = false\n return getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n segmentCacheMap,\n varyPath,\n isRevalidation\n )\n}\n\nfunction readRevalidatingSegmentCacheEntry(\n now: number,\n varyPath: SegmentVaryPath\n): SegmentCacheEntry | null {\n const isRevalidation = true\n return getFromCacheMap(\n now,\n getCurrentSegmentCacheVersion(),\n segmentCacheMap,\n varyPath,\n isRevalidation\n )\n}\n\nexport function waitForSegmentCacheEntry(\n pendingEntry: PendingSegmentCacheEntry\n): Promise<FulfilledSegmentCacheEntry | null> {\n // Because the entry is pending, there's already a in-progress request.\n // Attach a promise to the entry that will resolve when the server responds.\n let promiseWithResolvers = pendingEntry.promise\n if (promiseWithResolvers === null) {\n promiseWithResolvers = pendingEntry.promise =\n createPromiseWithResolvers<FulfilledSegmentCacheEntry | null>()\n } else {\n // There's already a promise we can use\n }\n return promiseWithResolvers.promise\n}\n\nfunction createDetachedRouteCacheEntry(): PendingRouteCacheEntry {\n return {\n canonicalUrl: null,\n status: EntryStatus.Empty,\n blockedTasks: null,\n tree: null,\n metadata: null,\n // This is initialized to true because we don't know yet whether the route\n // could be intercepted. It's only set to false once we receive a response\n // from the server.\n couldBeIntercepted: true,\n // Similarly, we don't yet know if the route supports PPR.\n supportsPerSegmentPrefetching: false,\n renderedSearch: null,\n\n // Map-related fields\n ref: null,\n size: 0,\n // Since this is an empty entry, there's no reason to ever evict it. It will\n // be updated when the data is populated.\n staleAt: Infinity,\n version: getCurrentRouteCacheVersion(),\n }\n}\n\n/**\n * Checks if an entry for a route exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateRouteCacheEntry(\n now: number,\n task: PrefetchTask,\n key: RouteCacheKey\n): RouteCacheEntry {\n attachInvalidationListener(task)\n\n const existingEntry = readRouteCacheEntry(now, key)\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache.\n const pendingEntry = createDetachedRouteCacheEntry()\n const varyPath: RouteVaryPath = getRouteVaryPath(\n key.pathname,\n key.search,\n key.nextUrl\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, varyPath, pendingEntry, isRevalidation)\n return pendingEntry\n}\n\n// TODO: This function predates the new optimisticRouting feature and will be\n// removed once optimisticRouting is stable. The new mechanism (matchKnownRoute)\n// handles search param variations more robustly as part of the general route\n// prediction system. This fallback remains for when optimisticRouting is\n// disabled (staticChildren is null).\nexport function deprecated_requestOptimisticRouteCacheEntry(\n now: number,\n requestedUrl: URL,\n nextUrl: string | null\n): FulfilledRouteCacheEntry | null {\n // This function is called during a navigation when there was no matching\n // route tree in the prefetch cache. Before de-opting to a blocking,\n // unprefetched navigation, we will first attempt to construct an \"optimistic\"\n // route tree by checking the cache for similar routes.\n //\n // Check if there's a route with the same pathname, but with different\n // search params. We can then base our optimistic route tree on this entry.\n //\n // Conceptually, we are simulating what would happen if we did perform a\n // prefetch the requested URL, under the assumption that the server will\n // not redirect or rewrite the request in a different manner than the\n // base route tree. This assumption might not hold, in which case we'll have\n // to recover when we perform the dynamic navigation request. However, this\n // is what would happen if a route were dynamically rewritten/redirected\n // in between the prefetch and the navigation. So the logic needs to exist\n // to handle this case regardless.\n\n // Look for a route with the same pathname, but with an empty search string.\n // TODO: There's nothing inherently special about the empty search string;\n // it's chosen somewhat arbitrarily, with the rationale that it's the most\n // likely one to exist. But we should update this to match _any_ search\n // string. The plan is to generalize this logic alongside other improvements\n // related to \"fallback\" cache entries.\n const requestedSearch = requestedUrl.search as NormalizedSearch\n if (requestedSearch === '') {\n // The caller would have already checked if a route with an empty search\n // string is in the cache. So we can bail out here.\n return null\n }\n const urlWithoutSearchParams = new URL(requestedUrl)\n urlWithoutSearchParams.search = ''\n const routeWithNoSearchParams = readRouteCacheEntry(\n now,\n createPrefetchRequestKey(urlWithoutSearchParams.href, nextUrl)\n )\n\n if (\n routeWithNoSearchParams === null ||\n routeWithNoSearchParams.status !== EntryStatus.Fulfilled\n ) {\n // Bail out of constructing an optimistic route tree. This will result in\n // a blocking, unprefetched navigation.\n return null\n }\n\n // Now we have a base route tree we can \"patch\" with our optimistic values.\n\n // Optimistically assume that redirects for the requested pathname do\n // not vary on the search string. Therefore, if the base route was\n // redirected to a different search string, then the optimistic route\n // should be redirected to the same search string. Otherwise, we use\n // the requested search string.\n const canonicalUrlForRouteWithNoSearchParams = new URL(\n routeWithNoSearchParams.canonicalUrl,\n requestedUrl.origin\n )\n const optimisticCanonicalSearch =\n canonicalUrlForRouteWithNoSearchParams.search !== ''\n ? // Base route was redirected. Reuse the same redirected search string.\n canonicalUrlForRouteWithNoSearchParams.search\n : requestedSearch\n\n // Similarly, optimistically assume that rewrites for the requested\n // pathname do not vary on the search string. Therefore, if the base\n // route was rewritten to a different search string, then the optimistic\n // route should be rewritten to the same search string. Otherwise, we use\n // the requested search string.\n const optimisticRenderedSearch =\n routeWithNoSearchParams.renderedSearch !== ''\n ? // Base route was rewritten. Reuse the same rewritten search string.\n routeWithNoSearchParams.renderedSearch\n : requestedSearch\n\n const optimisticUrl = new URL(\n routeWithNoSearchParams.canonicalUrl,\n location.origin\n )\n optimisticUrl.search = optimisticCanonicalSearch\n const optimisticCanonicalUrl = createHrefFromUrl(optimisticUrl)\n\n const optimisticRouteTree = deprecated_createOptimisticRouteTree(\n routeWithNoSearchParams.tree,\n optimisticRenderedSearch\n )\n const optimisticMetadataTree = deprecated_createOptimisticRouteTree(\n routeWithNoSearchParams.metadata,\n optimisticRenderedSearch\n )\n\n // Clone the base route tree, and override the relevant fields with our\n // optimistic values.\n const optimisticEntry: FulfilledRouteCacheEntry = {\n canonicalUrl: optimisticCanonicalUrl,\n\n status: EntryStatus.Fulfilled,\n // This isn't cloned because it's instance-specific\n blockedTasks: null,\n tree: optimisticRouteTree,\n metadata: optimisticMetadataTree,\n couldBeIntercepted: routeWithNoSearchParams.couldBeIntercepted,\n supportsPerSegmentPrefetching:\n routeWithNoSearchParams.supportsPerSegmentPrefetching,\n hasDynamicRewrite: routeWithNoSearchParams.hasDynamicRewrite,\n\n // Override the rendered search with the optimistic value.\n renderedSearch: optimisticRenderedSearch,\n\n // Map-related fields\n ref: null,\n size: 0,\n staleAt: routeWithNoSearchParams.staleAt,\n version: routeWithNoSearchParams.version,\n }\n\n // Do not insert this entry into the cache. It only exists so we can\n // perform the current navigation. Just return it to the caller.\n return optimisticEntry\n}\n\nfunction deprecated_createOptimisticRouteTree(\n tree: RouteTree,\n newRenderedSearch: NormalizedSearch\n): RouteTree {\n // Create a new route tree that identical to the original one except for\n // the rendered search string, which is contained in the vary path.\n\n let clonedSlots: Record<string, RouteTree> | null = null\n const originalSlots = tree.slots\n if (originalSlots !== null) {\n clonedSlots = {}\n for (const parallelRouteKey in originalSlots) {\n const childTree = originalSlots[parallelRouteKey]\n clonedSlots[parallelRouteKey] = deprecated_createOptimisticRouteTree(\n childTree,\n newRenderedSearch\n )\n }\n }\n\n // We only need to clone the vary path if the route is a page.\n if (tree.isPage) {\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n refreshState: tree.refreshState,\n varyPath: clonePageVaryPathWithNewSearchParams(\n tree.varyPath,\n newRenderedSearch\n ),\n isPage: true,\n slots: clonedSlots,\n\n prefetchHints: tree.prefetchHints,\n }\n }\n\n return {\n requestKey: tree.requestKey,\n segment: tree.segment,\n refreshState: tree.refreshState,\n varyPath: tree.varyPath,\n isPage: false,\n slots: clonedSlots,\n prefetchHints: tree.prefetchHints,\n }\n}\n\n/**\n * Checks if an entry for a segment exists in the cache. If so, it returns the\n * entry, If not, it adds an empty entry to the cache and returns it.\n */\nexport function readOrCreateSegmentCacheEntry(\n now: number,\n fetchStrategy: FetchStrategy,\n tree: RouteTree\n): SegmentCacheEntry {\n const existingEntry = readSegmentCacheEntry(now, tree.varyPath)\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache. The stale time is set to a\n // default value; the actual stale time will be set when the entry is\n // fulfilled with data from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(now)\n const isRevalidation = false\n setInCacheMap(\n segmentCacheMap,\n varyPathForRequest,\n pendingEntry,\n isRevalidation\n )\n return pendingEntry\n}\n\nexport function readOrCreateRevalidatingSegmentEntry(\n now: number,\n fetchStrategy: FetchStrategy,\n tree: RouteTree\n): SegmentCacheEntry {\n // This function is called when we've already confirmed that a particular\n // segment is cached, but we want to perform another request anyway in case it\n // returns more complete and/or fresher data than we already have. The logic\n // for deciding whether to replace the existing entry is handled elsewhere;\n // this function just handles retrieving a cache entry that we can use to\n // track the revalidation.\n //\n // The reason revalidations are stored in the cache is because we need to be\n // able to dedupe multiple revalidation requests. The reason they have to be\n // handled specially is because we shouldn't overwrite a \"normal\" entry if\n // one exists at the same keypath. So, for each internal cache location, there\n // is a special \"revalidation\" slot that is used solely for this purpose.\n //\n // You can think of it as if all the revalidation entries were stored in a\n // separate cache map from the canonical entries, and then transfered to the\n // canonical cache map once the request is complete — this isn't how it's\n // actually implemented, since it's more efficient to store them in the same\n // data structure as the normal entries, but that's how it's modeled\n // conceptually.\n\n // TODO: Once we implement Fallback behavior for params, where an entry is\n // re-keyed based on response information, we'll need to account for the\n // possibility that the keypath of the previous entry is more generic than\n // the keypath of the revalidating entry. In other words, the server could\n // return a less generic entry upon revalidation. For now, though, this isn't\n // a concern because the keypath is based solely on the prefetch strategy,\n // not on data contained in the response.\n const existingEntry = readRevalidatingSegmentCacheEntry(now, tree.varyPath)\n if (existingEntry !== null) {\n return existingEntry\n }\n // Create a pending entry and add it to the cache. The stale time is set to a\n // default value; the actual stale time will be set when the entry is\n // fulfilled with data from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(now)\n const isRevalidation = true\n setInCacheMap(\n segmentCacheMap,\n varyPathForRequest,\n pendingEntry,\n isRevalidation\n )\n return pendingEntry\n}\n\nexport function overwriteRevalidatingSegmentCacheEntry(\n now: number,\n fetchStrategy: FetchStrategy,\n tree: RouteTree\n) {\n // This function is called when we've already decided to replace an existing\n // revalidation entry. Create a new entry and write it into the cache,\n // overwriting the previous value. The stale time is set to a default value;\n // the actual stale time will be set when the entry is fulfilled with data\n // from the server response.\n const varyPathForRequest = getSegmentVaryPathForRequest(fetchStrategy, tree)\n const pendingEntry = createDetachedSegmentCacheEntry(now)\n const isRevalidation = true\n setInCacheMap(\n segmentCacheMap,\n varyPathForRequest,\n pendingEntry,\n isRevalidation\n )\n return pendingEntry\n}\n\nexport function upsertSegmentEntry(\n now: number,\n varyPath: SegmentVaryPath,\n candidateEntry: SegmentCacheEntry\n): SegmentCacheEntry | null {\n // We have a new entry that has not yet been inserted into the cache. Before\n // we do so, we need to confirm whether it takes precedence over the existing\n // entry (if one exists).\n // TODO: We should not upsert an entry if its key was invalidated in the time\n // since the request was made. We can do that by passing the \"owner\" entry to\n // this function and confirming it's the same as `existingEntry`.\n\n if (isValueExpired(now, getCurrentSegmentCacheVersion(), candidateEntry)) {\n // The entry is expired. We cannot upsert it.\n return null\n }\n\n const existingEntry = readSegmentCacheEntry(now, varyPath)\n if (existingEntry !== null) {\n // Don't replace a more specific segment with a less-specific one. A case where this\n // might happen is if the existing segment was fetched via\n // `<Link prefetch={true}>`.\n if (\n // We fetched the new segment using a different, less specific fetch strategy\n // than the segment we already have in the cache, so it can't have more content.\n (candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&\n !canNewFetchStrategyProvideMoreContent(\n existingEntry.fetchStrategy,\n candidateEntry.fetchStrategy\n )) ||\n // The existing entry isn't partial, but the new one is.\n // (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)\n (!existingEntry.isPartial && candidateEntry.isPartial)\n ) {\n // We're going to leave revalidating entry in the cache so that it doesn't\n // get revalidated again unnecessarily. Downgrade the Fulfilled entry to\n // Rejected and null out the data so it can be garbage collected. We leave\n // `staleAt` intact to prevent subsequent revalidation attempts only until\n // the entry expires.\n const rejectedEntry: RejectedSegmentCacheEntry = candidateEntry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.rsc = null\n return null\n }\n\n // Evict the existing entry from the cache.\n deleteFromCacheMap(existingEntry)\n }\n\n const isRevalidation = false\n setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation)\n return candidateEntry\n}\n\nexport function createDetachedSegmentCacheEntry(\n now: number\n): EmptySegmentCacheEntry {\n // Default stale time for pending segment cache entries. The actual stale time\n // is set when the entry is fulfilled with data from the server response.\n const staleAt = now + 30 * 1000\n const emptyEntry: EmptySegmentCacheEntry = {\n status: EntryStatus.Empty,\n // Default to assuming the fetch strategy will be PPR. This will be updated\n // when a fetch is actually initiated.\n fetchStrategy: FetchStrategy.PPR,\n rsc: null,\n isPartial: true,\n promise: null,\n\n // Map-related fields\n ref: null,\n size: 0,\n staleAt,\n version: 0,\n }\n return emptyEntry\n}\n\nexport function upgradeToPendingSegment(\n emptyEntry: EmptySegmentCacheEntry,\n fetchStrategy: FetchStrategy\n): PendingSegmentCacheEntry {\n const pendingEntry: PendingSegmentCacheEntry = emptyEntry as any\n pendingEntry.status = EntryStatus.Pending\n pendingEntry.fetchStrategy = fetchStrategy\n\n if (fetchStrategy === FetchStrategy.Full) {\n // We can assume the response will contain the full segment data. Set this\n // to false so we know it's OK to omit this segment from any navigation\n // requests that may happen while the data is still pending.\n pendingEntry.isPartial = false\n }\n\n // Set the version here, since this is right before the request is initiated.\n // The next time the segment cache version is incremented, the entry will\n // effectively be evicted. This happens before initiating the request, rather\n // than when receiving the response, because it's guaranteed to happen\n // before the data is read on the server.\n pendingEntry.version = getCurrentSegmentCacheVersion()\n return pendingEntry\n}\n\nexport function attemptToFulfillDynamicSegmentFromBFCache(\n now: number,\n segment: EmptySegmentCacheEntry,\n tree: RouteTree\n): FulfilledSegmentCacheEntry | null {\n // Attempts to fulfill an empty segment cache entry using data from the\n // bfcache. This is only valid during a Full prefetch (i.e. one that includes\n // dynamic data), because the bfcache stores data from navigations which\n // always include dynamic data.\n\n // We always use the canonical vary path when checking the bfcache. This is\n // the same operation we'd use to access the cache during a\n // regular navigation.\n const varyPath = tree.varyPath\n\n // Read from the BFCache without expiring it (pass -1). We check freshness\n // ourselves using navigatedAt, because the BFCache's staleAt may have been\n // overridden by a per-page unstable_dynamicStaleTime and can't be used to\n // derive the original request time.\n const bfcacheEntry = readFromBFCache(varyPath)\n if (bfcacheEntry !== null) {\n // The stale time for dynamic prefetches (default: 5 mins) is different\n // from the stale time for regular navigations (default: 0 secs). Use\n // navigatedAt to compute the correct expiry for prefetch purposes.\n const dynamicPrefetchStaleAt =\n bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n if (now > dynamicPrefetchStaleAt) {\n return null\n }\n\n const pendingSegment = upgradeToPendingSegment(segment, FetchStrategy.Full)\n const isPartial = false\n return fulfillSegmentCacheEntry(\n pendingSegment,\n bfcacheEntry.rsc,\n dynamicPrefetchStaleAt,\n isPartial\n )\n }\n return null\n}\n\n/**\n * Attempts to replace an existing segment cache entry with data from the\n * bfcache. Unlike `attemptToFulfillDynamicSegmentFromBFCache` (which fills an\n * empty entry), this creates a new entry and upserts it, so it works even when\n * the segment is already fulfilled.\n */\nexport function attemptToUpgradeSegmentFromBFCache(\n now: number,\n tree: RouteTree\n): FulfilledSegmentCacheEntry | null {\n const varyPath = tree.varyPath\n const bfcacheEntry = readFromBFCache(varyPath)\n if (bfcacheEntry !== null) {\n const dynamicPrefetchStaleAt =\n bfcacheEntry.navigatedAt + STATIC_STALETIME_MS\n if (now > dynamicPrefetchStaleAt) {\n return null\n }\n const pendingSegment = upgradeToPendingSegment(\n createDetachedSegmentCacheEntry(now),\n FetchStrategy.Full\n )\n const isPartial = false\n const newEntry = fulfillSegmentCacheEntry(\n pendingSegment,\n bfcacheEntry.rsc,\n dynamicPrefetchStaleAt,\n isPartial\n )\n const segmentVaryPath = getSegmentVaryPathForRequest(\n FetchStrategy.Full,\n tree\n )\n const upserted = upsertSegmentEntry(now, segmentVaryPath, newEntry)\n if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {\n return upserted\n }\n }\n return null\n}\n\nfunction pingBlockedTasks(entry: {\n blockedTasks: Set<PrefetchTask> | null\n}): void {\n const blockedTasks = entry.blockedTasks\n if (blockedTasks !== null) {\n for (const task of blockedTasks) {\n pingPrefetchTask(task)\n }\n entry.blockedTasks = null\n }\n}\n\nexport function createMetadataRouteTree(\n metadataVaryPath: PageVaryPath\n): RouteTree {\n // The Head is not actually part of the route tree, but other than that, it's\n // fetched and cached like a segment. Some functions expect a RouteTree\n // object, so rather than fork the logic in all those places, we use this\n // \"fake\" one.\n const metadata: RouteTree = {\n requestKey: HEAD_REQUEST_KEY,\n segment: HEAD_REQUEST_KEY,\n refreshState: null,\n varyPath: metadataVaryPath,\n // The metadata isn't really a \"page\" (though it isn't really a \"segment\"\n // either) but for the purposes of how this field is used, it behaves like\n // one. If this logic ever gets more complex we can change this to an enum.\n isPage: true,\n slots: null,\n prefetchHints: 0,\n }\n return metadata\n}\n\nexport function fulfillRouteCacheEntry(\n now: number,\n entry: PendingRouteCacheEntry,\n tree: RouteTree,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n // Get the rendered search from the vary path\n const renderedSearch =\n getRenderedSearchFromVaryPath(metadataVaryPath) ?? ('' as NormalizedSearch)\n const fulfilledEntry: FulfilledRouteCacheEntry = entry as any\n fulfilledEntry.status = EntryStatus.Fulfilled\n fulfilledEntry.tree = tree\n fulfilledEntry.metadata = createMetadataRouteTree(metadataVaryPath)\n // Route structure is essentially static — it only changes on deploy.\n // Always use the static stale time.\n // NOTE: An exception is rewrites/redirects in middleware or proxy, which can\n // change routes dynamically. We have other strategies for handling those.\n fulfilledEntry.staleAt = now + STATIC_STALETIME_MS\n fulfilledEntry.couldBeIntercepted = couldBeIntercepted\n fulfilledEntry.canonicalUrl = canonicalUrl\n fulfilledEntry.renderedSearch = renderedSearch\n fulfilledEntry.supportsPerSegmentPrefetching = supportsPerSegmentPrefetching\n fulfilledEntry.hasDynamicRewrite = false\n pingBlockedTasks(entry)\n return fulfilledEntry\n}\n\nexport function writeRouteIntoCache(\n now: number,\n pathname: NormalizedPathname,\n nextUrl: string | null,\n tree: RouteTree,\n metadataVaryPath: PageVaryPath,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n supportsPerSegmentPrefetching: boolean\n): FulfilledRouteCacheEntry {\n const pendingEntry = createDetachedRouteCacheEntry()\n const fulfilledEntry = fulfillRouteCacheEntry(\n now,\n pendingEntry,\n tree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n supportsPerSegmentPrefetching\n )\n const renderedSearch = fulfilledEntry.renderedSearch\n const varyPath = getFulfilledRouteVaryPath(\n pathname,\n renderedSearch,\n nextUrl as NormalizedNextUrl | null,\n couldBeIntercepted\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, varyPath, fulfilledEntry, isRevalidation)\n return fulfilledEntry\n}\n\n/**\n * Marks a route cache entry as having a dynamic rewrite. Called when we\n * discover that a route pattern has dynamic rewrite behavior - i.e., we used\n * an optimistic route tree for prediction, but the server responded with a\n * different rendered pathname.\n *\n * Once marked, attempts to use this entry as a template for prediction will\n * bail out to server resolution.\n */\nexport function markRouteEntryAsDynamicRewrite(\n entry: FulfilledRouteCacheEntry\n): void {\n entry.hasDynamicRewrite = true\n // Note: The caller is responsible for also calling invalidateRouteCacheEntries\n // to invalidate other entries that may have been derived from this template\n // before we knew it had a dynamic rewrite.\n}\n\nfunction fulfillSegmentCacheEntry(\n segmentCacheEntry: PendingSegmentCacheEntry,\n rsc: React.ReactNode,\n staleAt: number,\n isPartial: boolean\n): FulfilledSegmentCacheEntry {\n const fulfilledEntry: FulfilledSegmentCacheEntry = segmentCacheEntry as any\n fulfilledEntry.status = EntryStatus.Fulfilled\n fulfilledEntry.rsc = rsc\n fulfilledEntry.staleAt = staleAt\n fulfilledEntry.isPartial = isPartial\n // Resolve any listeners that were waiting for this data.\n if (segmentCacheEntry.promise !== null) {\n segmentCacheEntry.promise.resolve(fulfilledEntry)\n // Free the promise for garbage collection.\n fulfilledEntry.promise = null\n }\n return fulfilledEntry\n}\n\nfunction rejectRouteCacheEntry(\n entry: PendingRouteCacheEntry,\n staleAt: number\n): void {\n const rejectedEntry: RejectedRouteCacheEntry = entry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.staleAt = staleAt\n pingBlockedTasks(entry)\n}\n\nfunction rejectSegmentCacheEntry(\n entry: PendingSegmentCacheEntry,\n staleAt: number\n): void {\n const rejectedEntry: RejectedSegmentCacheEntry = entry as any\n rejectedEntry.status = EntryStatus.Rejected\n rejectedEntry.staleAt = staleAt\n if (entry.promise !== null) {\n // NOTE: We don't currently propagate the reason the prefetch was canceled\n // but we could by accepting a `reason` argument.\n entry.promise.resolve(null)\n entry.promise = null\n }\n}\n\ntype RouteTreeAccumulator = {\n metadataVaryPath: PageVaryPath | null\n}\n\nfunction convertRootTreePrefetchToRouteTree(\n rootTree: RootTreePrefetch,\n renderedPathname: string,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n) {\n // Remove trailing and leading slashes\n const pathnameParts = renderedPathname.split('/').filter((p) => p !== '')\n const index = 0\n const rootSegment = ROOT_SEGMENT_REQUEST_KEY\n return convertTreePrefetchToRouteTree(\n rootTree.tree,\n rootSegment,\n null,\n ROOT_SEGMENT_REQUEST_KEY,\n pathnameParts,\n index,\n renderedSearch,\n acc\n )\n}\n\nfunction convertTreePrefetchToRouteTree(\n prefetch: TreePrefetch,\n segment: FlightRouterStateSegment,\n partialVaryPath: PartialSegmentVaryPath | null,\n requestKey: SegmentRequestKey,\n pathnameParts: Array<string>,\n pathnamePartsIndex: number,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree {\n // Converts the route tree sent by the server into the format used by the\n // cache. The cached version of the tree includes additional fields, such as a\n // cache key for each segment. Since this is frequently accessed, we compute\n // it once instead of on every access. This same cache key is also used to\n // request the segment from the server.\n\n let slots: { [parallelRouteKey: string]: RouteTree } | null = null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n const prefetchSlots = prefetch.slots\n if (prefetchSlots !== null) {\n isPage = false\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n\n slots = {}\n for (let parallelRouteKey in prefetchSlots) {\n const childPrefetch = prefetchSlots[parallelRouteKey]\n const childSegmentName = childPrefetch.name\n const childParam = childPrefetch.param\n\n let childDoesAppearInURL: boolean\n let childSegment: FlightRouterStateSegment\n let childPartialVaryPath: PartialSegmentVaryPath | null\n if (childParam !== null) {\n // This segment is parameterized. Get the param from the pathname.\n const childParamValue = parseDynamicParamFromURLPart(\n childParam.type,\n pathnameParts,\n pathnamePartsIndex\n )\n\n // Assign a cache key to the segment, based on the param value. In the\n // pre-Segment Cache implementation, the server computes this and sends\n // it in the body of the response. In the Segment Cache implementation,\n // the server sends an empty string and we fill it in here.\n\n // TODO: We're intentionally not adding the search param to page\n // segments here; it's tracked separately and added back during a read.\n // This would clearer if we waited to construct the segment until it's\n // read from the cache, since that's effectively what we're\n // doing anyway.\n const childParamKey =\n // The server omits this field from the prefetch response when\n // cacheComponents is enabled.\n childParam.key !== null\n ? childParam.key\n : // If no param key was sent, use the value parsed on the client.\n getCacheKeyForDynamicParam(\n childParamValue,\n '' as NormalizedSearch\n )\n\n childPartialVaryPath = appendLayoutVaryPath(\n partialVaryPath,\n childParamKey,\n childSegmentName\n )\n childSegment = [\n childSegmentName,\n childParamKey,\n childParam.type,\n childParam.siblings,\n ]\n childDoesAppearInURL = true\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n childPartialVaryPath = partialVaryPath\n childSegment = childSegmentName\n childDoesAppearInURL = doesStaticSegmentAppearInURL(childSegmentName)\n }\n\n // Only increment the index if the segment appears in the URL. If it's a\n // \"virtual\" segment, like a route group, it remains the same.\n const childPathnamePartsIndex = childDoesAppearInURL\n ? pathnamePartsIndex + 1\n : pathnamePartsIndex\n\n const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n childRequestKeyPart\n )\n slots[parallelRouteKey] = convertTreePrefetchToRouteTree(\n childPrefetch,\n childSegment,\n childPartialVaryPath,\n childRequestKey,\n pathnameParts,\n childPathnamePartsIndex,\n renderedSearch,\n acc\n )\n }\n } else {\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n\n return {\n requestKey,\n segment,\n refreshState: null,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. The fix would be to\n // create separate constructors and call the appropriate one from each of\n // the branches above. Just seems a bit overkill only for one field so I'll\n // leave it as-is for now. If isPage were wrong it would break the behavior\n // and we'd catch it quickly, anyway.\n varyPath: varyPath as any,\n isPage: isPage as boolean as any,\n slots,\n prefetchHints: prefetch.prefetchHints,\n }\n}\n\nexport function convertRootFlightRouterStateToRouteTree(\n flightRouterState: FlightRouterState,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree {\n return convertFlightRouterStateToRouteTree(\n flightRouterState,\n ROOT_SEGMENT_REQUEST_KEY,\n null,\n renderedSearch,\n acc\n )\n}\n\nexport function convertReusedFlightRouterStateToRouteTree(\n parentRouteTree: RouteTree,\n parallelRouteKey: string,\n flightRouterState: FlightRouterState,\n renderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n) {\n // Create a RouteTree for a FlightRouterState that was reused from an older\n // route. This happens during a navigation when a parallel route slot does not\n // match the target route; we reuse whatever slot was already active.\n\n // Unlike a FlightRouterState, the RouteTree type contains backreferences to\n // the parent segments. Append the vary path to the parent's vary path.\n const parentPartialVaryPath = parentRouteTree.isPage\n ? getPartialPageVaryPath(parentRouteTree.varyPath)\n : getPartialLayoutVaryPath(parentRouteTree.varyPath)\n const segment = flightRouterState[0]\n // And the request key.\n const parentRequestKey = parentRouteTree.requestKey\n const requestKeyPart = createSegmentRequestKeyPart(segment)\n const requestKey = appendSegmentRequestKeyPart(\n parentRequestKey,\n parallelRouteKey,\n requestKeyPart\n )\n return convertFlightRouterStateToRouteTree(\n flightRouterState,\n requestKey,\n parentPartialVaryPath,\n renderedSearch,\n acc\n )\n}\n\nfunction convertFlightRouterStateToRouteTree(\n flightRouterState: FlightRouterState,\n requestKey: SegmentRequestKey,\n parentPartialVaryPath: PartialSegmentVaryPath | null,\n parentRenderedSearch: NormalizedSearch,\n acc: RouteTreeAccumulator\n): RouteTree {\n const originalSegment = flightRouterState[0]\n\n // If the FlightRouterState has a refresh state, then this segment is part of\n // an inactive parallel route. It has a different rendered search query than\n // the outer parent route. In order to construct the inactive route correctly,\n // we must restore the query that was originally used to render it.\n const compressedRefreshState = flightRouterState[2] ?? null\n const refreshState =\n compressedRefreshState !== null\n ? {\n canonicalUrl: compressedRefreshState[0] as string,\n renderedSearch: compressedRefreshState[1] as NormalizedSearch,\n }\n : null\n const renderedSearch =\n refreshState !== null ? refreshState.renderedSearch : parentRenderedSearch\n\n let segment: FlightRouterStateSegment\n let partialVaryPath: PartialSegmentVaryPath | null\n let isPage: boolean\n let varyPath: SegmentVaryPath\n if (Array.isArray(originalSegment)) {\n isPage = false\n const paramCacheKey = originalSegment[1]\n const paramName = originalSegment[0]\n partialVaryPath = appendLayoutVaryPath(\n parentPartialVaryPath,\n paramCacheKey,\n paramName\n )\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n segment = originalSegment\n } else {\n // This segment does not have a param. Inherit the partial vary path of\n // the parent.\n partialVaryPath = parentPartialVaryPath\n if (requestKey.endsWith(PAGE_SEGMENT_KEY)) {\n // This is a page segment.\n isPage = true\n\n // The navigation implementation expects the search params to be included\n // in the segment. However, in the case of a static response, the search\n // params are omitted. So the client needs to add them back in when reading\n // from the Segment Cache.\n //\n // For consistency, we'll do this for dynamic responses, too.\n //\n // TODO: We should move search params out of FlightRouterState and handle\n // them entirely on the client, similar to our plan for dynamic params.\n segment = PAGE_SEGMENT_KEY\n varyPath = finalizePageVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n // The metadata \"segment\" is not part the route tree, but it has the same\n // conceptual params as a page segment. Write the vary path into the\n // accumulator object. If there are multiple parallel pages, we use the\n // first one. Which page we choose is arbitrary as long as it's\n // consistently the same one every time every time. See\n // finalizeMetadataVaryPath for more details.\n if (acc.metadataVaryPath === null) {\n acc.metadataVaryPath = finalizeMetadataVaryPath(\n requestKey,\n renderedSearch,\n partialVaryPath\n )\n }\n } else {\n // This is a layout segment.\n isPage = false\n segment = originalSegment\n varyPath = finalizeLayoutVaryPath(requestKey, partialVaryPath)\n }\n }\n\n let slots: { [parallelRouteKey: string]: RouteTree } | null = null\n\n const parallelRoutes = flightRouterState[1]\n for (let parallelRouteKey in parallelRoutes) {\n const childRouterState = parallelRoutes[parallelRouteKey]\n const childSegment = childRouterState[0]\n // TODO: Eventually, the param values will not be included in the response\n // from the server. We'll instead fill them in on the client by parsing\n // the URL. This is where we'll do that.\n const childRequestKeyPart = createSegmentRequestKeyPart(childSegment)\n const childRequestKey = appendSegmentRequestKeyPart(\n requestKey,\n parallelRouteKey,\n childRequestKeyPart\n )\n const childTree = convertFlightRouterStateToRouteTree(\n childRouterState,\n childRequestKey,\n partialVaryPath,\n renderedSearch,\n acc\n )\n if (slots === null) {\n slots = {\n [parallelRouteKey]: childTree,\n }\n } else {\n slots[parallelRouteKey] = childTree\n }\n }\n\n return {\n requestKey,\n segment,\n refreshState,\n // TODO: Cheating the type system here a bit because TypeScript can't tell\n // that the type of isPage and varyPath are consistent. The fix would be to\n // create separate constructors and call the appropriate one from each of\n // the branches above. Just seems a bit overkill only for one field so I'll\n // leave it as-is for now. If isPage were wrong it would break the behavior\n // and we'd catch it quickly, anyway.\n varyPath: varyPath as any,\n isPage: isPage as boolean as any,\n slots,\n prefetchHints: flightRouterState[4] ?? 0,\n }\n}\n\nexport function convertRouteTreeToFlightRouterState(\n routeTree: RouteTree\n): FlightRouterState {\n const parallelRoutes: Record<string, FlightRouterState> = {}\n if (routeTree.slots !== null) {\n for (const parallelRouteKey in routeTree.slots) {\n parallelRoutes[parallelRouteKey] = convertRouteTreeToFlightRouterState(\n routeTree.slots[parallelRouteKey]\n )\n }\n }\n const flightRouterState: FlightRouterState = [\n routeTree.segment,\n parallelRoutes,\n null,\n null,\n ]\n return flightRouterState\n}\n\nexport async function fetchRouteOnCacheMiss(\n entry: PendingRouteCacheEntry,\n key: RouteCacheKey\n): Promise<PrefetchSubtaskResult<null> | null> {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n const pathname = key.pathname\n const search = key.search\n const nextUrl = key.nextUrl\n const segmentPath = '/_tree' as SegmentRequestKey\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: segmentPath,\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n // Tell the server to perform a static pre-render for the Instant Navigation\n // Testing API. Static pre-renders don't normally happen during development.\n addInstantPrefetchHeaderIfLocked(headers)\n\n try {\n const url = new URL(pathname + search, location.origin)\n let response\n let urlAfterRedirects\n if (isOutputExportMode) {\n // In output: \"export\" mode, we can't use headers to request a particular\n // segment. Instead, we encode the extra request information into the URL.\n // This is not part of the \"public\" interface of the app; it's an internal\n // Next.js implementation detail that the app developer should not need to\n // concern themselves with.\n //\n // For example, to request a segment:\n //\n // Path passed to <Link>: /path/to/page\n // Path passed to fetch: /path/to/page/__next-segments/_tree\n //\n // (This is not the exact protocol, just an illustration.)\n //\n // Before we do that, though, we need to account for redirects. Even in\n // output: \"export\" mode, a proxy might redirect the page to a different\n // location, but we shouldn't assume or expect that they also redirect all\n // the segment files, too.\n //\n // To check whether the page is redirected, previously we perform a range\n // request of 64 bytes of the HTML document to check if the target page\n // is part of this app (by checking if build id matches). Only if the target\n // page is part of this app do we determine the final canonical URL.\n //\n // However, as mentioned in https://github.com/vercel/next.js/pull/85903,\n // some popular static hosting providers (like Cloudflare Pages or Render.com)\n // do not support range requests, in the worst case, the entire HTML instead\n // of 64 bytes could be returned, which is wasteful.\n //\n // So instead, we drops the check for build id here, and simply perform\n // a HEAD request to rejects 1xx/4xx/5xx responses, and then determine the\n // final URL after redirects.\n //\n // NOTE: We could embed the route tree into the HTML document, to avoid\n // a second request. We're not doing that currently because it would make\n // the HTML document larger and affect normal page loads.\n const headResponse = await fetch(url, {\n method: 'HEAD',\n })\n if (headResponse.status < 200 || headResponse.status >= 400) {\n // The target page responded w/o a successful status code\n // Could be a WAF serving a 403, or a 5xx from a backend\n //\n // Note that we can't use headResponse.ok here, because\n // Response#ok returns `false` with 3xx responses.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n urlAfterRedirects = headResponse.redirected\n ? new URL(headResponse.url)\n : url\n\n response = await fetchPrefetchResponse(\n addSegmentPathToUrlInOutputExportMode(urlAfterRedirects, segmentPath),\n headers\n )\n } else {\n // \"Server\" mode. We can use request headers instead of the pathname.\n // TODO: The eventual plan is to get rid of our custom request headers and\n // encode everything into the URL, using a similar strategy to the\n // \"output: export\" block above.\n response = await fetchPrefetchResponse(url, headers)\n urlAfterRedirects =\n response !== null && response.redirected ? new URL(response.url) : url\n }\n\n if (\n !response ||\n !response.ok ||\n // 204 is a Cache miss. Though theoretically this shouldn't happen when\n // PPR is enabled, because we always respond to route tree requests, even\n // if it needs to be blockingly generated on demand.\n response.status === 204 ||\n !response.body\n ) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n // TODO: The canonical URL is the href without the origin. I think\n // historically the reason for this is because the initial canonical URL\n // gets passed as a prop to the top-level React component, which means it\n // needs to be computed during SSR. If it were to include the origin, it\n // would need to always be same as location.origin on the client, to prevent\n // a hydration mismatch. To sidestep this complexity, we omit the origin.\n //\n // However, since this is neither a native URL object nor a fully qualified\n // URL string, we need to be careful about how we use it. To prevent subtle\n // mistakes, we should create a special type for it, instead of just string.\n // Or, we should just use a (readonly) URL object instead. The type of the\n // prop that we pass to seed the initial state does not need to be the same\n // type as the state itself.\n const canonicalUrl = createHrefFromUrl(urlAfterRedirects)\n\n // Check whether the response varies based on the Next-Url header.\n const varyHeader = response.headers.get('vary')\n const couldBeIntercepted =\n varyHeader !== null && varyHeader.includes(NEXT_URL)\n\n // TODO: The `closed` promise was originally used to track when a streaming\n // network connection closes, so the scheduler could limit concurrent\n // connections. Now that prefetch responses are buffered, `closed` is\n // resolved immediately after buffering — before the outer function even\n // returns. This mechanism is only still meaningful for dynamic (Full)\n // prefetches, which use incremental streaming. Consider removing the\n // `closed` plumbing for buffered prefetch paths.\n const closed = createPromiseWithResolvers<void>()\n\n // This checks whether the response was served from the per-segment cache,\n // rather than the old prefetching flow. If it fails, it implies that PPR\n // is disabled on this route.\n const routeIsPPREnabled =\n response.headers.get(NEXT_DID_POSTPONE_HEADER) === '2' ||\n // In output: \"export\" mode, we can't rely on response headers. But if we\n // receive a well-formed response, we can assume it's a static response,\n // because all data is static in this mode.\n isOutputExportMode\n\n if (routeIsPPREnabled) {\n const { stream: prefetchStream, size: responseSize } =\n await createNonTaskyPrefetchResponseStream(response.body)\n closed.resolve()\n setSizeInCacheMap(entry, responseSize)\n const serverData = await createFromNextReadableStream<RootTreePrefetch>(\n prefetchStream,\n headers,\n { allowPartialStream: true }\n )\n\n if (\n (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n serverData.buildId) !== getNavigationBuildId()\n ) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n // Get the params that were used to render the target page. These may\n // be different from the params in the request URL, if the page\n // was rewritten.\n const renderedPathname = getRenderedPathname(response)\n const renderedSearch = getRenderedSearch(response)\n\n // Convert the server-sent data into the RouteTree format used by the\n // client cache.\n //\n // During this traversal, we accumulate additional data into this\n // \"accumulator\" object.\n const acc: RouteTreeAccumulator = { metadataVaryPath: null }\n const routeTree = convertRootTreePrefetchToRouteTree(\n serverData,\n renderedPathname,\n renderedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n discoverKnownRoute(\n Date.now(),\n pathname,\n nextUrl,\n entry,\n routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n routeIsPPREnabled,\n false // hasDynamicRewrite\n )\n } else {\n // PPR is not enabled for this route. The server responds with a\n // different format (FlightRouterState) that we need to convert.\n // TODO: We will unify the responses eventually. I'm keeping the types\n // separate for now because FlightRouterState has so many\n // overloaded concerns.\n const { stream: prefetchStream, size: responseSize } =\n await createNonTaskyPrefetchResponseStream(response.body)\n closed.resolve()\n setSizeInCacheMap(entry, responseSize)\n const serverData =\n await createFromNextReadableStream<NavigationFlightResponse>(\n prefetchStream,\n headers,\n { allowPartialStream: true }\n )\n\n if (\n (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n serverData.b) !== getNavigationBuildId()\n ) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n // TODO: We should cache the fact that this is an MPA navigation.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n\n // Read head vary params synchronously. Individual segments carry their\n // own thenables in CacheNodeSeedData.\n const headVaryParamsThenable = serverData.h\n const headVaryParams =\n headVaryParamsThenable !== null\n ? readVaryParams(headVaryParamsThenable)\n : null\n writeDynamicTreeResponseIntoCache(\n Date.now(),\n // The non-PPR response format is what we'd get if we prefetched these segments\n // using the LoadingBoundary fetch strategy, so mark their cache entries accordingly.\n FetchStrategy.LoadingBoundary,\n response as RSCResponse<NavigationFlightResponse>,\n serverData,\n entry,\n couldBeIntercepted,\n canonicalUrl,\n routeIsPPREnabled,\n headVaryParams,\n pathname,\n nextUrl\n )\n }\n\n if (!couldBeIntercepted) {\n // This route will never be intercepted. So we can use this entry for all\n // requests to this route, regardless of the Next-Url header. This works\n // because when reading the cache we always check for a valid\n // non-intercepted entry first.\n\n // Re-key the entry. The `set` implementation handles removing it from\n // its previous position in the cache. We don't need to do anything to\n // update the LRU, because the entry is already in it.\n // TODO: Treat this as an upsert — should check if an entry already\n // exists at the new keypath, and if so, whether we should keep that\n // one instead.\n const fulfilledVaryPath: RouteVaryPath = getFulfilledRouteVaryPath(\n pathname,\n search,\n nextUrl,\n couldBeIntercepted\n )\n const isRevalidation = false\n setInCacheMap(routeCacheMap, fulfilledVaryPath, entry, isRevalidation)\n }\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n return { value: null, closed: closed.promise }\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectRouteCacheEntry(entry, Date.now() + 10 * 1000)\n return null\n }\n}\n\nexport async function fetchSegmentOnCacheMiss(\n route: FulfilledRouteCacheEntry,\n segmentCacheEntry: PendingSegmentCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree\n): Promise<PrefetchSubtaskResult<FulfilledSegmentCacheEntry> | null> {\n // This function is allowed to use async/await because it contains the actual\n // fetch that gets issued on a cache miss. Notice it writes the result to the\n // cache entry directly, rather than return data that is then written by\n // the caller.\n //\n // Segment fetches are non-blocking so we don't need to ping the scheduler\n // on completion.\n\n // Use the canonical URL to request the segment, not the original URL. These\n // are usually the same, but the canonical URL will be different if the route\n // tree response was redirected. To avoid an extra waterfall on every segment\n // request, we pass the redirected URL instead of the original one.\n const url = new URL(route.canonicalUrl, location.origin)\n const nextUrl = routeKey.nextUrl\n\n const requestKey = tree.requestKey\n const normalizedRequestKey =\n requestKey === ROOT_SEGMENT_REQUEST_KEY\n ? // The root segment is a special case. To simplify the server-side\n // handling of these requests, we encode the root segment path as\n // `_index` instead of as an empty string. This should be treated as\n // an implementation detail and not as a stable part of the protocol.\n // It just needs to match the equivalent logic that happens when\n // prerendering the responses. It should not leak outside of Next.js.\n ('/_index' as SegmentRequestKey)\n : requestKey\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: normalizedRequestKey,\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n // Tell the server to perform a static pre-render for the Instant Navigation\n // Testing API. Static pre-renders don't normally happen during development.\n addInstantPrefetchHeaderIfLocked(headers)\n\n const requestUrl = isOutputExportMode\n ? // In output: \"export\" mode, we need to add the segment path to the URL.\n addSegmentPathToUrlInOutputExportMode(url, normalizedRequestKey)\n : url\n try {\n const response = await fetchPrefetchResponse(requestUrl, headers)\n if (\n !response ||\n !response.ok ||\n response.status === 204 || // Cache miss\n // This checks whether the response was served from the per-segment cache,\n // rather than the old prefetching flow. If it fails, it implies that PPR\n // is disabled on this route. Theoretically this should never happen\n // because we only issue requests for segments once we've verified that\n // the route supports PPR.\n (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n // In output: \"export\" mode, we can't rely on response headers. But if\n // we receive a well-formed response, we can assume it's a static\n // response, because all data is static in this mode.\n !isOutputExportMode) ||\n !response.body\n ) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n return null\n }\n\n // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n // buffered prefetch paths.\n const closed = createPromiseWithResolvers<void>()\n\n const { stream: prefetchStream, size: responseSize } =\n await createNonTaskyPrefetchResponseStream(response.body)\n closed.resolve()\n setSizeInCacheMap(segmentCacheEntry, responseSize)\n const serverData = await createFromNextReadableStream<SegmentPrefetch>(\n prefetchStream,\n headers,\n { allowPartialStream: true }\n )\n if (\n (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n serverData.buildId) !== getNavigationBuildId()\n ) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n return null\n }\n const now = Date.now()\n const staleAt = now + getStaleTimeMs(serverData.staleTime)\n const fulfilledEntry = fulfillSegmentCacheEntry(\n segmentCacheEntry,\n serverData.rsc,\n staleAt,\n serverData.isPartial\n )\n\n // If the server tells us which params the segment varies by, we can re-key\n // the entry to a more generic vary path. This allows the entry to be reused\n // across different param values for params that the segment doesn't\n // actually depend on.\n const varyParams = serverData.varyParams\n const fulfilledVaryPath =\n process.env.__NEXT_VARY_PARAMS && varyParams !== null\n ? getFulfilledSegmentVaryPath(tree.varyPath, varyParams)\n : getSegmentVaryPathForRequest(segmentCacheEntry.fetchStrategy, tree)\n // Re-key and upsert the entry at the fulfilled vary path. This ensures\n // the entry is stored at the most generic path possible based on which\n // params the segment actually depends on.\n upsertSegmentEntry(now, fulfilledVaryPath, fulfilledEntry)\n\n return {\n value: fulfilledEntry,\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n closed: closed.promise,\n }\n } catch (error) {\n // Either the connection itself failed, or something bad happened while\n // decoding the response.\n rejectSegmentCacheEntry(segmentCacheEntry, Date.now() + 10 * 1000)\n return null\n }\n}\n\n// TODO: The inlined prefetch flow below is temporary. Eventually, inlining\n// will be the default behavior controlled by a size heuristic rather than a\n// boolean flag. At that point, the per-segment and inlined fetch paths will\n// merge, and these separate functions will be removed.\n//\n// The call site in the scheduler is guarded by\n// process.env.__NEXT_PREFETCH_INLINING, so these functions are\n// dead-code-eliminated from the client bundle when the feature is disabled.\n\nexport async function fetchInlinedSegmentsOnCacheMiss(\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n // When prefetch inlining is enabled, all segment data for a route is bundled\n // into a single /_inlined response instead of individual per-segment\n // requests. This function fetches that response and walks the tree to fill\n // all segment cache entries at once.\n const url = new URL(route.canonicalUrl, location.origin)\n const nextUrl = routeKey.nextUrl\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_PREFETCH_HEADER]: '1',\n [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]: '/' + PAGE_SEGMENT_KEY,\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n addInstantPrefetchHeaderIfLocked(headers)\n\n try {\n const response = await fetchPrefetchResponse(url, headers)\n if (\n !response ||\n !response.ok ||\n response.status === 204 ||\n (response.headers.get(NEXT_DID_POSTPONE_HEADER) !== '2' &&\n !isOutputExportMode) ||\n !response.body\n ) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n\n // See TODO in fetchRouteOnCacheMiss about removing `closed` for\n // buffered prefetch paths.\n const closed = createPromiseWithResolvers<void>()\n\n const { stream: prefetchStream } =\n await createNonTaskyPrefetchResponseStream(response.body)\n closed.resolve()\n const serverData =\n await createFromNextReadableStream<InlinedPrefetchResponse>(\n prefetchStream,\n headers,\n { allowPartialStream: true }\n )\n\n if (\n (response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??\n serverData.tree.segment.buildId) !== getNavigationBuildId()\n ) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n\n const now = Date.now()\n\n // Walk the inlined tree in parallel with the RouteTree and fill\n // segment cache entries.\n fillInlinedSegmentEntries(now, route, tree, serverData.tree, spawnedEntries)\n\n // Fill the head entry.\n const headStaleAt = now + getStaleTimeMs(serverData.head.staleTime)\n const headKey = route.metadata.requestKey\n const ownedHeadEntry = spawnedEntries.get(headKey)\n if (ownedHeadEntry !== undefined) {\n fulfillSegmentCacheEntry(\n ownedHeadEntry,\n serverData.head.rsc,\n headStaleAt,\n serverData.head.isPartial\n )\n } else {\n // The head was already cached. Try to upsert if the entry is empty.\n const existingEntry = readOrCreateSegmentCacheEntry(\n now,\n FetchStrategy.PPR,\n route.metadata\n )\n if (existingEntry.status === EntryStatus.Empty) {\n fulfillSegmentCacheEntry(\n upgradeToPendingSegment(existingEntry, FetchStrategy.PPR),\n serverData.head.rsc,\n headStaleAt,\n serverData.head.isPartial\n )\n }\n }\n\n // Reject any remaining entries that were not fulfilled by the response.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n\n return { value: null, closed: closed.promise }\n } catch (error) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n}\n\nfunction fillInlinedSegmentEntries(\n now: number,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n inlinedNode: InlinedSegmentPrefetch,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): void {\n // Check if the spawned entries map has an entry for this segment's key.\n const segment = inlinedNode.segment\n const staleAt = now + getStaleTimeMs(segment.staleTime)\n const ownedEntry = spawnedEntries.get(tree.requestKey)\n if (ownedEntry !== undefined) {\n // We own this entry. Fulfill it directly.\n fulfillSegmentCacheEntry(\n ownedEntry,\n segment.rsc,\n staleAt,\n segment.isPartial\n )\n } else {\n // Not owned by us — this is extra data from the inlined response for a\n // segment that was already cached. Try to upsert if the entry is empty.\n const existingEntry = readOrCreateSegmentCacheEntry(\n now,\n FetchStrategy.PPR,\n tree\n )\n if (existingEntry.status === EntryStatus.Empty) {\n fulfillSegmentCacheEntry(\n upgradeToPendingSegment(existingEntry, FetchStrategy.PPR),\n segment.rsc,\n staleAt,\n segment.isPartial\n )\n }\n }\n\n // Recurse into children.\n if (tree.slots !== null && inlinedNode.slots !== null) {\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n const childInlinedNode = inlinedNode.slots[parallelRouteKey]\n if (childInlinedNode !== undefined) {\n fillInlinedSegmentEntries(\n now,\n route,\n childTree,\n childInlinedNode,\n spawnedEntries\n )\n }\n }\n }\n}\n\nexport async function fetchSegmentPrefetchesUsingDynamicRequest(\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n dynamicRequestTree: FlightRouterState,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): Promise<PrefetchSubtaskResult<null> | null> {\n const key = task.key\n const url = new URL(route.canonicalUrl, location.origin)\n const nextUrl = key.nextUrl\n\n if (\n spawnedEntries.size === 1 &&\n spawnedEntries.has(route.metadata.requestKey)\n ) {\n // The only thing pending is the head. Instruct the server to\n // skip over everything else.\n dynamicRequestTree = MetadataOnlyRequestTree\n }\n\n const headers: RequestHeaders = {\n [RSC_HEADER]: '1',\n [NEXT_ROUTER_STATE_TREE_HEADER]:\n prepareFlightRouterStateForRequest(dynamicRequestTree),\n }\n if (nextUrl !== null) {\n headers[NEXT_URL] = nextUrl\n }\n switch (fetchStrategy) {\n case FetchStrategy.Full: {\n // We omit the prefetch header from a full prefetch because it's essentially\n // just a navigation request that happens ahead of time — it should include\n // all the same data in the response.\n break\n }\n case FetchStrategy.PPRRuntime: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '2'\n break\n }\n case FetchStrategy.LoadingBoundary: {\n headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'\n break\n }\n default: {\n fetchStrategy satisfies never\n }\n }\n\n try {\n const response = await fetchPrefetchResponse(url, headers)\n if (!response || !response.ok || !response.body) {\n // Server responded with an error, or with a miss. We should still cache\n // the response, but we can try again after 10 seconds.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n\n const renderedSearch = getRenderedSearch(response)\n if (renderedSearch !== route.renderedSearch) {\n // The search params that were used to render the target page are\n // different from the search params in the request URL. This only happens\n // when there's a dynamic rewrite in between the tree prefetch and the\n // data prefetch.\n // TODO: For now, since this is an edge case, we reject the prefetch, but\n // the proper way to handle this is to evict the stale route tree entry\n // then fill the cache with the new response.\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n\n // Track when the network connection closes. Only meaningful for Full\n // (dynamic) prefetches which use incremental streaming. For buffered\n // paths, this is resolved immediately — see TODO in fetchRouteOnCacheMiss.\n const closed = createPromiseWithResolvers<void>()\n\n let fulfilledEntries: Array<FulfilledSegmentCacheEntry> | null = null\n let prefetchStream: ReadableStream<Uint8Array>\n let bufferedResponseSize: number | null = null\n if (fetchStrategy === FetchStrategy.Full) {\n // Full prefetches are dynamic responses stored in the prefetch cache.\n // They don't carry vary params or other cache metadata, so there's no\n // need to buffer them. Use the incremental version to allow data to be\n // processed as it arrives.\n prefetchStream = createIncrementalPrefetchResponseStream(\n response.body,\n closed.resolve,\n function onResponseSizeUpdate(totalBytesReceivedSoFar) {\n // When processing a dynamic response, we don't know how large each\n // individual segment is, so approximate by assigning each segment\n // the average of the total response size.\n if (fulfilledEntries === null) {\n // Haven't received enough data yet to know which segments\n // were included.\n return\n }\n const averageSize = totalBytesReceivedSoFar / fulfilledEntries.length\n for (const entry of fulfilledEntries) {\n setSizeInCacheMap(entry, averageSize)\n }\n }\n )\n } else {\n const { stream, size } = await createNonTaskyPrefetchResponseStream(\n response.body\n )\n closed.resolve()\n prefetchStream = stream\n bufferedResponseSize = size\n }\n\n const [serverData, cacheData] = await Promise.all([\n createFromNextReadableStream<NavigationFlightResponse>(\n prefetchStream,\n headers,\n { allowPartialStream: true }\n ),\n response.cacheData,\n ])\n\n // Read head vary params synchronously. Individual segments carry their\n // own thenables in CacheNodeSeedData.\n const headVaryParamsThenable = serverData.h\n const headVaryParams =\n headVaryParamsThenable !== null\n ? readVaryParams(headVaryParamsThenable)\n : null\n\n const now = Date.now()\n const staleAt = await getStaleAt(now, serverData.s, response)\n // PPRRuntime prefetches are partial when the server marks the response\n // as '~' (Partial). Full/LoadingBoundary prefetches are always complete.\n const isResponsePartial =\n fetchStrategy === FetchStrategy.PPRRuntime &&\n (cacheData?.isResponsePartial ?? false)\n\n // Aside from writing the data into the cache, this function also returns\n // the entries that were fulfilled, so we can streamingly update their sizes\n // in the LRU as more data comes in.\n const buildId =\n response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n const flightDatas = normalizeFlightData(serverData.f)\n if (typeof flightDatas === 'string') {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n const navigationSeed = convertServerPatchToFullTree(\n now,\n dynamicRequestTree,\n flightDatas,\n renderedSearch,\n // Not needed for prefetch responses; pass unknown to use the default.\n UnknownDynamicStaleTime\n )\n fulfilledEntries = writeDynamicRenderResponseIntoCache(\n now,\n fetchStrategy,\n flightDatas,\n buildId,\n isResponsePartial,\n headVaryParams,\n staleAt,\n navigationSeed,\n spawnedEntries\n )\n\n // For buffered responses, update LRU sizes now that we know which\n // entries were fulfilled.\n if (\n bufferedResponseSize !== null &&\n fulfilledEntries !== null &&\n fulfilledEntries.length > 0\n ) {\n const averageSize = bufferedResponseSize / fulfilledEntries.length\n for (const entry of fulfilledEntries) {\n setSizeInCacheMap(entry, averageSize)\n }\n }\n\n // Return a promise that resolves when the network connection closes, so\n // the scheduler can track the number of concurrent network connections.\n return { value: null, closed: closed.promise }\n } catch (error) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)\n return null\n }\n}\n\nfunction writeDynamicTreeResponseIntoCache(\n now: number,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n response: RSCResponse<NavigationFlightResponse>,\n serverData: NavigationFlightResponse,\n entry: PendingRouteCacheEntry,\n couldBeIntercepted: boolean,\n canonicalUrl: string,\n routeIsPPREnabled: boolean,\n headVaryParams: VaryParams | null,\n originalPathname: string,\n nextUrl: string | null\n): void {\n const renderedSearch = getRenderedSearch(response)\n\n const normalizedFlightDataResult = normalizeFlightData(serverData.f)\n if (\n // A string result means navigating to this route will result in an\n // MPA navigation.\n typeof normalizedFlightDataResult === 'string' ||\n normalizedFlightDataResult.length !== 1\n ) {\n rejectRouteCacheEntry(entry, now + 10 * 1000)\n return\n }\n const flightData = normalizedFlightDataResult[0]\n if (!flightData.isRootRender) {\n // Unexpected response format.\n rejectRouteCacheEntry(entry, now + 10 * 1000)\n return\n }\n\n const flightRouterState = flightData.tree\n // If the response was postponed, segments may contain dynamic holes.\n // The head has its own partiality flag (flightDataEntry.isHeadPartial)\n // which is handled separately in writeDynamicRenderResponseIntoCache.\n const isResponsePartial =\n response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'\n\n // Convert the server-sent data into the RouteTree format used by the\n // client cache.\n //\n // During this traversal, we accumulate additional data into this\n // \"accumulator\" object.\n const acc: RouteTreeAccumulator = { metadataVaryPath: null }\n const routeTree = convertRootFlightRouterStateToRouteTree(\n flightRouterState,\n renderedSearch,\n acc\n )\n const metadataVaryPath = acc.metadataVaryPath\n if (metadataVaryPath === null) {\n rejectRouteCacheEntry(entry, now + 10 * 1000)\n return\n }\n\n discoverKnownRoute(\n now,\n originalPathname,\n nextUrl,\n entry,\n routeTree,\n metadataVaryPath,\n couldBeIntercepted,\n canonicalUrl,\n routeIsPPREnabled,\n false // hasDynamicRewrite\n )\n\n // If the server sent segment data as part of the response, we should write\n // it into the cache to prevent a second, redundant prefetch request.\n // TODO: This is a leftover branch from before Client Segment Cache was\n // enabled everywhere. Tree prefetches should never include segment data. We\n // can delete it. Leaving for a subsequent PR.\n const navigationSeed = convertServerPatchToFullTree(\n now,\n flightRouterState,\n normalizedFlightDataResult,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n const buildId =\n response.headers.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ?? serverData.b\n writeDynamicRenderResponseIntoCache(\n now,\n fetchStrategy,\n normalizedFlightDataResult,\n buildId,\n isResponsePartial,\n headVaryParams,\n getStaleAtFromHeader(now, response),\n navigationSeed,\n null\n )\n}\n\nfunction rejectSegmentEntriesIfStillPending(\n entries: Map<SegmentRequestKey, SegmentCacheEntry>,\n staleAt: number\n): Array<FulfilledSegmentCacheEntry> {\n const fulfilledEntries = []\n for (const entry of entries.values()) {\n if (entry.status === EntryStatus.Pending) {\n rejectSegmentCacheEntry(entry, staleAt)\n } else if (entry.status === EntryStatus.Fulfilled) {\n fulfilledEntries.push(entry)\n }\n }\n return fulfilledEntries\n}\n\nexport function writeDynamicRenderResponseIntoCache(\n now: number,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n flightDatas: NormalizedFlightData[],\n buildId: string | undefined,\n isResponsePartial: boolean,\n headVaryParams: VaryParams | null,\n staleAt: number,\n navigationSeed: NavigationSeed,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry> | null\n): Array<FulfilledSegmentCacheEntry> | null {\n if (buildId && buildId !== getNavigationBuildId()) {\n // The server build does not match the client. Treat as a 404. During\n // an actual navigation, the router will trigger an MPA navigation.\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n }\n return null\n }\n\n const routeTree = navigationSeed.routeTree\n const metadataTree =\n navigationSeed.metadataVaryPath !== null\n ? createMetadataRouteTree(navigationSeed.metadataVaryPath)\n : null\n\n for (const flightDataEntry of flightDatas) {\n const seedData = flightDataEntry.seedData\n if (seedData !== null) {\n // The data sent by the server represents only a subtree of the app. We\n // need to find the part of the task tree that matches the response.\n //\n // segmentPath represents the parent path of subtree. It's a repeating\n // pattern of parallel route key and segment:\n //\n // [string, Segment, string, Segment, string, Segment, ...]\n const segmentPath = flightDataEntry.segmentPath\n let tree = routeTree\n for (let i = 0; i < segmentPath.length; i += 2) {\n const parallelRouteKey: string = segmentPath[i]\n if (tree?.slots?.[parallelRouteKey] !== undefined) {\n tree = tree.slots[parallelRouteKey]\n } else {\n if (spawnedEntries !== null) {\n rejectSegmentEntriesIfStillPending(spawnedEntries, now + 10 * 1000)\n }\n return null\n }\n }\n\n writeSeedDataIntoCache(\n now,\n fetchStrategy,\n tree,\n staleAt,\n seedData,\n isResponsePartial,\n spawnedEntries\n )\n }\n\n const head = flightDataEntry.head\n if (head !== null && metadataTree !== null) {\n // When Cache Components is enabled, the server conservatively marks\n // the head as partial during static generation (isPossiblyPartialHead\n // in app-render.tsx), even for fully static pages where the head is\n // actually complete. When the response is non-partial, we override\n // this since the server confirmed no dynamic content exists.\n //\n // Without Cache Components, the server always sends the correct\n // isHeadPartial value, so no override is needed.\n const isHeadPartial =\n !isResponsePartial && process.env.__NEXT_CACHE_COMPONENTS\n ? false\n : flightDataEntry.isHeadPartial\n\n fulfillEntrySpawnedByRuntimePrefetch(\n now,\n fetchStrategy,\n head,\n isHeadPartial,\n staleAt,\n // For head entries, use the head-specific vary params passed as\n // parameter.\n headVaryParams,\n metadataTree,\n spawnedEntries\n )\n }\n }\n // Any entry that's still pending was intentionally not rendered by the\n // server, because it was inside the loading boundary. Mark them as rejected\n // so we know not to fetch them again.\n // TODO: If PPR is enabled on some routes but not others, then it's possible\n // that a different page is able to do a per-segment prefetch of one of the\n // segments we're marking as rejected here. We should mark on the segment\n // somehow that the reason for the rejection is because of a non-PPR prefetch.\n // That way a per-segment prefetch knows to disregard the rejection.\n if (spawnedEntries !== null) {\n const fulfilledEntries = rejectSegmentEntriesIfStillPending(\n spawnedEntries,\n now + 10 * 1000\n )\n return fulfilledEntries\n }\n return null\n}\n\nfunction writeSeedDataIntoCache(\n now: number,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n tree: RouteTree,\n staleAt: number,\n seedData: CacheNodeSeedData,\n isResponsePartial: boolean,\n entriesOwnedByCurrentTask: Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n > | null\n) {\n // This function is used to write the result of a runtime server request\n // (CacheNodeSeedData) into the prefetch cache.\n const rsc = seedData[0]\n const isPartial = rsc === null || isResponsePartial\n const varyParamsThenable = seedData[4]\n // Each segment carries its own vary params thenable in the seed data. The\n // thenable resolves to the set of params the segment accessed during render.\n // A null thenable means tracking was not enabled (not a prerender).\n const varyParams =\n varyParamsThenable !== null ? readVaryParams(varyParamsThenable) : null\n fulfillEntrySpawnedByRuntimePrefetch(\n now,\n fetchStrategy,\n rsc,\n isPartial,\n staleAt,\n varyParams,\n tree,\n entriesOwnedByCurrentTask\n )\n\n // Recursively write the child data into the cache.\n const slots = tree.slots\n if (slots !== null) {\n const seedDataChildren = seedData[1]\n for (const parallelRouteKey in slots) {\n const childTree = slots[parallelRouteKey]\n const childSeedData: CacheNodeSeedData | null | void =\n seedDataChildren[parallelRouteKey]\n if (childSeedData !== null && childSeedData !== undefined) {\n writeSeedDataIntoCache(\n now,\n fetchStrategy,\n childTree,\n staleAt,\n childSeedData,\n isResponsePartial,\n entriesOwnedByCurrentTask\n )\n }\n }\n }\n}\n\nfunction fulfillEntrySpawnedByRuntimePrefetch(\n now: number,\n fetchStrategy:\n | FetchStrategy.LoadingBoundary\n | FetchStrategy.PPR\n | FetchStrategy.PPRRuntime\n | FetchStrategy.Full,\n rsc: React.ReactNode,\n isPartial: boolean,\n staleAt: number,\n segmentVaryParams: Set<string> | null,\n tree: RouteTree,\n entriesOwnedByCurrentTask: Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n > | null\n) {\n // We should only write into cache entries that are owned by us. Or create\n // a new one and write into that. We must never write over an entry that was\n // created by a different task, because that causes data races.\n const ownedEntry =\n entriesOwnedByCurrentTask !== null\n ? entriesOwnedByCurrentTask.get(tree.requestKey)\n : undefined\n if (ownedEntry !== undefined) {\n const fulfilledEntry = fulfillSegmentCacheEntry(\n ownedEntry,\n rsc,\n staleAt,\n isPartial\n )\n // Re-key the entry based on which params the segment actually depends on.\n if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n const fulfilledVaryPath = getFulfilledSegmentVaryPath(\n tree.varyPath,\n segmentVaryParams\n )\n const isRevalidation = false\n setInCacheMap(\n segmentCacheMap,\n fulfilledVaryPath,\n fulfilledEntry,\n isRevalidation\n )\n }\n } else {\n // There's no matching entry. Attempt to create a new one.\n const possiblyNewEntry = readOrCreateSegmentCacheEntry(\n now,\n fetchStrategy,\n tree\n )\n if (possiblyNewEntry.status === EntryStatus.Empty) {\n // Confirmed this is a new entry. We can fulfill it.\n const newEntry = possiblyNewEntry\n const fulfilledEntry = fulfillSegmentCacheEntry(\n upgradeToPendingSegment(newEntry, fetchStrategy),\n rsc,\n staleAt,\n isPartial\n )\n // Re-key the entry based on which params the segment actually depends on.\n if (process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null) {\n const fulfilledVaryPath = getFulfilledSegmentVaryPath(\n tree.varyPath,\n segmentVaryParams\n )\n const isRevalidation = false\n setInCacheMap(\n segmentCacheMap,\n fulfilledVaryPath,\n fulfilledEntry,\n isRevalidation\n )\n }\n } else {\n // There was already an entry in the cache. But we may be able to\n // replace it with the new one from the server.\n const newEntry = fulfillSegmentCacheEntry(\n upgradeToPendingSegment(\n createDetachedSegmentCacheEntry(now),\n fetchStrategy\n ),\n rsc,\n staleAt,\n isPartial\n )\n // Use the fulfilled vary path if available, otherwise fall back to\n // the request vary path.\n const varyPath =\n process.env.__NEXT_VARY_PARAMS && segmentVaryParams !== null\n ? getFulfilledSegmentVaryPath(tree.varyPath, segmentVaryParams)\n : getSegmentVaryPathForRequest(fetchStrategy, tree)\n upsertSegmentEntry(now, varyPath, newEntry)\n }\n }\n}\n\nasync function fetchPrefetchResponse<T>(\n url: URL,\n headers: RequestHeaders\n): Promise<RSCResponse<T> | null> {\n const fetchPriority = 'low'\n // When issuing a prefetch request, don't immediately decode the response; we\n // use the lower level `createFromResponse` API instead because we need to do\n // some extra processing of the response stream. See\n // `createNonTaskyPrefetchResponseStream` for more details.\n const shouldImmediatelyDecode = false\n const response = await createFetch<T>(\n url,\n headers,\n fetchPriority,\n shouldImmediatelyDecode\n )\n if (!response.ok) {\n return null\n }\n\n // Check the content type\n if (isOutputExportMode) {\n // In output: \"export\" mode, we relaxed about the content type, since it's\n // not Next.js that's serving the response. If the status is OK, assume the\n // response is valid. If it's not a valid response, the Flight client won't\n // be able to decode it, and we'll treat it as a miss.\n } else {\n const contentType = response.headers.get('content-type')\n const isFlightResponse =\n contentType && contentType.startsWith(RSC_CONTENT_TYPE_HEADER)\n if (!isFlightResponse) {\n return null\n }\n }\n return response\n}\n\nasync function createNonTaskyPrefetchResponseStream(\n body: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; size: number }> {\n // Buffer the entire response before passing it to the Flight client. This\n // ensures that when Flight processes the stream, all model data is available\n // synchronously. This is important for readVaryParams, which synchronously\n // checks the thenable status — if data arrived in multiple network chunks,\n // the thenables might not yet be fulfilled.\n //\n // TODO: There are too many intermediate stream transformations in the\n // prefetch response pipeline (e.g. stripIsPartialByte, this function).\n // These could all be consolidated into a single transformation. Refactor\n // once the cached navigations experiment lands.\n //\n // Read the entire response from the network.\n const reader = body.getReader()\n const chunks: Uint8Array[] = []\n let size = 0\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n chunks.push(value)\n size += value.byteLength\n }\n // Concatenate into a single chunk so that Flight's processBinaryChunk\n // processes all rows synchronously in one call. Multiple chunks would not\n // be sufficient: even though reader.read() resolves as a microtask for\n // already-enqueued data, the `await` continuation from\n // createFromReadableStream can interleave between chunks. If the root\n // model row isn't the first row (e.g. outlined values come first), the\n // PromiseResolveThenableJob from `await` can cause the root to initialize\n // eagerly, scheduling the continuation before remaining chunks (including\n // promise value rows) are processed. A single chunk avoids this.\n let buffer: Uint8Array\n if (chunks.length === 1) {\n buffer = chunks[0]\n } else if (chunks.length > 1) {\n buffer = new Uint8Array(size)\n let offset = 0\n for (const chunk of chunks) {\n buffer.set(chunk, offset)\n offset += chunk.byteLength\n }\n } else {\n buffer = new Uint8Array(0)\n }\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(buffer)\n controller.close()\n },\n })\n return { stream, size }\n}\n\n/**\n * Creates a streaming (non-buffered) prefetch response stream for dynamic/Full\n * prefetches. These are essentially dynamic responses that get stored in the\n * prefetch cache — they don't carry vary params or other cache metadata that\n * requires synchronous thenable resolution, so there's no need to buffer them.\n * They should continue to stream so consumers can process data as it arrives.\n */\nfunction createIncrementalPrefetchResponseStream(\n originalFlightStream: ReadableStream<Uint8Array>,\n onStreamClose: () => void,\n onResponseSizeUpdate: (size: number) => void\n): ReadableStream<Uint8Array> {\n // While processing the original stream, we incrementally update the size\n // of the cache entry in the LRU.\n let totalByteLength = 0\n const reader = originalFlightStream.getReader()\n return new ReadableStream({\n async pull(controller) {\n while (true) {\n const { done, value } = await reader.read()\n if (!done) {\n // Pass to the target stream and keep consuming the Flight response\n // from the server.\n controller.enqueue(value)\n\n // Incrementally update the size of the cache entry in the LRU.\n totalByteLength += value.byteLength\n onResponseSizeUpdate(totalByteLength)\n continue\n }\n controller.close()\n onStreamClose()\n return\n }\n },\n })\n}\n\nfunction addSegmentPathToUrlInOutputExportMode(\n url: URL,\n segmentPath: SegmentRequestKey\n): URL {\n if (isOutputExportMode) {\n // In output: \"export\" mode, we cannot use a header to encode the segment\n // path. Instead, we append it to the end of the pathname.\n const staticUrl = new URL(url)\n const routeDir = staticUrl.pathname.endsWith('/')\n ? staticUrl.pathname.slice(0, -1)\n : staticUrl.pathname\n const staticExportFilename =\n convertSegmentPathToStaticExportFilename(segmentPath)\n staticUrl.pathname = `${routeDir}/${staticExportFilename}`\n return staticUrl\n }\n return url\n}\n\n/**\n * Checks whether the new fetch strategy is likely to provide more content than the old one.\n *\n * Generally, when an app uses dynamic data, a \"more specific\" fetch strategy is expected to provide more content:\n * - `LoadingBoundary` only provides static layouts\n * - `PPR` can provide shells for each segment (even for segments that use dynamic data)\n * - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies\n * - `Full` includes all the content, even if it uses dynamic data\n *\n * However, it's possible that a more specific fetch strategy *won't* give us more content if:\n * - a segment is fully static\n * (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)\n * - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`\n * (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)\n * Because of this, when comparing two segments, we should also check if the existing segment is partial.\n * If it's not partial, then there's no need to prefetch it again, even using a \"more specific\" strategy.\n * There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.\n *\n * Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,\n * because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.\n */\nexport function canNewFetchStrategyProvideMoreContent(\n currentStrategy: FetchStrategy,\n newStrategy: FetchStrategy\n): boolean {\n return currentStrategy < newStrategy\n}\n\n/**\n * Adds the instant prefetch header if the navigation lock is active.\n * Uses a lazy require to ensure dead code elimination.\n */\nfunction addInstantPrefetchHeaderIfLocked(\n headers: Record<string, string>\n): void {\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n const { isNavigationLocked } =\n require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')\n if (isNavigationLocked()) {\n headers[NEXT_INSTANT_PREFETCH_HEADER] = '1'\n }\n }\n}\n\nfunction getStaleAtFromHeader(\n now: number,\n response: RSCResponse<unknown>\n): number {\n const staleTimeSeconds = parseInt(\n response.headers.get(NEXT_ROUTER_STALE_TIME_HEADER) ?? '',\n 10\n )\n\n const staleTimeMs = !isNaN(staleTimeSeconds)\n ? getStaleTimeMs(staleTimeSeconds)\n : STATIC_STALETIME_MS\n\n return now + staleTimeMs\n}\n\n/**\n * Reads the stale time from an async iterable or a response header and\n * returns a staleAt timestamp.\n *\n * TODO: Buffer the response and then read the iterable values\n * synchronously, similar to readVaryParams. This would avoid the need to\n * make this async, and we could also use it in\n * writeDynamicTreeResponseIntoCache. This will also be needed when React\n * starts leaving async iterables hanging when the outer RSC stream is\n * aborted e.g. due to sync I/O (with unstable_allowPartialStream).\n */\nexport async function getStaleAt(\n now: number,\n staleTimeIterable: AsyncIterable<number> | undefined,\n response?: RSCResponse<unknown>\n): Promise<number> {\n if (staleTimeIterable !== undefined) {\n // Iterate the async iterable and take the last yielded value. The server\n // yields updated staleTime values during the render; the last one is the\n // final staleTime.\n let staleTimeSeconds: number | undefined\n for await (const value of staleTimeIterable) {\n staleTimeSeconds = value\n }\n\n if (staleTimeSeconds !== undefined) {\n const staleTimeMs = isNaN(staleTimeSeconds)\n ? STATIC_STALETIME_MS\n : getStaleTimeMs(staleTimeSeconds)\n\n return now + staleTimeMs\n }\n }\n\n if (response !== undefined) {\n return getStaleAtFromHeader(now, response)\n }\n\n return now + STATIC_STALETIME_MS\n}\n\n/**\n * Writes the static stage of a navigation response into the segment cache.\n * When `isResponsePartial` is false, segments are written as non-partial with\n * `FetchStrategy.Full` so no dynamic follow-up is needed. Default segments\n * are skipped (by `writeSeedDataIntoCache`) to avoid caching fallback content\n * that would block refreshes from overwriting with dynamic data.\n */\nexport function writeStaticStageResponseIntoCache(\n now: number,\n flightData: FlightData,\n buildId: string | undefined,\n headVaryParamsThenable: VaryParamsThenable | null,\n staleAt: number,\n baseTree: FlightRouterState,\n renderedSearch: string,\n isResponsePartial: boolean\n): void {\n const fetchStrategy = isResponsePartial\n ? FetchStrategy.PPR\n : FetchStrategy.Full\n\n const headVaryParams =\n headVaryParamsThenable !== null\n ? readVaryParams(headVaryParamsThenable)\n : null\n\n const flightDatas = normalizeFlightData(flightData)\n if (typeof flightDatas === 'string') {\n return\n }\n const navigationSeed = convertServerPatchToFullTree(\n now,\n baseTree,\n flightDatas,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n writeDynamicRenderResponseIntoCache(\n now,\n fetchStrategy,\n flightDatas,\n buildId,\n isResponsePartial,\n headVaryParams,\n staleAt,\n navigationSeed,\n null // spawnedEntries — no pre-created entries; will create or upsert\n )\n}\n\n/**\n * Decodes an embedded runtime prefetch Flight stream, normalizes the flight\n * data, and derives a `NavigationSeed` from the base tree.\n *\n * Returns `null` if the response triggers an MPA navigation.\n */\nexport async function processRuntimePrefetchStream(\n now: number,\n runtimePrefetchStream: ReadableStream<Uint8Array>,\n baseTree: FlightRouterState,\n renderedSearch: string\n): Promise<{\n flightDatas: NormalizedFlightData[]\n navigationSeed: NavigationSeed\n buildId: string | undefined\n isResponsePartial: boolean\n headVaryParams: VaryParams | null\n staleAt: number\n} | null> {\n const { stream, isPartial } = await stripIsPartialByte(runtimePrefetchStream)\n\n const serverData =\n await createFromNextReadableStream<NavigationFlightResponse>(\n stream,\n undefined,\n { allowPartialStream: true }\n )\n\n const headVaryParamsThenable = serverData.h\n const headVaryParams =\n headVaryParamsThenable !== null\n ? readVaryParams(headVaryParamsThenable)\n : null\n\n const staleAt = await getStaleAt(now, serverData.s)\n\n const flightDatas = normalizeFlightData(serverData.f)\n if (typeof flightDatas === 'string') {\n return null\n }\n const navigationSeed = convertServerPatchToFullTree(\n now,\n baseTree,\n flightDatas,\n renderedSearch,\n UnknownDynamicStaleTime\n )\n\n return {\n flightDatas,\n navigationSeed,\n buildId: serverData.b,\n isResponsePartial: isPartial,\n headVaryParams,\n staleAt,\n }\n}\n\n/**\n * Strips the leading isPartial byte from an RSC response stream.\n *\n * The server prepends a single byte: '~' (0x7e) for partial, '#' (0x23) for\n * complete. These bytes cannot appear as the first byte of a valid RSC Flight\n * response (Flight rows start with a hex digit or ':').\n *\n * If the first byte is not a recognized marker, the stream is returned intact\n * and `isPartial` is determined by the cachedNavigations experimental flag.\n */\nexport async function stripIsPartialByte(\n stream: ReadableStream<Uint8Array>\n): Promise<{ stream: ReadableStream<Uint8Array>; isPartial: boolean }> {\n // When there is no recognized marker byte, the fallback depends on whether\n // Cached Navigations is enabled. When enabled, dynamic navigation responses\n // don't have a marker but may contain dynamic holes, so they are treated as\n // partial. When disabled, unmarked responses are treated as non-partial.\n const defaultIsPartial = !!process.env.__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS\n\n const reader = stream.getReader()\n const { done, value } = await reader.read()\n\n if (done || !value || value.byteLength === 0) {\n return {\n stream: new ReadableStream({ start: (c) => c.close() }),\n isPartial: defaultIsPartial,\n }\n }\n\n const firstByte = value[0]\n const hasMarker = firstByte === 0x23 || firstByte === 0x7e\n const isPartial = hasMarker ? firstByte === 0x7e : defaultIsPartial\n\n const remainder = hasMarker\n ? value.byteLength > 1\n ? value.subarray(1)\n : null\n : value\n\n return {\n isPartial,\n stream: new ReadableStream<Uint8Array>({\n start(controller) {\n if (remainder) {\n controller.enqueue(remainder)\n }\n },\n async pull(controller) {\n const result = await reader.read()\n if (result.done) {\n controller.close()\n } else {\n controller.enqueue(result.value)\n }\n },\n }),\n }\n}\n","import type {\n FlightRouterState,\n Segment as FlightRouterStateSegment,\n Segment,\n} from '../../../shared/lib/app-router-types'\nimport { PrefetchHint } from '../../../shared/lib/app-router-types'\nimport { matchSegment } from '../match-segments'\nimport {\n readOrCreateRouteCacheEntry,\n readOrCreateSegmentCacheEntry,\n fetchRouteOnCacheMiss,\n fetchSegmentOnCacheMiss,\n fetchInlinedSegmentsOnCacheMiss,\n EntryStatus,\n type FulfilledRouteCacheEntry,\n type RouteCacheEntry,\n type SegmentCacheEntry,\n type RouteTree,\n fetchSegmentPrefetchesUsingDynamicRequest,\n type PendingSegmentCacheEntry,\n convertRouteTreeToFlightRouterState,\n readOrCreateRevalidatingSegmentEntry,\n upgradeToPendingSegment,\n overwriteRevalidatingSegmentCacheEntry,\n canNewFetchStrategyProvideMoreContent,\n attemptToFulfillDynamicSegmentFromBFCache,\n attemptToUpgradeSegmentFromBFCache,\n} from './cache'\nimport type { RouteCacheKey } from './cache-key'\nimport { createCacheKey } from './cache-key'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n PrefetchPriority,\n} from './types'\nimport {\n getCurrentRouteCacheVersion,\n getCurrentSegmentCacheVersion,\n} from './cache'\nimport {\n addSearchParamsIfPageSegment,\n PAGE_SEGMENT_KEY,\n} from '../../../shared/lib/segment'\nimport type { SegmentRequestKey } from '../../../shared/lib/segment-cache/segment-value-encoding'\nimport { cleanup } from './lru'\n\nconst scheduleMicrotask =\n typeof queueMicrotask === 'function'\n ? queueMicrotask\n : (fn: () => unknown) =>\n Promise.resolve()\n .then(fn)\n .catch((error) =>\n setTimeout(() => {\n throw error\n })\n )\n\nexport type PrefetchTask = {\n key: RouteCacheKey\n\n /**\n * The FlightRouterState at the time the task was initiated. This is needed\n * when falling back to the non-PPR behavior, which only prefetches up to\n * the first loading boundary.\n */\n treeAtTimeOfPrefetch: FlightRouterState\n\n /**\n * The cache versions at the time the task was initiated. Used to determine\n * if the cache was invalidated since the task was initiated. Route and\n * segment caches have separate versions so they can be invalidated\n * independently.\n */\n routeCacheVersion: number\n segmentCacheVersion: number\n\n /**\n * Whether to prefetch dynamic data, in addition to static data. This is\n * used by `<Link prefetch={true}>`.\n *\n * Note that a task with `FetchStrategy.PPR` might need to use\n * `FetchStrategy.LoadingBoundary` instead if we find out that a route\n * does not support PPR after doing the initial route prefetch.\n */\n fetchStrategy: PrefetchTaskFetchStrategy\n\n /**\n * sortId is an incrementing counter\n *\n * Newer prefetches are prioritized over older ones, so that as new links\n * enter the viewport, they are not starved by older links that are no\n * longer relevant. In the future, we can add additional prioritization\n * heuristics, like removing prefetches once a link leaves the viewport.\n *\n * The sortId is assigned when the prefetch is initiated, and reassigned if\n * the same task is prefetched again (effectively bumping it to the top of\n * the queue).\n *\n * TODO: We can add additional fields here to indicate what kind of prefetch\n * it is. For example, was it initiated by a link? Or was it an imperative\n * call? If it was initiated by a link, we can remove it from the queue when\n * the link leaves the viewport, but if it was an imperative call, then we\n * should keep it in the queue until it's fulfilled.\n *\n * We can also add priority levels. For example, hovering over a link could\n * increase the priority of its prefetch.\n */\n sortId: number\n\n /**\n * The priority of the task. Like sortId, this affects the task's position in\n * the queue, so it must never be updated without resifting the heap.\n */\n priority: PrefetchPriority\n\n /**\n * The phase of the task. Tasks are split into multiple phases so that their\n * priority can be adjusted based on what kind of work they're doing.\n * Concretely, prefetching the route tree is higher priority than prefetching\n * segment data.\n */\n phase: PrefetchPhase\n\n /**\n * These fields are temporary state for tracking the currently running task.\n * They are reset after each iteration of the task queue.\n */\n hasBackgroundWork: boolean\n spawnedRuntimePrefetches: Set<SegmentRequestKey> | null\n\n /**\n * True if the prefetch was cancelled.\n */\n isCanceled: boolean\n\n /**\n * The callback passed to `router.prefetch`, if given.\n */\n onInvalidate: null | (() => void)\n\n /**\n * The index of the task in the heap's backing array. Used to efficiently\n * change the priority of a task by re-sifting it, which requires knowing\n * where it is in the array. This is only used internally by the heap\n * algorithm. The naive alternative is indexOf every time a task is queued,\n * which has O(n) complexity.\n *\n * We also use this field to check whether a task is currently in the queue.\n */\n _heapIndex: number\n\n /**\n * Called when the prefetch task finishes (either completed or canceled).\n * Used by the Instant Navigation Testing API to await prefetch completion.\n * Not exposed in production builds by default.\n *\n * Note: \"Complete\" means the scheduler has no more work to do for this task\n * — all network requests have been spawned. It does not mean all data has\n * been retrieved; responses may still be in flight.\n */\n _onComplete?: () => void\n}\n\nconst enum PrefetchTaskExitStatus {\n /**\n * The task yielded because there are too many requests in progress.\n */\n InProgress,\n\n /**\n * The task is blocked. It needs more data before it can proceed.\n *\n * Currently the only reason this happens is we're still waiting to receive a\n * route tree from the server, because we can't start prefetching the segments\n * until we know what to prefetch.\n */\n Blocked,\n\n /**\n * There's nothing left to prefetch.\n */\n Done,\n}\n\n/**\n * Prefetch tasks are processed in two phases: first the route tree is fetched,\n * then the segments. We use this to priortize tasks that have not yet fetched\n * the route tree.\n */\nconst enum PrefetchPhase {\n RouteTree = 1,\n Segments = 0,\n}\n\nexport type PrefetchSubtaskResult<T> = {\n /**\n * A promise that resolves when the network connection is closed.\n */\n closed: Promise<void>\n value: T\n}\n\nconst taskHeap: Array<PrefetchTask> = []\n\nlet inProgressRequests = 0\n\nlet sortIdCounter = 0\nlet didScheduleMicrotask = false\n\n// The most recently hovered (or touched, etc) link, i.e. the most recent task\n// scheduled at Intent priority. There's only ever a single task at Intent\n// priority at a time. We reserve special network bandwidth for this task only.\nlet mostRecentlyHoveredLink: PrefetchTask | null = null\n\n// CDN cache propagation delay after revalidation (in milliseconds)\nconst REVALIDATION_COOLDOWN_MS = 300\n\n// Timeout handle for the revalidation cooldown. When non-null, prefetch\n// requests are blocked to allow CDN cache propagation.\nlet revalidationCooldownTimeoutHandle: ReturnType<typeof setTimeout> | null =\n null\n\n/**\n * Called by the cache when revalidation occurs. Starts a cooldown period\n * during which prefetch requests are blocked to allow CDN cache propagation.\n */\nexport function startRevalidationCooldown(): void {\n // Clear any existing timeout in case multiple revalidations happen\n // in quick succession.\n if (revalidationCooldownTimeoutHandle !== null) {\n clearTimeout(revalidationCooldownTimeoutHandle)\n }\n\n // Schedule the cooldown to expire after the delay.\n revalidationCooldownTimeoutHandle = setTimeout(() => {\n revalidationCooldownTimeoutHandle = null\n // Retry the prefetch queue now that the cooldown has expired.\n pingPrefetchScheduler()\n }, REVALIDATION_COOLDOWN_MS)\n}\n\nexport type IncludeDynamicData = null | 'full' | 'dynamic'\n\n/**\n * Initiates a prefetch task for the given URL. If a prefetch for the same URL\n * is already in progress, this will bump it to the top of the queue.\n *\n * This is not a user-facing function. By the time this is called, the href is\n * expected to be validated and normalized.\n *\n * @param key The RouteCacheKey to prefetch.\n * @param treeAtTimeOfPrefetch The app's current FlightRouterState\n * @param fetchStrategy Whether to prefetch dynamic data, in addition to\n * static data. This is used by `<Link prefetch={true}>`.\n * @param _onComplete Called when the prefetch task finishes. Testing API only.\n */\nexport function schedulePrefetchTask(\n key: RouteCacheKey,\n treeAtTimeOfPrefetch: FlightRouterState,\n fetchStrategy: PrefetchTaskFetchStrategy,\n priority: PrefetchPriority,\n onInvalidate: null | (() => void),\n _onComplete?: () => void\n): PrefetchTask {\n // Spawn a new prefetch task\n const task: PrefetchTask = {\n key,\n treeAtTimeOfPrefetch,\n routeCacheVersion: getCurrentRouteCacheVersion(),\n segmentCacheVersion: getCurrentSegmentCacheVersion(),\n priority,\n phase: PrefetchPhase.RouteTree,\n hasBackgroundWork: false,\n spawnedRuntimePrefetches: null,\n fetchStrategy,\n sortId: sortIdCounter++,\n isCanceled: false,\n onInvalidate,\n _heapIndex: -1,\n }\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n task._onComplete = _onComplete\n }\n\n trackMostRecentlyHoveredLink(task)\n\n heapPush(taskHeap, task)\n\n // Schedule an async task to process the queue.\n //\n // The main reason we process the queue in an async task is for batching.\n // It's common for a single JS task/event to trigger multiple prefetches.\n // By deferring to a microtask, we only process the queue once per JS task.\n // If they have different priorities, it also ensures they are processed in\n // the optimal order.\n pingPrefetchScheduler()\n\n return task\n}\n\nexport function cancelPrefetchTask(task: PrefetchTask): void {\n // Remove the prefetch task from the queue. If the task already completed,\n // then this is a no-op.\n //\n // We must also explicitly mark the task as canceled so that a blocked task\n // does not get added back to the queue when it's pinged by the network.\n task.isCanceled = true\n heapDelete(taskHeap, task)\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n // Call completion callback. In practice this shouldn't be reached for\n // test-initiated prefetches since cancellation is only used by the Link\n // component when elements scroll out of viewport.\n const onComplete = task._onComplete\n task._onComplete = undefined\n onComplete?.()\n }\n}\n\nexport function reschedulePrefetchTask(\n task: PrefetchTask,\n treeAtTimeOfPrefetch: FlightRouterState,\n fetchStrategy: PrefetchTaskFetchStrategy,\n priority: PrefetchPriority\n): void {\n // Bump the prefetch task to the top of the queue, as if it were a fresh\n // task. This is essentially the same as canceling the task and scheduling\n // a new one, except it reuses the original object.\n //\n // The primary use case is to increase the priority of a Link-initated\n // prefetch on hover.\n //\n // Note: _onComplete is not reset here because it's preserved on the same\n // task object. When the rescheduled task completes, the original callback\n // will still be invoked.\n\n // Un-cancel the task, in case it was previously canceled.\n task.isCanceled = false\n task.phase = PrefetchPhase.RouteTree\n\n // Assign a new sort ID to move it ahead of all other tasks at the same\n // priority level. (Higher sort IDs are processed first.)\n task.sortId = sortIdCounter++\n task.priority =\n // If this task is the most recently hovered link, maintain its\n // Intent priority, even if the rescheduled priority is lower.\n task === mostRecentlyHoveredLink ? PrefetchPriority.Intent : priority\n\n task.treeAtTimeOfPrefetch = treeAtTimeOfPrefetch\n task.fetchStrategy = fetchStrategy\n\n trackMostRecentlyHoveredLink(task)\n\n if (task._heapIndex !== -1) {\n // The task is already in the queue.\n heapResift(taskHeap, task)\n } else {\n heapPush(taskHeap, task)\n }\n pingPrefetchScheduler()\n}\n\nexport function isPrefetchTaskDirty(\n task: PrefetchTask,\n nextUrl: string | null,\n tree: FlightRouterState\n): boolean {\n // This is used to quickly bail out of a prefetch task if the result is\n // guaranteed to not have changed since the task was initiated. This is\n // strictly an optimization — theoretically, if it always returned true, no\n // behavior should change because a full prefetch task will effectively\n // perform the same checks.\n return (\n task.routeCacheVersion !== getCurrentRouteCacheVersion() ||\n task.segmentCacheVersion !== getCurrentSegmentCacheVersion() ||\n task.treeAtTimeOfPrefetch !== tree ||\n task.key.nextUrl !== nextUrl\n )\n}\n\nfunction trackMostRecentlyHoveredLink(task: PrefetchTask) {\n // Track the mostly recently hovered link, i.e. the most recently scheduled\n // task at Intent priority. There must only be one such task at a time.\n if (\n task.priority === PrefetchPriority.Intent &&\n task !== mostRecentlyHoveredLink\n ) {\n if (mostRecentlyHoveredLink !== null) {\n // Bump the previously hovered link's priority down to Default.\n if (mostRecentlyHoveredLink.priority !== PrefetchPriority.Background) {\n mostRecentlyHoveredLink.priority = PrefetchPriority.Default\n heapResift(taskHeap, mostRecentlyHoveredLink)\n }\n }\n mostRecentlyHoveredLink = task\n }\n}\n\nexport function pingPrefetchScheduler() {\n if (didScheduleMicrotask) {\n // Already scheduled a task to process the queue\n return\n }\n didScheduleMicrotask = true\n scheduleMicrotask(processQueueInMicrotask)\n}\n\n/**\n * Checks if we've exceeded the maximum number of concurrent prefetch requests,\n * to avoid saturating the browser's internal network queue. This is a\n * cooperative limit — prefetch tasks should check this before issuing\n * new requests.\n *\n * Also checks if we're within the revalidation cooldown window, during which\n * prefetch requests are delayed to allow CDN cache propagation.\n */\nfunction hasNetworkBandwidth(task: PrefetchTask): boolean {\n // Check if we're within the revalidation cooldown window\n if (revalidationCooldownTimeoutHandle !== null) {\n // We're within the cooldown window. Return false to prevent prefetching.\n // When the cooldown expires, the timeout will call ensureWorkIsScheduled()\n // to retry the queue.\n return false\n }\n\n // TODO: Also check if there's an in-progress navigation. We should never\n // add prefetch requests to the network queue if an actual navigation is\n // taking place, to ensure there's sufficient bandwidth for render-blocking\n // data and resources.\n\n // TODO: Consider reserving some amount of bandwidth for static prefetches.\n\n if (task.priority === PrefetchPriority.Intent) {\n // The most recently hovered link is allowed to exceed the default limit.\n //\n // The goal is to always have enough bandwidth to start a new prefetch\n // request when hovering over a link.\n //\n // However, because we don't abort in-progress requests, it's still possible\n // we'll run out of bandwidth. When links are hovered in quick succession,\n // there could be multiple hover requests running simultaneously.\n return inProgressRequests < 12\n }\n\n // The default limit is lower than the limit for a hovered link.\n return inProgressRequests < 4\n}\n\nfunction spawnPrefetchSubtask<T>(\n prefetchSubtask: Promise<PrefetchSubtaskResult<T> | null>\n): Promise<T | null> {\n // When the scheduler spawns an async task, we don't await its result.\n // Instead, the async task writes its result directly into the cache, then\n // pings the scheduler to continue.\n //\n // We process server responses streamingly, so the prefetch subtask will\n // likely resolve before we're finished receiving all the data. The subtask\n // result includes a promise that resolves once the network connection is\n // closed. The scheduler uses this to control network bandwidth by tracking\n // and limiting the number of concurrent requests.\n inProgressRequests++\n return prefetchSubtask.then((result) => {\n if (result === null) {\n // The prefetch task errored before it could start processing the\n // network stream. Assume the connection is closed.\n onPrefetchConnectionClosed()\n return null\n }\n // Wait for the connection to close before freeing up more bandwidth.\n result.closed.then(onPrefetchConnectionClosed)\n return result.value\n })\n}\n\nfunction onPrefetchConnectionClosed(): void {\n inProgressRequests--\n\n // Notify the scheduler that we have more bandwidth, and can continue\n // processing tasks.\n pingPrefetchScheduler()\n}\n\n/**\n * Notify the scheduler that we've received new data for an in-progress\n * prefetch. The corresponding task will be added back to the queue (unless the\n * task has been canceled in the meantime).\n */\nexport function pingPrefetchTask(task: PrefetchTask) {\n // \"Ping\" a prefetch that's already in progress to notify it of new data.\n if (\n // Check if prefetch was canceled.\n task.isCanceled ||\n // Check if prefetch is already queued.\n task._heapIndex !== -1\n ) {\n return\n }\n // Add the task back to the queue.\n heapPush(taskHeap, task)\n pingPrefetchScheduler()\n}\n\nfunction processQueueInMicrotask() {\n didScheduleMicrotask = false\n\n // We aim to minimize how often we read the current time. Since nearly all\n // functions in the prefetch scheduler are synchronous, we can read the time\n // once and pass it as an argument wherever it's needed.\n const now = Date.now()\n\n // Process the task queue until we run out of network bandwidth.\n let task = heapPeek(taskHeap)\n while (task !== null && hasNetworkBandwidth(task)) {\n task.routeCacheVersion = getCurrentRouteCacheVersion()\n task.segmentCacheVersion = getCurrentSegmentCacheVersion()\n\n const exitStatus = pingRoute(now, task)\n\n // These fields are only valid for a single attempt. Reset them after each\n // iteration of the task queue.\n const hasBackgroundWork = task.hasBackgroundWork\n task.hasBackgroundWork = false\n task.spawnedRuntimePrefetches = null\n\n switch (exitStatus) {\n case PrefetchTaskExitStatus.InProgress:\n // The task yielded because there are too many requests in progress.\n // Stop processing tasks until we have more bandwidth.\n return\n case PrefetchTaskExitStatus.Blocked:\n // The task is blocked. It needs more data before it can proceed.\n // Keep the task out of the queue until the server responds.\n heapPop(taskHeap)\n // Continue to the next task\n task = heapPeek(taskHeap)\n continue\n case PrefetchTaskExitStatus.Done:\n if (task.phase === PrefetchPhase.RouteTree) {\n // Finished prefetching the route tree. Proceed to prefetching\n // the segments.\n task.phase = PrefetchPhase.Segments\n heapResift(taskHeap, task)\n } else if (hasBackgroundWork) {\n // The task spawned additional background work. Reschedule the task\n // at background priority.\n task.priority = PrefetchPriority.Background\n heapResift(taskHeap, task)\n } else {\n // The prefetch is complete. Continue to the next task.\n if (process.env.__NEXT_EXPOSE_TESTING_API) {\n // Notify the Instant Navigation Testing API that the prefetch has\n // completed, so it can proceed with navigation.\n const onComplete = task._onComplete\n task._onComplete = undefined\n onComplete?.()\n }\n heapPop(taskHeap)\n }\n task = heapPeek(taskHeap)\n continue\n default:\n exitStatus satisfies never\n }\n }\n\n // Run LRU cleanup only when the scheduler is fully idle: no queued tasks and\n // no in-progress requests. At that point, all active prefetch tasks have\n // finished reading from the cache (moving recently used entries to the front\n // of the list), so only genuinely stale data gets evicted.\n if (task === null && inProgressRequests === 0) {\n cleanup()\n }\n}\n\n/**\n * Check this during a prefetch task to determine if background work can be\n * performed. If so, it evaluates to `true`. Otherwise, it returns `false`,\n * while also scheduling a background task to run later. Usage:\n *\n * @example\n * if (background(task)) {\n * // Perform background-pri work\n * }\n */\nfunction background(task: PrefetchTask): boolean {\n if (task.priority === PrefetchPriority.Background) {\n return true\n }\n task.hasBackgroundWork = true\n return false\n}\n\nfunction pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus {\n const key = task.key\n const route = readOrCreateRouteCacheEntry(now, task, key)\n const exitStatus = pingRootRouteTree(now, task, route)\n\n if (exitStatus !== PrefetchTaskExitStatus.InProgress && key.search !== '') {\n // If the URL has a non-empty search string, also prefetch the pathname\n // without the search string. We use the searchless route tree as a base for\n // optimistic routing; see requestOptimisticRouteCacheEntry for details.\n //\n // Note that we don't need to prefetch any of the segment data. Just the\n // route tree.\n //\n // TODO: This is a temporary solution; the plan is to replace this by adding\n // a wildcard lookup method to the TupleMap implementation. This is\n // non-trivial to implement because it needs to account for things like\n // fallback route entries, hence this temporary workaround.\n const url = new URL(key.pathname, location.origin)\n const keyWithoutSearch = createCacheKey(url.href, key.nextUrl)\n const routeWithoutSearch = readOrCreateRouteCacheEntry(\n now,\n task,\n keyWithoutSearch\n )\n switch (routeWithoutSearch.status) {\n case EntryStatus.Empty: {\n if (background(task)) {\n routeWithoutSearch.status = EntryStatus.Pending\n spawnPrefetchSubtask(\n fetchRouteOnCacheMiss(routeWithoutSearch, keyWithoutSearch)\n )\n }\n break\n }\n case EntryStatus.Pending:\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected: {\n // Either the route tree is already cached, or there's already a\n // request in progress. Since we don't need to fetch any segment data\n // for this route, there's nothing left to do.\n break\n }\n default:\n routeWithoutSearch satisfies never\n }\n }\n\n return exitStatus\n}\n\nfunction pingRootRouteTree(\n now: number,\n task: PrefetchTask,\n route: RouteCacheEntry\n): PrefetchTaskExitStatus {\n switch (route.status) {\n case EntryStatus.Empty: {\n // Route is not yet cached, and there's no request already in progress.\n // Spawn a task to request the route, load it into the cache, and ping\n // the task to continue.\n\n // TODO: There are multiple strategies in the <Link> API for prefetching\n // a route. Currently we've only implemented the main one: per-segment,\n // static-data only.\n //\n // There's also `<Link prefetch={true}>`\n // which prefetch both static *and* dynamic data.\n // Similarly, we need to fallback to the old, per-page\n // behavior if PPR is disabled for a route (via the incremental opt-in).\n //\n // Those cases will be handled here.\n spawnPrefetchSubtask(fetchRouteOnCacheMiss(route, task.key))\n\n // If the request takes longer than a minute, a subsequent request should\n // retry instead of waiting for this one. When the response is received,\n // this value will be replaced by a new value based on the stale time sent\n // from the server.\n // TODO: We should probably also manually abort the fetch task, to reclaim\n // server bandwidth.\n route.staleAt = now + 60 * 1000\n\n // Upgrade to Pending so we know there's already a request in progress\n route.status = EntryStatus.Pending\n\n // Intentional fallthrough to the Pending branch\n }\n case EntryStatus.Pending: {\n // Still pending. We can't start prefetching the segments until the route\n // tree has loaded. Add the task to the set of blocked tasks so that it\n // is notified when the route tree is ready.\n const blockedTasks = route.blockedTasks\n if (blockedTasks === null) {\n route.blockedTasks = new Set([task])\n } else {\n blockedTasks.add(task)\n }\n return PrefetchTaskExitStatus.Blocked\n }\n case EntryStatus.Rejected: {\n // Route tree failed to load. Treat as a 404.\n return PrefetchTaskExitStatus.Done\n }\n case EntryStatus.Fulfilled: {\n if (task.phase !== PrefetchPhase.Segments) {\n // Do not prefetch segment data until we've entered the segment phase.\n return PrefetchTaskExitStatus.Done\n }\n // Recursively fill in the segment tree.\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n const tree = route.tree\n\n // A task's fetch strategy gets set to `PPR` for any \"auto\" prefetch.\n // If it turned out that the route isn't PPR-enabled, we need to use `LoadingBoundary` instead.\n // We don't need to do this for runtime prefetches, because those are only available in\n // `cacheComponents`, where every route is PPR.\n let fetchStrategy: FetchStrategy\n if (tree.prefetchHints & PrefetchHint.SubtreeHasInstant) {\n // If `instant` is defined anywhere on the target route, ignore the\n // fetch strategy and switch to unified strategy used by Cache\n // Components (called `PPR` for now, will likely be renamed).\n //\n // In practice, this just means that a \"full\" prefetch (<Link\n // prefetch={true}>) has no effect. You're meant to use Runtime\n // Prefetching instead — that's the new pattern that replaces\n // prefetch={true}.\n //\n // The reason we check for `instant` rather than the `cacheComponents`\n // flag is to support incremental adoption. `prefetch={true}` will\n // continue to work until you opt into `instant`.\n fetchStrategy = FetchStrategy.PPR\n } else if (task.fetchStrategy === FetchStrategy.PPR) {\n fetchStrategy = route.supportsPerSegmentPrefetching\n ? FetchStrategy.PPR\n : FetchStrategy.LoadingBoundary\n } else {\n fetchStrategy = task.fetchStrategy\n }\n\n switch (fetchStrategy) {\n case FetchStrategy.PPR: {\n // For Cache Components pages, each segment may be prefetched\n // statically or using a runtime request, based on various\n // configurations and heuristics. We'll do this in two passes: first\n // traverse the tree and perform all the static prefetches.\n //\n // Then, if there are any segments that need a runtime request,\n // do another pass to perform a runtime prefetch.\n pingStaticHead(now, task, route)\n const exitStatus = pingSharedPartOfCacheComponentsTree(\n now,\n task,\n route,\n task.treeAtTimeOfPrefetch,\n tree\n )\n if (exitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n const spawnedRuntimePrefetches = task.spawnedRuntimePrefetches\n if (spawnedRuntimePrefetches !== null) {\n // During the first pass, we discovered segments that require a\n // runtime prefetch. Do a second pass to construct a request tree.\n const spawnedEntries = new Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n >()\n pingRuntimeHead(\n now,\n task,\n route,\n spawnedEntries,\n FetchStrategy.PPRRuntime\n )\n const requestTree = pingRuntimePrefetches(\n now,\n task,\n route,\n tree,\n spawnedRuntimePrefetches,\n spawnedEntries\n )\n let needsDynamicRequest = spawnedEntries.size > 0\n if (needsDynamicRequest) {\n // Perform a dynamic prefetch request and populate the cache with\n // the result.\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingDynamicRequest(\n task,\n route,\n FetchStrategy.PPRRuntime,\n requestTree,\n spawnedEntries\n )\n )\n }\n }\n\n return PrefetchTaskExitStatus.Done\n }\n case FetchStrategy.Full:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.LoadingBoundary: {\n // Prefetch multiple segments using a single dynamic request.\n // TODO: We can consolidate this branch with previous one by modeling\n // it as if the first segment in the new tree has runtime prefetching\n // enabled. Will do this as a follow-up refactor. Might want to remove\n // the special metatdata case below first. In the meantime, it's not\n // really that much duplication, just would be nice to remove one of\n // these codepaths.\n const spawnedEntries = new Map<\n SegmentRequestKey,\n PendingSegmentCacheEntry\n >()\n pingRuntimeHead(now, task, route, spawnedEntries, fetchStrategy)\n const dynamicRequestTree = diffRouteTreeAgainstCurrent(\n now,\n task,\n route,\n task.treeAtTimeOfPrefetch,\n tree,\n spawnedEntries,\n fetchStrategy\n )\n let needsDynamicRequest = spawnedEntries.size > 0\n if (needsDynamicRequest) {\n spawnPrefetchSubtask(\n fetchSegmentPrefetchesUsingDynamicRequest(\n task,\n route,\n fetchStrategy,\n dynamicRequestTree,\n spawnedEntries\n )\n )\n }\n return PrefetchTaskExitStatus.Done\n }\n default:\n fetchStrategy satisfies never\n }\n break\n }\n default: {\n route satisfies never\n }\n }\n return PrefetchTaskExitStatus.Done\n}\n\nfunction pingStaticHead(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry\n): void {\n // The Head data for a page (metadata, viewport) is not really a route\n // segment, in the sense that it doesn't appear in the route tree. But we\n // store it in the cache as if it were, using a special key.\n pingStaticSegmentData(\n now,\n task,\n route,\n readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, route.metadata),\n task.key,\n route.metadata\n )\n}\n\nfunction pingRuntimeHead(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.LoadingBoundary\n): void {\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n route.metadata,\n false,\n spawnedEntries,\n // When prefetching the head, there's no difference between Full\n // and LoadingBoundary\n fetchStrategy === FetchStrategy.LoadingBoundary\n ? FetchStrategy.Full\n : fetchStrategy\n )\n}\n\n// TODO: Rename dynamic -> runtime throughout this module\n\nfunction pingSharedPartOfCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n oldTree: FlightRouterState,\n newTree: RouteTree\n): PrefetchTaskExitStatus {\n // When Cache Components is enabled (or PPR, or a fully static route when PPR\n // is disabled; those cases are treated equivalently to Cache Components), we\n // start by prefetching each segment individually. Once we reach the \"new\"\n // part of the tree — the part that doesn't exist on the current page — we\n // may choose to switch to a runtime prefetch instead, based on the\n // information sent by the server in the route tree.\n //\n // The traversal starts in the \"shared\" part of the tree. Once we reach the\n // \"new\" part of the tree, we switch to a different traversal,\n // pingNewPartOfCacheComponentsTree.\n\n // Prefetch this segment's static data.\n const segment = readOrCreateSegmentCacheEntry(\n now,\n task.fetchStrategy,\n newTree\n )\n pingStaticSegmentData(now, task, route, segment, task.key, newTree)\n\n // Recursively ping the children.\n const oldTreeChildren = oldTree[1]\n const newTreeChildren = newTree.slots\n if (newTreeChildren !== null) {\n for (const parallelRouteKey in newTreeChildren) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n const newTreeChild = newTreeChildren[parallelRouteKey]\n const newTreeChildSegment = newTreeChild.segment\n const oldTreeChild: FlightRouterState | void =\n oldTreeChildren[parallelRouteKey]\n const oldTreeChildSegment: FlightRouterStateSegment | void =\n oldTreeChild?.[0]\n let childExitStatus\n if (\n oldTreeChildSegment !== undefined &&\n doesCurrentSegmentMatchCachedSegment(\n route,\n newTreeChildSegment,\n oldTreeChildSegment\n )\n ) {\n // We're still in the \"shared\" part of the tree.\n childExitStatus = pingSharedPartOfCacheComponentsTree(\n now,\n task,\n route,\n oldTreeChild,\n newTreeChild\n )\n } else {\n // We've entered the \"new\" part of the tree. Switch\n // traversal functions.\n childExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n newTreeChild\n )\n }\n if (childExitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n }\n }\n\n return PrefetchTaskExitStatus.Done\n}\n\nfunction pingNewPartOfCacheComponentsTree(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree\n): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {\n // We're now prefetching in the \"new\" part of the tree, the part that doesn't\n // exist on the current page. (In other words, we're deeper than the\n // shared layouts.) Segments in here default to being prefetched statically.\n // However, if the server instructs us to, we may switch to a runtime\n // prefetch instead. Traverse the tree and check at each segment.\n if (tree.prefetchHints & PrefetchHint.HasRuntimePrefetch) {\n // This route has a runtime prefetch response. Since we're below the shared\n // layout, everything from this point should be prefetched using a single,\n // combined runtime request, rather than using per-segment static requests.\n // This is true even if some of the child segments are known to be fully\n // static — once we've decided to perform a runtime prefetch, we might as\n // well respond with the static segments in the same roundtrip. (That's how\n // regular navigations work, too.) We'll still skip over segments that are\n // already cached, though.\n //\n // It's the server's responsibility to set a reasonable value of\n // `hasRuntimePrefetch`. Currently it's user-defined, but eventually, the\n // server may send a value of `false` even if the user opts in, if it\n // determines during build that the route is always fully static. There are\n // more optimizations we can do once we implement fallback param\n // tracking, too.\n //\n // Use the task object to collect the segments that need a runtime prefetch.\n // This will signal to the outer task queue that a second traversal is\n // required to construct a request tree.\n if (task.spawnedRuntimePrefetches === null) {\n task.spawnedRuntimePrefetches = new Set([tree.requestKey])\n } else {\n task.spawnedRuntimePrefetches.add(tree.requestKey)\n }\n // Then exit the traversal without prefetching anything further.\n return PrefetchTaskExitStatus.Done\n }\n\n // This segment should not be runtime prefetched. Prefetch its static data.\n const segment = readOrCreateSegmentCacheEntry(now, task.fetchStrategy, tree)\n pingStaticSegmentData(now, task, route, segment, task.key, tree)\n if (tree.slots !== null) {\n if (!hasNetworkBandwidth(task)) {\n // Stop prefetching segments until there's more bandwidth.\n return PrefetchTaskExitStatus.InProgress\n }\n // Recursively ping the children.\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n const childExitStatus = pingNewPartOfCacheComponentsTree(\n now,\n task,\n route,\n childTree\n )\n if (childExitStatus === PrefetchTaskExitStatus.InProgress) {\n // Child yielded without finishing.\n return PrefetchTaskExitStatus.InProgress\n }\n }\n }\n // This segment and all its children have finished prefetching.\n return PrefetchTaskExitStatus.Done\n}\n\nfunction diffRouteTreeAgainstCurrent(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n oldTree: FlightRouterState,\n newTree: RouteTree,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy:\n | FetchStrategy.Full\n | FetchStrategy.PPRRuntime\n | FetchStrategy.LoadingBoundary\n): FlightRouterState {\n // This is a single recursive traversal that does multiple things:\n // - Finds the parts of the target route (newTree) that are not part of\n // of the current page (oldTree) by diffing them, using the same algorithm\n // as a real navigation.\n // - Constructs a request tree (FlightRouterState) that describes which\n // segments need to be prefetched and which ones are already cached.\n // - Creates a set of pending cache entries for the segments that need to\n // be prefetched, so that a subsequent prefetch task does not request the\n // same segments again.\n const oldTreeChildren = oldTree[1]\n const newTreeChildren = newTree.slots\n let requestTreeChildren: Record<string, FlightRouterState> = {}\n if (newTreeChildren !== null) {\n for (const parallelRouteKey in newTreeChildren) {\n const newTreeChild = newTreeChildren[parallelRouteKey]\n const newTreeChildSegment = newTreeChild.segment\n const oldTreeChild: FlightRouterState | void =\n oldTreeChildren[parallelRouteKey]\n const oldTreeChildSegment: FlightRouterStateSegment | void =\n oldTreeChild?.[0]\n if (\n oldTreeChildSegment !== undefined &&\n doesCurrentSegmentMatchCachedSegment(\n route,\n newTreeChildSegment,\n oldTreeChildSegment\n )\n ) {\n // This segment is already part of the current route. Keep traversing.\n const requestTreeChild = diffRouteTreeAgainstCurrent(\n now,\n task,\n route,\n oldTreeChild,\n newTreeChild,\n spawnedEntries,\n fetchStrategy\n )\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n } else {\n // This segment is not part of the current route. We're entering a\n // part of the tree that we need to prefetch (unless everything is\n // already cached).\n switch (fetchStrategy) {\n case FetchStrategy.LoadingBoundary: {\n // When PPR is disabled, we can't prefetch per segment. We must\n // fallback to the old prefetch behavior and send a dynamic request.\n // Only routes that include a loading boundary can be prefetched in\n // this way.\n //\n // This is simlar to a \"full\" prefetch, but we're much more\n // conservative about which segments to include in the request.\n //\n // The server will only render up to the first loading boundary\n // inside new part of the tree. If there's no loading boundary\n // anywhere in the tree, the server will never return any data, so\n // we can skip the request.\n const subtreeHasLoadingBoundary =\n (newTreeChild.prefetchHints &\n (PrefetchHint.SegmentHasLoadingBoundary |\n PrefetchHint.SubtreeHasLoadingBoundary)) !==\n 0\n const requestTreeChild = subtreeHasLoadingBoundary\n ? pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now,\n task,\n route,\n newTreeChild,\n null,\n spawnedEntries\n )\n : // There's no loading boundary within this tree. Bail out.\n convertRouteTreeToFlightRouterState(newTreeChild)\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n break\n }\n case FetchStrategy.PPRRuntime: {\n // This is a runtime prefetch. Fetch all cacheable data in the tree,\n // not just the static PPR shell.\n const requestTreeChild = pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n newTreeChild,\n false,\n spawnedEntries,\n fetchStrategy\n )\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n break\n }\n case FetchStrategy.Full: {\n // This is a \"full\" prefetch. Fetch all the data in the tree, both\n // static and dynamic. We issue roughly the same request that we\n // would during a real navigation. The goal is that once the\n // navigation occurs, the router should not have to fetch any\n // additional data.\n //\n // Although the response will include dynamic data, opting into a\n // Full prefetch — via <Link prefetch={true}> — implicitly\n // instructs the cache to treat the response as \"static\", or non-\n // dynamic, since the whole point is to cache it for\n // future navigations.\n //\n // Construct a tree (currently a FlightRouterState) that represents\n // which segments need to be prefetched and which ones are already\n // cached. If the tree is empty, then we can exit. Otherwise, we'll\n // send the request tree to the server and use the response to\n // populate the segment cache.\n const requestTreeChild = pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n newTreeChild,\n false,\n spawnedEntries,\n fetchStrategy\n )\n requestTreeChildren[parallelRouteKey] = requestTreeChild\n break\n }\n default:\n fetchStrategy satisfies never\n }\n }\n }\n }\n const requestTree: FlightRouterState = [\n newTree.segment,\n requestTreeChildren,\n null,\n null,\n ]\n return requestTree\n}\n\nfunction pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n refetchMarkerContext: 'refetch' | 'inside-shared-layout' | null,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): FlightRouterState {\n // This function is similar to pingRouteTreeAndIncludeDynamicData, except the\n // server is only going to return a minimal loading state — it will stop\n // rendering at the first loading boundary. Whereas a Full prefetch is\n // intentionally aggressive and tries to pretfetch all the data that will be\n // needed for a navigation, a LoadingBoundary prefetch is much more\n // conservative. For example, it will omit from the request tree any segment\n // that is already cached, regardles of whether it's partial or full. By\n // contrast, a Full prefetch will refetch partial segments.\n\n // \"inside-shared-layout\" tells the server where to start looking for a\n // loading boundary.\n let refetchMarker: 'refetch' | 'inside-shared-layout' | null =\n refetchMarkerContext === null ? 'inside-shared-layout' : null\n\n const segment = readOrCreateSegmentCacheEntry(now, task.fetchStrategy, tree)\n switch (segment.status) {\n case EntryStatus.Empty: {\n // This segment is not cached. Add a refetch marker so the server knows\n // to start rendering here.\n // TODO: Instead of a \"refetch\" marker, we could just omit this subtree's\n // FlightRouterState from the request tree. I think this would probably\n // already work even without any updates to the server. For consistency,\n // though, I'll send the full tree and we'll look into this later as part\n // of a larger redesign of the request protocol.\n\n // Add the pending cache entry to the result map.\n spawnedEntries.set(\n tree.requestKey,\n upgradeToPendingSegment(\n segment,\n // Set the fetch strategy to LoadingBoundary to indicate that the server\n // might not include it in the pending response. If another route is able\n // to issue a per-segment request, we'll do that in the background.\n FetchStrategy.LoadingBoundary\n )\n )\n if (refetchMarkerContext !== 'refetch') {\n refetchMarker = refetchMarkerContext = 'refetch'\n } else {\n // There's already a parent with a refetch marker, so we don't need\n // to add another one.\n }\n break\n }\n case EntryStatus.Fulfilled: {\n // The segment is already cached.\n const segmentHasLoadingBoundary =\n (tree.prefetchHints & PrefetchHint.SegmentHasLoadingBoundary) !== 0\n if (segmentHasLoadingBoundary) {\n // This segment has a loading boundary, which means the server won't\n // render its children. So there's nothing left to prefetch along this\n // path. We can bail out.\n return convertRouteTreeToFlightRouterState(tree)\n }\n // NOTE: If the cached segment were fetched using PPR, then it might be\n // partial. We could get a more complete version of the segment by\n // including it in this non-PPR request.\n //\n // We're intentionally choosing not to, though, because it's generally\n // better to avoid doing a full prefetch whenever possible.\n break\n }\n case EntryStatus.Pending: {\n // There's another prefetch currently in progress. Don't add the refetch\n // marker yet, so the server knows it can skip rendering this segment.\n break\n }\n case EntryStatus.Rejected: {\n // The segment failed to load. We shouldn't issue another request until\n // the stale time has elapsed.\n break\n }\n default:\n segment satisfies never\n }\n const requestTreeChildren: Record<string, FlightRouterState> = {}\n if (tree.slots !== null) {\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n requestTreeChildren[parallelRouteKey] =\n pingPPRDisabledRouteTreeUpToLoadingBoundary(\n now,\n task,\n route,\n childTree,\n refetchMarkerContext,\n spawnedEntries\n )\n }\n }\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker,\n ]\n return requestTree\n}\n\nfunction pingRouteTreeAndIncludeDynamicData(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n isInsideRefetchingParent: boolean,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,\n fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime\n): FlightRouterState {\n // The tree we're constructing is the same shape as the tree we're navigating\n // to. But even though this is a \"new\" tree, some of the individual segments\n // may be cached as a result of other route prefetches.\n //\n // So we need to find the first uncached segment along each path add an\n // explicit \"refetch\" marker so the server knows where to start rendering.\n // Once the server starts rendering along a path, it keeps rendering the\n // entire subtree.\n const segment = readOrCreateSegmentCacheEntry(\n now,\n // Note that `fetchStrategy` might be different from `task.fetchStrategy`,\n // and we have to use the former here.\n // We can have a task with `FetchStrategy.PPR` where some of its segments are configured to\n // always use runtime prefetching (via `export const prefetch`), and those should check for\n // entries that include search params.\n fetchStrategy,\n tree\n )\n\n let spawnedSegment: PendingSegmentCacheEntry | null = null\n\n switch (segment.status) {\n case EntryStatus.Empty: {\n // This segment is not cached.\n if (fetchStrategy === FetchStrategy.Full) {\n // Check if there's a matching entry in the bfcache. If so, fulfill the\n // segment using the bfcache entry instead of issuing a new request.\n const fulfilled = attemptToFulfillDynamicSegmentFromBFCache(\n now,\n segment,\n tree\n )\n if (fulfilled !== null) {\n break\n }\n }\n // Include it in the request.\n spawnedSegment = upgradeToPendingSegment(segment, fetchStrategy)\n break\n }\n case EntryStatus.Fulfilled: {\n // The segment is already cached.\n if (\n segment.isPartial &&\n canNewFetchStrategyProvideMoreContent(\n segment.fetchStrategy,\n fetchStrategy\n )\n ) {\n // The cached segment contains dynamic holes, and was prefetched using a\n // less specific strategy than the current one. This means we're in one\n // of these cases:\n // - we have a static prefetch, and we're doing a runtime prefetch\n // - we have a static or runtime prefetch, and we're doing a Full\n // prefetch (or a navigation).\n // In either case, we need to include it in the request to get a more\n // specific (or full) version. However, if there's a non-stale bfcache\n // entry from a previous navigation, prefer that over making a new\n // request.\n if (fetchStrategy === FetchStrategy.Full) {\n const fulfilled = attemptToUpgradeSegmentFromBFCache(now, tree)\n if (fulfilled !== null) {\n break\n }\n }\n spawnedSegment = pingFullSegmentRevalidation(now, tree, fetchStrategy)\n }\n break\n }\n case EntryStatus.Pending:\n case EntryStatus.Rejected: {\n // There's either another prefetch currently in progress, or the previous\n // attempt failed. If the new strategy can provide more content, fetch it again.\n if (\n canNewFetchStrategyProvideMoreContent(\n segment.fetchStrategy,\n fetchStrategy\n )\n ) {\n spawnedSegment = pingFullSegmentRevalidation(now, tree, fetchStrategy)\n }\n break\n }\n default:\n segment satisfies never\n }\n const requestTreeChildren: Record<string, FlightRouterState> = {}\n if (tree.slots !== null) {\n for (const parallelRouteKey in tree.slots) {\n const childTree = tree.slots[parallelRouteKey]\n requestTreeChildren[parallelRouteKey] =\n pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n childTree,\n isInsideRefetchingParent || spawnedSegment !== null,\n spawnedEntries,\n fetchStrategy\n )\n }\n }\n\n if (spawnedSegment !== null) {\n // Add the pending entry to the result map.\n spawnedEntries.set(tree.requestKey, spawnedSegment)\n }\n\n // Don't bother to add a refetch marker if one is already present in a parent.\n const refetchMarker =\n !isInsideRefetchingParent && spawnedSegment !== null ? 'refetch' : null\n\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n refetchMarker,\n ]\n return requestTree\n}\n\nfunction pingRuntimePrefetches(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n tree: RouteTree,\n spawnedRuntimePrefetches: Set<SegmentRequestKey>,\n spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): FlightRouterState {\n // Construct a request tree (FlightRouterState) for a runtime prefetch. If\n // a segment is part of the runtime prefetch, the tree is constructed by\n // diffing against what's already in the prefetch cache. Otherwise, we send\n // a regular FlightRouterState with no special markers.\n //\n // See pingRouteTreeAndIncludeDynamicData for details.\n if (spawnedRuntimePrefetches.has(tree.requestKey)) {\n // This segment needs a runtime prefetch.\n return pingRouteTreeAndIncludeDynamicData(\n now,\n task,\n route,\n tree,\n false,\n spawnedEntries,\n FetchStrategy.PPRRuntime\n )\n }\n let requestTreeChildren: Record<string, FlightRouterState> = {}\n const slots = tree.slots\n if (slots !== null) {\n for (const parallelRouteKey in slots) {\n const childTree = slots[parallelRouteKey]\n requestTreeChildren[parallelRouteKey] = pingRuntimePrefetches(\n now,\n task,\n route,\n childTree,\n spawnedRuntimePrefetches,\n spawnedEntries\n )\n }\n }\n\n // This segment is not part of the runtime prefetch. Clone the base tree.\n const requestTree: FlightRouterState = [\n tree.segment,\n requestTreeChildren,\n null,\n null,\n ]\n return requestTree\n}\n\nfunction pingStaticSegmentData(\n now: number,\n task: PrefetchTask,\n route: FulfilledRouteCacheEntry,\n segment: SegmentCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree\n): void {\n switch (segment.status) {\n case EntryStatus.Empty:\n if (process.env.__NEXT_PREFETCH_INLINING) {\n // All segment data for this route is bundled into a single\n // /_inlined response. Walk the full route tree to collect all\n // Empty segments, upgrade them to Pending, and spawn one\n // bundled request. Subsequent calls for other segments in the\n // same tree will see them as Pending and skip.\n const inlinedEntries = collectInlinedEntries(now, route)\n if (inlinedEntries.size > 0) {\n spawnPrefetchSubtask(\n fetchInlinedSegmentsOnCacheMiss(\n route,\n routeKey,\n route.tree,\n inlinedEntries\n )\n )\n }\n break\n }\n // Upgrade to Pending so we know there's already a request in progress\n spawnPrefetchSubtask(\n fetchSegmentOnCacheMiss(\n route,\n upgradeToPendingSegment(segment, FetchStrategy.PPR),\n routeKey,\n tree\n )\n )\n break\n case EntryStatus.Pending: {\n // There's already a request in progress. Depending on what kind of\n // request it is, we may want to revalidate it.\n switch (segment.fetchStrategy) {\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n // There's already a request in progress. Don't do anything.\n break\n case FetchStrategy.LoadingBoundary:\n // There's a pending request, but because it's using the old\n // prefetching strategy, we can't be sure if it will be fulfilled by\n // the response — it might be inside the loading boundary. Perform\n // a revalidation, but because it's speculative, wait to do it at\n // background priority.\n if (background(task)) {\n // TODO: Instead of speculatively revalidating, consider including\n // `hasLoading` in the route tree prefetch response.\n pingPPRSegmentRevalidation(now, route, routeKey, tree)\n }\n break\n default:\n segment.fetchStrategy satisfies never\n }\n break\n }\n case EntryStatus.Rejected: {\n // The existing entry in the cache was rejected. Depending on how it\n // was originally fetched, we may or may not want to revalidate it.\n switch (segment.fetchStrategy) {\n case FetchStrategy.PPR:\n case FetchStrategy.PPRRuntime:\n case FetchStrategy.Full:\n // The previous attempt to fetch this entry failed. Don't attempt to\n // fetch it again until the entry expires.\n break\n case FetchStrategy.LoadingBoundary:\n // There's a rejected entry, but it was fetched using the loading\n // boundary strategy. So the reason it wasn't returned by the server\n // might just be because it was inside a loading boundary. Or because\n // there was a dynamic rewrite. Revalidate it using the per-\n // segment strategy.\n //\n // Because a rejected segment will definitely prevent the segment (and\n // all of its children) from rendering, we perform this revalidation\n // immediately instead of deferring it to a background task.\n pingPPRSegmentRevalidation(now, route, routeKey, tree)\n break\n default:\n segment.fetchStrategy satisfies never\n }\n break\n }\n case EntryStatus.Fulfilled:\n // Segment is already cached. There's nothing left to prefetch.\n break\n default:\n segment satisfies never\n }\n\n // Segments do not have dependent tasks, so once the prefetch is initiated,\n // there's nothing else for us to do (except write the server data into the\n // entry, which is handled by `fetchSegmentOnCacheMiss`).\n}\n\n/**\n * Walks the RouteTree (including the head metadata) and collects any segments\n * that are still Empty into a Map, upgrading them to Pending. These entries\n * will be fulfilled by the inlined prefetch response.\n */\nfunction collectInlinedEntries(\n now: number,\n route: FulfilledRouteCacheEntry\n): Map<SegmentRequestKey, PendingSegmentCacheEntry> {\n const entries = new Map<SegmentRequestKey, PendingSegmentCacheEntry>()\n collectInlinedEntriesImpl(now, route.tree, entries)\n // Also collect the head/metadata entry.\n const headEntry = readOrCreateSegmentCacheEntry(\n now,\n FetchStrategy.PPR,\n route.metadata\n )\n if (headEntry.status === EntryStatus.Empty) {\n entries.set(\n route.metadata.requestKey,\n upgradeToPendingSegment(headEntry, FetchStrategy.PPR)\n )\n }\n return entries\n}\n\nfunction collectInlinedEntriesImpl(\n now: number,\n tree: RouteTree,\n entries: Map<SegmentRequestKey, PendingSegmentCacheEntry>\n): void {\n const entry = readOrCreateSegmentCacheEntry(now, FetchStrategy.PPR, tree)\n if (entry.status === EntryStatus.Empty) {\n entries.set(\n tree.requestKey,\n upgradeToPendingSegment(entry, FetchStrategy.PPR)\n )\n }\n if (tree.slots !== null) {\n for (const parallelRouteKey in tree.slots) {\n collectInlinedEntriesImpl(now, tree.slots[parallelRouteKey], entries)\n }\n }\n}\n\nfunction pingPPRSegmentRevalidation(\n now: number,\n route: FulfilledRouteCacheEntry,\n routeKey: RouteCacheKey,\n tree: RouteTree\n): void {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(\n now,\n FetchStrategy.PPR,\n tree\n )\n switch (revalidatingSegment.status) {\n case EntryStatus.Empty:\n // Spawn a prefetch request. The fetch function handles upserting\n // the entry at the correct fulfilled vary path upon completion.\n spawnPrefetchSubtask(\n fetchSegmentOnCacheMiss(\n route,\n upgradeToPendingSegment(revalidatingSegment, FetchStrategy.PPR),\n routeKey,\n tree\n )\n )\n break\n case EntryStatus.Pending:\n // There's already a revalidation in progress.\n break\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n // A previous revalidation attempt finished, but we chose not to replace\n // the existing entry in the cache. Don't try again until or unless the\n // revalidation entry expires.\n break\n default:\n revalidatingSegment satisfies never\n }\n}\n\nfunction pingFullSegmentRevalidation(\n now: number,\n tree: RouteTree,\n fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime\n): PendingSegmentCacheEntry | null {\n const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(\n now,\n fetchStrategy,\n tree\n )\n if (revalidatingSegment.status === EntryStatus.Empty) {\n // During a Full/PPRRuntime prefetch, a single dynamic request is made for all the\n // segments that we need. So we don't initiate a request here directly. By\n // returning a pending entry from this function, it signals to the caller\n // that this segment should be included in the request that's sent to\n // the server.\n const pendingSegment = upgradeToPendingSegment(\n revalidatingSegment,\n fetchStrategy\n )\n // The upsert is handled by fulfillEntrySpawnedByRuntimePrefetch\n // when the dynamic prefetch response is written into the cache.\n return pendingSegment\n } else {\n // There's already a revalidation in progress.\n const nonEmptyRevalidatingSegment = revalidatingSegment\n if (\n canNewFetchStrategyProvideMoreContent(\n nonEmptyRevalidatingSegment.fetchStrategy,\n fetchStrategy\n )\n ) {\n // The existing revalidation was fetched using a less specific strategy.\n // Reset it and start a new revalidation.\n const emptySegment = overwriteRevalidatingSegmentCacheEntry(\n now,\n fetchStrategy,\n tree\n )\n const pendingSegment = upgradeToPendingSegment(\n emptySegment,\n fetchStrategy\n )\n // The upsert is handled by fulfillEntrySpawnedByRuntimePrefetch\n // when the dynamic prefetch response is written into the cache.\n return pendingSegment\n }\n switch (nonEmptyRevalidatingSegment.status) {\n case EntryStatus.Pending:\n // There's already an in-progress prefetch that includes this segment.\n return null\n case EntryStatus.Fulfilled:\n case EntryStatus.Rejected:\n // A previous revalidation attempt finished, but we chose not to replace\n // the existing entry in the cache. Don't try again until or unless the\n // revalidation entry expires.\n return null\n default:\n nonEmptyRevalidatingSegment satisfies never\n return null\n }\n }\n}\n\nfunction doesCurrentSegmentMatchCachedSegment(\n route: FulfilledRouteCacheEntry,\n currentSegment: Segment,\n cachedSegment: Segment\n): boolean {\n if (cachedSegment === PAGE_SEGMENT_KEY) {\n // In the FlightRouterState stored by the router, the page segment has the\n // rendered search params appended to the name of the segment. In the\n // prefetch cache, however, this is stored separately. So, when comparing\n // the router's current FlightRouterState to the cached FlightRouterState,\n // we need to make sure we compare both parts of the segment.\n // TODO: This is not modeled clearly. We use the same type,\n // FlightRouterState, for both the CacheNode tree _and_ the prefetch cache\n // _and_ the server response format, when conceptually those are three\n // different things and treated in different ways. We should encode more of\n // this information into the type design so mistakes are less likely.\n return (\n currentSegment ===\n addSearchParamsIfPageSegment(\n PAGE_SEGMENT_KEY,\n Object.fromEntries(new URLSearchParams(route.renderedSearch))\n )\n )\n }\n // Non-page segments are compared using the same function as the server\n return matchSegment(cachedSegment, currentSegment)\n}\n\n// -----------------------------------------------------------------------------\n// The remainder of the module is a MinHeap implementation. Try not to put any\n// logic below here unless it's related to the heap algorithm. We can extract\n// this to a separate module if/when we need multiple kinds of heaps.\n// -----------------------------------------------------------------------------\n\nfunction compareQueuePriority(a: PrefetchTask, b: PrefetchTask) {\n // Since the queue is a MinHeap, this should return a positive number if b is\n // higher priority than a, and a negative number if a is higher priority\n // than b.\n\n // `priority` is an integer, where higher numbers are higher priority.\n const priorityDiff = b.priority - a.priority\n if (priorityDiff !== 0) {\n return priorityDiff\n }\n\n // If the priority is the same, check which phase the prefetch is in — is it\n // prefetching the route tree, or the segments? Route trees are prioritized.\n const phaseDiff = b.phase - a.phase\n if (phaseDiff !== 0) {\n return phaseDiff\n }\n\n // Finally, check the insertion order. `sortId` is an incrementing counter\n // assigned to prefetches. We want to process the newest prefetches first.\n return b.sortId - a.sortId\n}\n\nfunction heapPush(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = heap.length\n heap.push(node)\n node._heapIndex = index\n heapSiftUp(heap, node, index)\n}\n\nfunction heapPeek(heap: Array<PrefetchTask>): PrefetchTask | null {\n return heap.length === 0 ? null : heap[0]\n}\n\nfunction heapPop(heap: Array<PrefetchTask>): PrefetchTask | null {\n if (heap.length === 0) {\n return null\n }\n const first = heap[0]\n first._heapIndex = -1\n const last = heap.pop() as PrefetchTask\n if (last !== first) {\n heap[0] = last\n last._heapIndex = 0\n heapSiftDown(heap, last, 0)\n }\n return first\n}\n\nfunction heapDelete(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = node._heapIndex\n if (index !== -1) {\n node._heapIndex = -1\n if (heap.length !== 0) {\n const last = heap.pop() as PrefetchTask\n if (last !== node) {\n heap[index] = last\n last._heapIndex = index\n heapSiftDown(heap, last, index)\n }\n }\n }\n}\n\nfunction heapResift(heap: Array<PrefetchTask>, node: PrefetchTask): void {\n const index = node._heapIndex\n if (index !== -1) {\n if (index === 0) {\n heapSiftDown(heap, node, 0)\n } else {\n const parentIndex = (index - 1) >>> 1\n const parent = heap[parentIndex]\n if (compareQueuePriority(parent, node) > 0) {\n // The parent is larger. Sift up.\n heapSiftUp(heap, node, index)\n } else {\n // The parent is smaller (or equal). Sift down.\n heapSiftDown(heap, node, index)\n }\n }\n }\n}\n\nfunction heapSiftUp(\n heap: Array<PrefetchTask>,\n node: PrefetchTask,\n i: number\n): void {\n let index = i\n while (index > 0) {\n const parentIndex = (index - 1) >>> 1\n const parent = heap[parentIndex]\n if (compareQueuePriority(parent, node) > 0) {\n // The parent is larger. Swap positions.\n heap[parentIndex] = node\n node._heapIndex = parentIndex\n heap[index] = parent\n parent._heapIndex = index\n\n index = parentIndex\n } else {\n // The parent is smaller. Exit.\n return\n }\n }\n}\n\nfunction heapSiftDown(\n heap: Array<PrefetchTask>,\n node: PrefetchTask,\n i: number\n): void {\n let index = i\n const length = heap.length\n const halfLength = length >>> 1\n while (index < halfLength) {\n const leftIndex = (index + 1) * 2 - 1\n const left = heap[leftIndex]\n const rightIndex = leftIndex + 1\n const right = heap[rightIndex]\n\n // If the left or right node is smaller, swap with the smaller of those.\n if (compareQueuePriority(left, node) < 0) {\n if (rightIndex < length && compareQueuePriority(right, left) < 0) {\n heap[index] = right\n right._heapIndex = index\n heap[rightIndex] = node\n node._heapIndex = rightIndex\n\n index = rightIndex\n } else {\n heap[index] = left\n left._heapIndex = index\n heap[leftIndex] = node\n node._heapIndex = leftIndex\n\n index = leftIndex\n }\n } else if (rightIndex < length && compareQueuePriority(right, node) < 0) {\n heap[index] = right\n right._heapIndex = index\n heap[rightIndex] = node\n node._heapIndex = rightIndex\n\n index = rightIndex\n } else {\n // Neither child is smaller. Exit.\n return\n }\n }\n}\n","import type { FlightRouterState } from '../../shared/lib/app-router-types'\nimport type { AppRouterInstance } from '../../shared/lib/app-router-context.shared-runtime'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n PrefetchPriority,\n} from './segment-cache/types'\nimport { createCacheKey } from './segment-cache/cache-key'\nimport {\n type PrefetchTask,\n schedulePrefetchTask as scheduleSegmentPrefetchTask,\n cancelPrefetchTask,\n reschedulePrefetchTask,\n isPrefetchTaskDirty,\n} from './segment-cache/scheduler'\nimport { startTransition } from 'react'\n\ntype LinkElement = HTMLAnchorElement | SVGAElement\n\ntype Element = LinkElement | HTMLFormElement\n\n// Properties that are shared between Link and Form instances. We use the same\n// shape for both to prevent a polymorphic de-opt in the VM.\ntype LinkOrFormInstanceShared = {\n router: AppRouterInstance\n fetchStrategy: PrefetchTaskFetchStrategy\n\n isVisible: boolean\n\n // The most recently initiated prefetch task. It may or may not have\n // already completed. The same prefetch task object can be reused across\n // multiple prefetches of the same link.\n prefetchTask: PrefetchTask | null\n}\n\nexport type FormInstance = LinkOrFormInstanceShared & {\n prefetchHref: string\n setOptimisticLinkStatus: null\n}\n\ntype PrefetchableLinkInstance = LinkOrFormInstanceShared & {\n prefetchHref: string\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n}\n\ntype NonPrefetchableLinkInstance = LinkOrFormInstanceShared & {\n prefetchHref: null\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n}\n\ntype PrefetchableInstance = PrefetchableLinkInstance | FormInstance\n\nexport type LinkInstance =\n | PrefetchableLinkInstance\n | NonPrefetchableLinkInstance\n\n// Tracks the most recently navigated link instance. When null, indicates\n// the current navigation was not initiated by a link click.\nlet linkForMostRecentNavigation: LinkInstance | null = null\n\n// Status object indicating link is pending\nexport const PENDING_LINK_STATUS = { pending: true }\n\n// Status object indicating link is idle\nexport const IDLE_LINK_STATUS = { pending: false }\n\n// Updates the loading state when navigating between links\n// - Resets the previous link's loading state\n// - Sets the new link's loading state\n// - Updates tracking of current navigation\nexport function setLinkForCurrentNavigation(link: LinkInstance | null) {\n startTransition(() => {\n linkForMostRecentNavigation?.setOptimisticLinkStatus(IDLE_LINK_STATUS)\n link?.setOptimisticLinkStatus(PENDING_LINK_STATUS)\n linkForMostRecentNavigation = link\n })\n}\n\n// Unmounts the current link instance from navigation tracking\nexport function unmountLinkForCurrentNavigation(link: LinkInstance) {\n if (linkForMostRecentNavigation === link) {\n linkForMostRecentNavigation = null\n }\n}\n\n/**\n * Returns the link instance that initiated the most recent navigation.\n * Returns null if the navigation was not initiated by a link click.\n *\n * Used by the Instant Navigation Testing API in dev mode to match the\n * fetch strategy of the link during cache-miss navigations.\n */\nexport function getLinkForCurrentNavigation(): LinkInstance | null {\n return linkForMostRecentNavigation\n}\n\n// Use a WeakMap to associate a Link instance with its DOM element. This is\n// used by the IntersectionObserver to track the link's visibility.\nconst prefetchable:\n | WeakMap<Element, PrefetchableInstance>\n | Map<Element, PrefetchableInstance> =\n typeof WeakMap === 'function' ? new WeakMap() : new Map()\n\n// A Set of the currently visible links. We re-prefetch visible links after a\n// cache invalidation, or when the current URL changes. It's a separate data\n// structure from the WeakMap above because only the visible links need to\n// be enumerated.\nconst prefetchableAndVisible: Set<PrefetchableInstance> = new Set()\n\n// A single IntersectionObserver instance shared by all <Link> components.\nconst observer: IntersectionObserver | null =\n typeof IntersectionObserver === 'function'\n ? new IntersectionObserver(handleIntersect, {\n rootMargin: '200px',\n })\n : null\n\nfunction observeVisibility(element: Element, instance: PrefetchableInstance) {\n const existingInstance = prefetchable.get(element)\n if (existingInstance !== undefined) {\n // This shouldn't happen because each <Link> component should have its own\n // anchor tag instance, but it's defensive coding to avoid a memory leak in\n // case there's a logical error somewhere else.\n unmountPrefetchableInstance(element)\n }\n // Only track prefetchable links that have a valid prefetch URL\n prefetchable.set(element, instance)\n if (observer !== null) {\n observer.observe(element)\n }\n}\n\nfunction coercePrefetchableUrl(href: string): URL | null {\n if (typeof window !== 'undefined') {\n const { createPrefetchURL } =\n require('./app-router-utils') as typeof import('./app-router-utils')\n\n try {\n return createPrefetchURL(href)\n } catch {\n // createPrefetchURL sometimes throws an error if an invalid URL is\n // provided, though I'm not sure if it's actually necessary.\n // TODO: Consider removing the throw from the inner function, or change it\n // to reportError. Or maybe the error isn't even necessary for automatic\n // prefetches, just navigations.\n const reportErrorFn =\n typeof reportError === 'function' ? reportError : console.error\n reportErrorFn(\n `Cannot prefetch '${href}' because it cannot be converted to a URL.`\n )\n return null\n }\n } else {\n return null\n }\n}\n\nexport function mountLinkInstance(\n element: LinkElement,\n href: string,\n router: AppRouterInstance,\n fetchStrategy: PrefetchTaskFetchStrategy,\n prefetchEnabled: boolean,\n setOptimisticLinkStatus: (status: { pending: boolean }) => void\n): LinkInstance {\n if (prefetchEnabled) {\n const prefetchURL = coercePrefetchableUrl(href)\n if (prefetchURL !== null) {\n const instance: PrefetchableLinkInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus,\n }\n // We only observe the link's visibility if it's prefetchable. For\n // example, this excludes links to external URLs.\n observeVisibility(element, instance)\n return instance\n }\n }\n // If the link is not prefetchable, we still create an instance so we can\n // track its optimistic state (i.e. useLinkStatus).\n const instance: NonPrefetchableLinkInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: null,\n setOptimisticLinkStatus,\n }\n return instance\n}\n\nexport function mountFormInstance(\n element: HTMLFormElement,\n href: string,\n router: AppRouterInstance,\n fetchStrategy: PrefetchTaskFetchStrategy\n): void {\n const prefetchURL = coercePrefetchableUrl(href)\n if (prefetchURL === null) {\n // This href is not prefetchable, so we don't track it.\n // TODO: We currently observe/unobserve a form every time its href changes.\n // For Links, this isn't a big deal because the href doesn't usually change,\n // but for forms it's extremely common. We should optimize this.\n return\n }\n const instance: FormInstance = {\n router,\n fetchStrategy,\n isVisible: false,\n prefetchTask: null,\n prefetchHref: prefetchURL.href,\n setOptimisticLinkStatus: null,\n }\n observeVisibility(element, instance)\n}\n\nexport function unmountPrefetchableInstance(element: Element) {\n const instance = prefetchable.get(element)\n if (instance !== undefined) {\n prefetchable.delete(element)\n prefetchableAndVisible.delete(instance)\n const prefetchTask = instance.prefetchTask\n if (prefetchTask !== null) {\n cancelPrefetchTask(prefetchTask)\n }\n }\n if (observer !== null) {\n observer.unobserve(element)\n }\n}\n\nfunction handleIntersect(entries: Array<IntersectionObserverEntry>) {\n for (const entry of entries) {\n // Some extremely old browsers or polyfills don't reliably support\n // isIntersecting so we check intersectionRatio instead. (Do we care? Not\n // really. But whatever this is fine.)\n const isVisible = entry.intersectionRatio > 0\n onLinkVisibilityChanged(entry.target as HTMLAnchorElement, isVisible)\n }\n}\n\nexport function onLinkVisibilityChanged(element: Element, isVisible: boolean) {\n if (process.env.NODE_ENV !== 'production') {\n // Prefetching on viewport is disabled in development for performance\n // reasons, because it requires compiling the target page.\n // TODO: Investigate re-enabling this.\n return\n }\n\n const instance = prefetchable.get(element)\n if (instance === undefined) {\n return\n }\n\n instance.isVisible = isVisible\n if (isVisible) {\n prefetchableAndVisible.add(instance)\n } else {\n prefetchableAndVisible.delete(instance)\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Default)\n}\n\nexport function onNavigationIntent(\n element: HTMLAnchorElement | SVGAElement,\n unstable_upgradeToDynamicPrefetch: boolean\n) {\n const instance = prefetchable.get(element)\n if (instance === undefined) {\n return\n }\n // Prefetch the link on hover/touchstart.\n if (instance !== undefined) {\n if (\n process.env.__NEXT_DYNAMIC_ON_HOVER &&\n unstable_upgradeToDynamicPrefetch\n ) {\n // Switch to a full prefetch\n instance.fetchStrategy = FetchStrategy.Full\n }\n rescheduleLinkPrefetch(instance, PrefetchPriority.Intent)\n }\n}\n\nfunction rescheduleLinkPrefetch(\n instance: PrefetchableInstance,\n priority: PrefetchPriority.Default | PrefetchPriority.Intent\n) {\n // Ensures that app-router-instance is not compiled in the server bundle\n if (typeof window !== 'undefined') {\n const existingPrefetchTask = instance.prefetchTask\n\n if (!instance.isVisible) {\n // Cancel any in-progress prefetch task. (If it already finished then this\n // is a no-op.)\n if (existingPrefetchTask !== null) {\n cancelPrefetchTask(existingPrefetchTask)\n }\n // We don't need to reset the prefetchTask to null upon cancellation; an\n // old task object can be rescheduled with reschedulePrefetchTask. This is a\n // micro-optimization but also makes the code simpler (don't need to\n // worry about whether an old task object is stale).\n return\n }\n\n const { getCurrentAppRouterState } =\n require('./app-router-instance') as typeof import('./app-router-instance')\n\n const appRouterState = getCurrentAppRouterState()\n if (appRouterState !== null) {\n const treeAtTimeOfPrefetch = appRouterState.tree\n if (existingPrefetchTask === null) {\n // Initiate a prefetch task.\n const nextUrl = appRouterState.nextUrl\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)\n instance.prefetchTask = scheduleSegmentPrefetchTask(\n cacheKey,\n treeAtTimeOfPrefetch,\n instance.fetchStrategy,\n priority,\n null\n )\n } else {\n // We already have an old task object that we can reschedule. This is\n // effectively the same as canceling the old task and creating a new one.\n reschedulePrefetchTask(\n existingPrefetchTask,\n treeAtTimeOfPrefetch,\n instance.fetchStrategy,\n priority\n )\n }\n }\n }\n}\n\nexport function pingVisibleLinks(\n nextUrl: string | null,\n tree: FlightRouterState\n) {\n // For each currently visible link, cancel the existing prefetch task (if it\n // exists) and schedule a new one. This is effectively the same as if all the\n // visible links left and then re-entered the viewport.\n //\n // This is called when the Next-Url or the base tree changes, since those\n // may affect the result of a prefetch task. It's also called after a\n // cache invalidation.\n for (const instance of prefetchableAndVisible) {\n const task = instance.prefetchTask\n if (task !== null && !isPrefetchTaskDirty(task, nextUrl, tree)) {\n // The cache has not been invalidated, and none of the inputs have\n // changed. Bail out.\n continue\n }\n // Something changed. Cancel the existing prefetch task and schedule a\n // new one.\n if (task !== null) {\n cancelPrefetchTask(task)\n }\n const cacheKey = createCacheKey(instance.prefetchHref, nextUrl)\n instance.prefetchTask = scheduleSegmentPrefetchTask(\n cacheKey,\n tree,\n instance.fetchStrategy,\n PrefetchPriority.Default,\n null\n )\n }\n}\n","import { parsePath } from './parse-path'\n\n/**\n * Checks if a given path starts with a given prefix. It ensures it matches\n * exactly without containing extra chars. e.g. prefix /docs should replace\n * for /docs, /docs/, /docs/a but not /docsss\n * @param path The path to check.\n * @param prefix The prefix to check against.\n */\nexport function pathHasPrefix(path: string, prefix: string) {\n if (typeof path !== 'string') {\n return false\n }\n\n const { pathname } = parsePath(path)\n return pathname === prefix || pathname.startsWith(prefix + '/')\n}\n","import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix'\n\nconst basePath = (process.env.__NEXT_ROUTER_BASEPATH as string) || ''\n\nexport function hasBasePath(path: string): boolean {\n return pathHasPrefix(path, basePath)\n}\n","import { isAbsoluteUrl, getLocationOrigin } from '../../utils'\nimport { hasBasePath } from '../../../../client/has-base-path'\n\n/**\n * Detects whether a given url is routable by the Next.js router (browser only).\n */\nexport function isLocalURL(url: string): boolean {\n // prevent a hydration mismatch on href for url with anchor refs\n if (!isAbsoluteUrl(url)) return true\n try {\n // absolute urls can be local if they are on the same origin\n const locationOrigin = getLocationOrigin()\n const resolved = new URL(url, locationOrigin)\n return resolved.origin === locationOrigin && hasBasePath(resolved.pathname)\n } catch (_) {\n return false\n }\n}\n","let errorOnce = (_: string) => {}\nif (process.env.NODE_ENV !== 'production') {\n const errors = new Set<string>()\n errorOnce = (msg: string) => {\n if (!errors.has(msg)) {\n console.error(msg)\n }\n errors.add(msg)\n }\n}\n\nexport { errorOnce }\n","'use client'\n\nimport React, { createContext, useContext, useOptimistic, useRef } from 'react'\nimport type { UrlObject } from 'url'\nimport { formatUrl } from '../../shared/lib/router/utils/format-url'\nimport { AppRouterContext } from '../../shared/lib/app-router-context.shared-runtime'\nimport { useMergedRef } from '../use-merged-ref'\nimport { isAbsoluteUrl } from '../../shared/lib/utils'\nimport { addBasePath } from '../add-base-path'\nimport { warnOnce } from '../../shared/lib/utils/warn-once'\nimport { ScrollBehavior } from '../components/router-reducer/router-reducer-types'\nimport type { PENDING_LINK_STATUS } from '../components/links'\nimport {\n IDLE_LINK_STATUS,\n mountLinkInstance,\n onNavigationIntent,\n unmountLinkForCurrentNavigation,\n unmountPrefetchableInstance,\n type LinkInstance,\n} from '../components/links'\nimport { isLocalURL } from '../../shared/lib/router/utils/is-local-url'\nimport {\n FetchStrategy,\n type PrefetchTaskFetchStrategy,\n} from '../components/segment-cache/types'\nimport { errorOnce } from '../../shared/lib/utils/error-once'\n\ntype Url = string | UrlObject\ntype RequiredKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? never : K\n}[keyof T]\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never\n}[keyof T]\n\ntype OnNavigateEventHandler = (event: { preventDefault: () => void }) => void\n\ntype InternalLinkProps = {\n /**\n * **Required**. The path or URL to navigate to. It can also be an object (similar to `URL`).\n *\n * @example\n * ```tsx\n * // Navigate to /dashboard:\n * <Link href=\"/dashboard\">Dashboard</Link>\n *\n * // Navigate to /about?name=test:\n * <Link href={{ pathname: '/about', query: { name: 'test' } }}>\n * About\n * </Link>\n * ```\n *\n * @remarks\n * - For external URLs, use a fully qualified URL such as `https://...`.\n * - In the App Router, dynamic routes must not include bracketed segments in `href`.\n */\n href: Url\n\n /**\n * @deprecated v10.0.0: `href` props pointing to a dynamic route are\n * automatically resolved and no longer require the `as` prop.\n */\n as?: Url\n\n /**\n * Replace the current `history` state instead of adding a new URL into the stack.\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/about\" replace>\n * About (replaces the history state)\n * </Link>\n * ```\n */\n replace?: boolean\n\n /**\n * Whether to override the default scroll behavior. If `true`, Next.js attempts to maintain\n * the scroll position if the newly navigated page is still visible. If not, it scrolls to the top.\n *\n * If `false`, Next.js will not modify the scroll behavior at all.\n *\n * @defaultValue `true`\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" scroll={false}>\n * No auto scroll\n * </Link>\n * ```\n */\n scroll?: boolean\n\n /**\n * Update the path of the current page without rerunning data fetching methods\n * like `getStaticProps`, `getServerSideProps`, or `getInitialProps`.\n *\n * @remarks\n * `shallow` only applies to the Pages Router. For the App Router, see the\n * [following documentation](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#using-the-native-history-api).\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/blog\" shallow>\n * Shallow navigation\n * </Link>\n * ```\n */\n shallow?: boolean\n\n /**\n * Forces `Link` to pass its `href` to the child component. Useful if the child is a custom\n * component that wraps an `<a>` tag, or if you're using certain styling libraries.\n *\n * @defaultValue `false`\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" passHref legacyBehavior>\n * <MyStyledAnchor>Dashboard</MyStyledAnchor>\n * </Link>\n * ```\n */\n passHref?: boolean\n\n /**\n * Prefetch the page in the background.\n * Any `<Link />` that is in the viewport (initially or through scroll) will be prefetched.\n * Prefetch can be disabled by passing `prefetch={false}`.\n *\n * @remarks\n * Prefetching is only enabled in production.\n *\n * - In the **App Router**:\n * - `\"auto\"`, `null`, `undefined` (default): Prefetch behavior depends on static vs dynamic routes:\n * - Static routes: fully prefetched\n * - Dynamic routes: partial prefetch to the nearest segment with a `loading.js`\n * - `true`: Always prefetch the full route and data.\n * - `false`: Disable prefetching on both viewport and hover.\n * - In the **Pages Router**:\n * - `true` (default): Prefetches the route and data in the background on viewport or hover.\n * - `false`: Prefetch only on hover, not on viewport.\n *\n * @defaultValue `true` (Pages Router) or `null` (App Router)\n *\n * @example\n * ```tsx\n * <Link href=\"/dashboard\" prefetch={false}>\n * Dashboard\n * </Link>\n * ```\n */\n prefetch?: boolean | 'auto' | null\n\n /**\n * (unstable) Switch to a full prefetch on hover. Effectively the same as\n * updating the prefetch prop to `true` in a mouse event.\n */\n unstable_dynamicOnHover?: boolean\n\n /**\n * The active locale is automatically prepended in the Pages Router. `locale` allows for providing\n * a different locale, or can be set to `false` to opt out of automatic locale behavior.\n *\n * @remarks\n * Note: locale only applies in the Pages Router and is ignored in the App Router.\n *\n * @example\n * ```tsx\n * // Use the 'fr' locale:\n * <Link href=\"/about\" locale=\"fr\">\n * About (French)\n * </Link>\n *\n * // Disable locale prefix:\n * <Link href=\"/about\" locale={false}>\n * About (no locale prefix)\n * </Link>\n * ```\n */\n locale?: string | false\n\n /**\n * Enable legacy link behavior.\n *\n * @deprecated This will be removed in a future version\n * @defaultValue `false`\n * @see https://github.com/vercel/next.js/commit/489e65ed98544e69b0afd7e0cfc3f9f6c2b803b7\n */\n legacyBehavior?: boolean\n\n /**\n * Optional event handler for when the mouse pointer is moved onto the `<Link>`.\n */\n onMouseEnter?: React.MouseEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is touched.\n */\n onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is clicked.\n */\n onClick?: React.MouseEventHandler<HTMLAnchorElement>\n\n /**\n * Optional event handler for when the `<Link>` is navigated.\n */\n onNavigate?: OnNavigateEventHandler\n\n /**\n * Transition types to apply when navigating. These types are passed to\n * [`React.addTransitionType`](https://react.dev/reference/react/addTransitionType)\n * inside the navigation transition, enabling\n * [`<ViewTransition>`](https://react.dev/reference/react/ViewTransition) components\n * to apply different animations based on the type of navigation.\n *\n * @example\n * ```tsx\n * <Link href=\"/about\" transitionTypes={['slide-in']}>About</Link>\n * ```\n */\n transitionTypes?: string[]\n}\n\n// TODO-APP: Include the full set of Anchor props\n// adding this to the publicly exported type currently breaks existing apps\n\n// `RouteInferType` is a stub here to avoid breaking `typedRoutes` when the type\n// isn't generated yet. It will be replaced when type generation runs.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport type LinkProps<RouteInferType = any> = InternalLinkProps\ntype LinkPropsRequired = RequiredKeys<LinkProps>\ntype LinkPropsOptional = OptionalKeys<Omit<InternalLinkProps, 'locale'>>\n\nfunction isModifiedEvent(event: React.MouseEvent): boolean {\n const eventTarget = event.currentTarget as HTMLAnchorElement | SVGAElement\n const target = eventTarget.getAttribute('target')\n return (\n (target && target !== '_self') ||\n event.metaKey ||\n event.ctrlKey ||\n event.shiftKey ||\n event.altKey || // triggers resource download\n (event.nativeEvent && event.nativeEvent.which === 2)\n )\n}\n\nfunction linkClicked(\n e: React.MouseEvent,\n href: string,\n linkInstanceRef: React.RefObject<LinkInstance | null>,\n replace?: boolean,\n scroll?: boolean,\n onNavigate?: OnNavigateEventHandler,\n transitionTypes?: string[]\n): void {\n if (typeof window !== 'undefined') {\n const { nodeName } = e.currentTarget\n\n // anchors inside an svg have a lowercase nodeName\n const isAnchorNodeName = nodeName.toUpperCase() === 'A'\n if (\n (isAnchorNodeName && isModifiedEvent(e)) ||\n e.currentTarget.hasAttribute('download')\n ) {\n // ignore click for browser’s default behavior\n return\n }\n\n if (!isLocalURL(href)) {\n if (replace) {\n // browser default behavior does not replace the history state\n // so we need to do it manually\n e.preventDefault()\n location.replace(href)\n }\n\n // ignore click for browser’s default behavior\n return\n }\n\n e.preventDefault()\n\n if (onNavigate) {\n let isDefaultPrevented = false\n\n onNavigate({\n preventDefault: () => {\n isDefaultPrevented = true\n },\n })\n\n if (isDefaultPrevented) {\n return\n }\n }\n\n const { dispatchNavigateAction } =\n require('../components/app-router-instance') as typeof import('../components/app-router-instance')\n\n React.startTransition(() => {\n dispatchNavigateAction(\n href,\n replace ? 'replace' : 'push',\n scroll === false ? ScrollBehavior.NoScroll : ScrollBehavior.Default,\n linkInstanceRef.current,\n transitionTypes\n )\n })\n }\n}\n\nfunction formatStringOrUrl(urlObjOrString: UrlObject | string): string {\n if (typeof urlObjOrString === 'string') {\n return urlObjOrString\n }\n\n return formatUrl(urlObjOrString)\n}\n\n/**\n * A React component that extends the HTML `<a>` element to provide\n * [prefetching](https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating#2-prefetching)\n * and client-side navigation. This is the primary way to navigate between routes in Next.js.\n *\n * @remarks\n * - Prefetching is only enabled in production.\n *\n * @see https://nextjs.org/docs/app/api-reference/components/link\n */\nexport default function LinkComponent(\n props: LinkProps & {\n children: React.ReactNode\n ref: React.Ref<HTMLAnchorElement>\n }\n) {\n const [linkStatus, setOptimisticLinkStatus] = useOptimistic(IDLE_LINK_STATUS)\n\n let children: React.ReactNode\n\n const linkInstanceRef = useRef<LinkInstance | null>(null)\n\n const {\n href: hrefProp,\n as: asProp,\n children: childrenProp,\n prefetch: prefetchProp = null,\n passHref,\n replace,\n shallow,\n scroll,\n onClick,\n onMouseEnter: onMouseEnterProp,\n onTouchStart: onTouchStartProp,\n legacyBehavior = false,\n onNavigate,\n transitionTypes,\n ref: forwardedRef,\n unstable_dynamicOnHover,\n ...restProps\n } = props\n\n children = childrenProp\n\n if (\n legacyBehavior &&\n (typeof children === 'string' || typeof children === 'number')\n ) {\n children = <a>{children}</a>\n }\n\n const router = React.useContext(AppRouterContext)\n\n const prefetchEnabled = prefetchProp !== false\n\n const fetchStrategy =\n prefetchProp !== false\n ? getFetchStrategyFromPrefetchProp(prefetchProp)\n : // TODO: it makes no sense to assign a fetchStrategy when prefetching is disabled.\n FetchStrategy.PPR\n\n if (process.env.NODE_ENV !== 'production') {\n function createPropError(args: {\n key: string\n expected: string\n actual: string\n }) {\n return new Error(\n `Failed prop type: The prop \\`${args.key}\\` expects a ${args.expected} in \\`<Link>\\`, but got \\`${args.actual}\\` instead.` +\n (typeof window !== 'undefined'\n ? \"\\nOpen your browser's console to view the Component stack trace.\"\n : '')\n )\n }\n\n // TypeScript trick for type-guarding:\n const requiredPropsGuard: Record<LinkPropsRequired, true> = {\n href: true,\n } as const\n const requiredProps: LinkPropsRequired[] = Object.keys(\n requiredPropsGuard\n ) as LinkPropsRequired[]\n requiredProps.forEach((key: LinkPropsRequired) => {\n if (key === 'href') {\n if (\n props[key] == null ||\n (typeof props[key] !== 'string' && typeof props[key] !== 'object')\n ) {\n throw createPropError({\n key,\n expected: '`string` or `object`',\n actual: props[key] === null ? 'null' : typeof props[key],\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n const _: never = key\n }\n })\n\n // TypeScript trick for type-guarding:\n const optionalPropsGuard: Record<LinkPropsOptional, true> = {\n as: true,\n replace: true,\n scroll: true,\n shallow: true,\n passHref: true,\n prefetch: true,\n unstable_dynamicOnHover: true,\n onClick: true,\n onMouseEnter: true,\n onTouchStart: true,\n legacyBehavior: true,\n onNavigate: true,\n transitionTypes: true,\n } as const\n const optionalProps: LinkPropsOptional[] = Object.keys(\n optionalPropsGuard\n ) as LinkPropsOptional[]\n optionalProps.forEach((key: LinkPropsOptional) => {\n const valType = typeof props[key]\n\n if (key === 'as') {\n if (props[key] && valType !== 'string' && valType !== 'object') {\n throw createPropError({\n key,\n expected: '`string` or `object`',\n actual: valType,\n })\n }\n } else if (\n key === 'onClick' ||\n key === 'onMouseEnter' ||\n key === 'onTouchStart' ||\n key === 'onNavigate'\n ) {\n if (props[key] && valType !== 'function') {\n throw createPropError({\n key,\n expected: '`function`',\n actual: valType,\n })\n }\n } else if (\n key === 'replace' ||\n key === 'scroll' ||\n key === 'shallow' ||\n key === 'passHref' ||\n key === 'legacyBehavior' ||\n key === 'unstable_dynamicOnHover'\n ) {\n if (props[key] != null && valType !== 'boolean') {\n throw createPropError({\n key,\n expected: '`boolean`',\n actual: valType,\n })\n }\n } else if (key === 'prefetch') {\n if (\n props[key] != null &&\n valType !== 'boolean' &&\n props[key] !== 'auto'\n ) {\n throw createPropError({\n key,\n expected: '`boolean | \"auto\"`',\n actual: valType,\n })\n }\n } else if (key === 'transitionTypes') {\n if (props[key] != null && !Array.isArray(props[key])) {\n throw createPropError({\n key,\n expected: '`string[]`',\n actual: valType,\n })\n }\n } else {\n // TypeScript trick for type-guarding:\n const _: never = key\n }\n })\n }\n\n const resolvedHref = asProp || hrefProp\n const formattedHref = formatStringOrUrl(resolvedHref)\n\n if (process.env.NODE_ENV !== 'production') {\n if (props.locale) {\n warnOnce(\n 'The `locale` prop is not supported in `next/link` while using the `app` router. Read more about app router internalization: https://nextjs.org/docs/app/building-your-application/routing/internationalization'\n )\n }\n if (!asProp) {\n let href: string | undefined\n if (typeof resolvedHref === 'string') {\n href = resolvedHref\n } else if (\n typeof resolvedHref === 'object' &&\n typeof resolvedHref.pathname === 'string'\n ) {\n href = resolvedHref.pathname\n }\n\n if (href) {\n const hasDynamicSegment = href\n .split('/')\n .some((segment) => segment.startsWith('[') && segment.endsWith(']'))\n\n if (hasDynamicSegment) {\n throw new Error(\n `Dynamic href \\`${href}\\` found in <Link> while using the \\`/app\\` router, this is not supported. Read more: https://nextjs.org/docs/messages/app-dir-dynamic-href`\n )\n }\n }\n }\n }\n\n // This will return the first child, if multiple are provided it will throw an error\n let child: any\n if (legacyBehavior) {\n if ((children as any)?.$$typeof === Symbol.for('react.lazy')) {\n throw new Error(\n `\\`<Link legacyBehavior>\\` received a direct child that is either a Server Component, or JSX that was loaded with React.lazy(). This is not supported. Either remove legacyBehavior, or make the direct child a Client Component that renders the Link's \\`<a>\\` tag.`\n )\n }\n\n if (process.env.NODE_ENV === 'development') {\n if (onClick) {\n console.warn(\n `\"onClick\" was passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but \"legacyBehavior\" was set. The legacy behavior requires onClick be set on the child of next/link`\n )\n }\n if (onMouseEnterProp) {\n console.warn(\n `\"onMouseEnter\" was passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but \"legacyBehavior\" was set. The legacy behavior requires onMouseEnter be set on the child of next/link`\n )\n }\n try {\n child = React.Children.only(children)\n } catch (err) {\n if (!children) {\n throw new Error(\n `No children were passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but one child is required https://nextjs.org/docs/messages/link-no-children`\n )\n }\n throw new Error(\n `Multiple children were passed to <Link> with \\`href\\` of \\`${formattedHref}\\` but only one child is supported https://nextjs.org/docs/messages/link-multiple-children` +\n (typeof window !== 'undefined'\n ? \" \\nOpen your browser's console to view the Component stack trace.\"\n : '')\n )\n }\n } else {\n child = React.Children.only(children)\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if ((children as any)?.type === 'a') {\n throw new Error(\n 'Invalid <Link> with <a> child. Please remove <a> or use <Link legacyBehavior>.\\nLearn more: https://nextjs.org/docs/messages/invalid-new-link-with-extra-anchor'\n )\n }\n }\n }\n\n const childRef: any = legacyBehavior\n ? child && typeof child === 'object' && child.ref\n : forwardedRef\n\n // Use a callback ref to attach an IntersectionObserver to the anchor tag on\n // mount. In the future we will also use this to keep track of all the\n // currently mounted <Link> instances, e.g. so we can re-prefetch them after\n // a revalidation or refresh.\n const observeLinkVisibilityOnMount = React.useCallback(\n (element: HTMLAnchorElement | SVGAElement) => {\n if (router !== null) {\n linkInstanceRef.current = mountLinkInstance(\n element,\n formattedHref,\n router,\n fetchStrategy,\n prefetchEnabled,\n setOptimisticLinkStatus\n )\n }\n\n return () => {\n if (linkInstanceRef.current) {\n unmountLinkForCurrentNavigation(linkInstanceRef.current)\n linkInstanceRef.current = null\n }\n unmountPrefetchableInstance(element)\n }\n },\n [\n prefetchEnabled,\n formattedHref,\n router,\n fetchStrategy,\n setOptimisticLinkStatus,\n ]\n )\n\n const mergedRef = useMergedRef(observeLinkVisibilityOnMount, childRef)\n\n const childProps: {\n onTouchStart?: React.TouchEventHandler<HTMLAnchorElement>\n onMouseEnter: React.MouseEventHandler<HTMLAnchorElement>\n onClick: React.MouseEventHandler<HTMLAnchorElement>\n href?: string\n ref?: any\n } = {\n ref: mergedRef,\n onClick(e) {\n if (process.env.NODE_ENV !== 'production') {\n if (!e) {\n throw new Error(\n `Component rendered inside next/link has to pass click event to \"onClick\" prop.`\n )\n }\n }\n\n if (!legacyBehavior && typeof onClick === 'function') {\n onClick(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onClick === 'function'\n ) {\n child.props.onClick(e)\n }\n\n if (!router) {\n return\n }\n if (e.defaultPrevented) {\n return\n }\n linkClicked(\n e,\n formattedHref,\n linkInstanceRef,\n replace,\n scroll,\n onNavigate,\n transitionTypes\n )\n },\n onMouseEnter(e) {\n if (!legacyBehavior && typeof onMouseEnterProp === 'function') {\n onMouseEnterProp(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onMouseEnter === 'function'\n ) {\n child.props.onMouseEnter(e)\n }\n\n if (!router) {\n return\n }\n if (!prefetchEnabled || process.env.NODE_ENV === 'development') {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(\n e.currentTarget as HTMLAnchorElement | SVGAElement,\n upgradeToDynamicPrefetch\n )\n },\n onTouchStart: process.env.__NEXT_LINK_NO_TOUCH_START\n ? undefined\n : function onTouchStart(e) {\n if (!legacyBehavior && typeof onTouchStartProp === 'function') {\n onTouchStartProp(e)\n }\n\n if (\n legacyBehavior &&\n child.props &&\n typeof child.props.onTouchStart === 'function'\n ) {\n child.props.onTouchStart(e)\n }\n\n if (!router) {\n return\n }\n if (!prefetchEnabled) {\n return\n }\n\n const upgradeToDynamicPrefetch = unstable_dynamicOnHover === true\n onNavigationIntent(\n e.currentTarget as HTMLAnchorElement | SVGAElement,\n upgradeToDynamicPrefetch\n )\n },\n }\n\n // If the url is absolute, we can bypass the logic to prepend the basePath.\n if (isAbsoluteUrl(formattedHref)) {\n childProps.href = formattedHref\n } else if (\n !legacyBehavior ||\n passHref ||\n (child.type === 'a' && !('href' in child.props))\n ) {\n childProps.href = addBasePath(formattedHref)\n }\n\n let link: React.ReactNode\n\n if (legacyBehavior) {\n if (process.env.NODE_ENV === 'development') {\n errorOnce(\n '`legacyBehavior` is deprecated and will be removed in a future ' +\n 'release. A codemod is available to upgrade your components:\\n\\n' +\n 'npx @next/codemod@latest new-link .\\n\\n' +\n 'Learn more: https://nextjs.org/docs/app/building-your-application/upgrading/codemods#remove-a-tags-from-link-components'\n )\n }\n link = React.cloneElement(child, childProps)\n } else {\n link = (\n <a {...restProps} {...childProps}>\n {children}\n </a>\n )\n }\n\n return (\n <LinkStatusContext.Provider value={linkStatus}>\n {link}\n </LinkStatusContext.Provider>\n )\n}\n\nconst LinkStatusContext = createContext<\n typeof PENDING_LINK_STATUS | typeof IDLE_LINK_STATUS\n>(IDLE_LINK_STATUS)\n\nexport const useLinkStatus = () => {\n return useContext(LinkStatusContext)\n}\n\nfunction getFetchStrategyFromPrefetchProp(\n prefetchProp: Exclude<LinkProps['prefetch'], undefined | false>\n): PrefetchTaskFetchStrategy {\n if (process.env.__NEXT_CACHE_COMPONENTS) {\n if (prefetchProp === true) {\n return FetchStrategy.Full\n }\n\n // `null` or `\"auto\"`: this is the default \"auto\" mode, where we will prefetch partially if the link is in the viewport.\n // This will also include invalid prop values that don't match the types specified here.\n // (although those should've been filtered out by prop validation in dev)\n prefetchProp satisfies null | 'auto'\n return FetchStrategy.PPR\n } else {\n return prefetchProp === null || prefetchProp === 'auto'\n ? // We default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.\n FetchStrategy.PPR\n : // In the old implementation without runtime prefetches, `prefetch={true}` forces all dynamic data to be prefetched.\n // To preserve backwards-compatibility, anything other than `false`, `null`, or `\"auto\"` results in a full prefetch.\n // (although invalid values should've been filtered out by prop validation in dev)\n FetchStrategy.Full\n }\n}\n","export class UnrecognizedActionError extends Error {\n constructor(...args: ConstructorParameters<typeof Error>) {\n super(...args)\n this.name = 'UnrecognizedActionError'\n }\n}\n\n/**\n * Check whether a server action call failed because the server action was not recognized by the server.\n * This can happen if the client and the server are not from the same deployment.\n *\n * Example usage:\n * ```ts\n * try {\n * await myServerAction();\n * } catch (err) {\n * if (unstable_isUnrecognizedActionError(err)) {\n * // The client is from a different deployment than the server.\n * // Reloading the page will fix this mismatch.\n * window.alert(\"Please refresh the page and try again\");\n * return;\n * }\n * }\n * ```\n * */\nexport function unstable_isUnrecognizedActionError(\n error: unknown\n): error is UnrecognizedActionError {\n return !!(\n error &&\n typeof error === 'object' &&\n error instanceof UnrecognizedActionError\n )\n}\n","/**\n * ReadonlyURLSearchParams implementation shared between client and server.\n * This file is intentionally not marked as 'use client' or 'use server'\n * so it can be imported by both environments.\n */\n\n/** @internal */\nclass ReadonlyURLSearchParamsError extends Error {\n constructor() {\n super(\n 'Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams'\n )\n }\n}\n\n/**\n * A read-only version of URLSearchParams that throws errors when mutation methods are called.\n * This ensures that the URLSearchParams returned by useSearchParams() cannot be mutated.\n */\nexport class ReadonlyURLSearchParams extends URLSearchParams {\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n append() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n delete() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n set() {\n throw new ReadonlyURLSearchParamsError()\n }\n /** @deprecated Method unavailable on `ReadonlyURLSearchParams`. Read more: https://nextjs.org/docs/app/api-reference/functions/use-search-params#updating-searchparams */\n sort() {\n throw new ReadonlyURLSearchParamsError()\n }\n}\n","export enum RedirectStatusCode {\n SeeOther = 303,\n TemporaryRedirect = 307,\n PermanentRedirect = 308,\n}\n","import { RedirectStatusCode } from './redirect-status-code'\n\nexport const REDIRECT_ERROR_CODE = 'NEXT_REDIRECT'\n\nexport type RedirectType = 'push' | 'replace'\n\nexport type RedirectError = Error & {\n digest: `${typeof REDIRECT_ERROR_CODE};${RedirectType};${string};${RedirectStatusCode};`\n}\n\n/**\n * Checks an error to determine if it's an error generated by the\n * `redirect(url)` helper.\n *\n * @param error the error that may reference a redirect error\n * @returns true if the error is a redirect error\n */\nexport function isRedirectError(error: unknown): error is RedirectError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n\n const digest = error.digest.split(';')\n const [errorCode, type] = digest\n const destination = digest.slice(2, -2).join(';')\n const status = digest.at(-2)\n\n const statusCode = Number(status)\n\n return (\n errorCode === REDIRECT_ERROR_CODE &&\n (type === 'replace' || type === 'push') &&\n typeof destination === 'string' &&\n !isNaN(statusCode) &&\n statusCode in RedirectStatusCode\n )\n}\n","import { RedirectStatusCode } from './redirect-status-code'\nimport {\n type RedirectType,\n type RedirectError,\n isRedirectError,\n REDIRECT_ERROR_CODE,\n} from './redirect-error'\n\nconst actionAsyncStorage =\n typeof window === 'undefined'\n ? (\n require('../../server/app-render/action-async-storage.external') as typeof import('../../server/app-render/action-async-storage.external')\n ).actionAsyncStorage\n : undefined\n\nexport function getRedirectError(\n url: string,\n type: RedirectType,\n statusCode: RedirectStatusCode = RedirectStatusCode.TemporaryRedirect\n): RedirectError {\n const error = new Error(REDIRECT_ERROR_CODE) as RedirectError\n error.digest = `${REDIRECT_ERROR_CODE};${type};${url};${statusCode};`\n return error\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler or Server Action, it will serve a 307/303 to the caller.\n * - In a Server Action, type defaults to 'push' and 'replace' elsewhere.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function redirect(\n /** The URL to redirect to */\n url: string,\n type?: RedirectType\n): never {\n type ??= actionAsyncStorage?.getStore()?.isAction ? 'push' : 'replace'\n\n throw getRedirectError(url, type, RedirectStatusCode.TemporaryRedirect)\n}\n\n/**\n * This function allows you to redirect the user to another URL. It can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a meta tag to redirect the user to the target page.\n * - In a Route Handler or Server Action, it will serve a 308/303 to the caller.\n *\n * Read more: [Next.js Docs: `redirect`](https://nextjs.org/docs/app/api-reference/functions/redirect)\n */\nexport function permanentRedirect(\n /** The URL to redirect to */\n url: string,\n type: RedirectType = 'replace'\n): never {\n throw getRedirectError(url, type, RedirectStatusCode.PermanentRedirect)\n}\n\n/**\n * Returns the encoded URL from the error if it's a RedirectError, null\n * otherwise. Note that this does not validate the URL returned.\n *\n * @param error the error that may be a redirect error\n * @return the url if the error was a redirect error\n */\nexport function getURLFromRedirectError(error: RedirectError): string\nexport function getURLFromRedirectError(error: unknown): string | null {\n if (!isRedirectError(error)) return null\n\n // Slices off the beginning of the digest that contains the code and the\n // separating ';'.\n return error.digest.split(';').slice(2, -2).join(';')\n}\n\nexport function getRedirectTypeFromError(error: RedirectError): RedirectType {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error')\n }\n\n return error.digest.split(';', 2)[1] as RedirectType\n}\n\nexport function getRedirectStatusCodeFromError(error: RedirectError): number {\n if (!isRedirectError(error)) {\n throw new Error('Not a redirect error')\n }\n\n return Number(error.digest.split(';').at(-2))\n}\n","export const HTTPAccessErrorStatus = {\n NOT_FOUND: 404,\n FORBIDDEN: 403,\n UNAUTHORIZED: 401,\n}\n\nconst ALLOWED_CODES = new Set(Object.values(HTTPAccessErrorStatus))\n\nexport const HTTP_ERROR_FALLBACK_ERROR_CODE = 'NEXT_HTTP_ERROR_FALLBACK'\n\nexport type HTTPAccessFallbackError = Error & {\n digest: `${typeof HTTP_ERROR_FALLBACK_ERROR_CODE};${string}`\n}\n\n/**\n * Checks an error to determine if it's an error generated by\n * the HTTP navigation APIs `notFound()`, `forbidden()` or `unauthorized()`.\n *\n * @param error the error that may reference a HTTP access error\n * @returns true if the error is a HTTP access error\n */\nexport function isHTTPAccessFallbackError(\n error: unknown\n): error is HTTPAccessFallbackError {\n if (\n typeof error !== 'object' ||\n error === null ||\n !('digest' in error) ||\n typeof error.digest !== 'string'\n ) {\n return false\n }\n const [prefix, httpStatus] = error.digest.split(';')\n\n return (\n prefix === HTTP_ERROR_FALLBACK_ERROR_CODE &&\n ALLOWED_CODES.has(Number(httpStatus))\n )\n}\n\nexport function getAccessFallbackHTTPStatus(\n error: HTTPAccessFallbackError\n): number {\n const httpStatus = error.digest.split(';')[1]\n return Number(httpStatus)\n}\n\nexport function getAccessFallbackErrorTypeByStatus(\n status: number\n): 'not-found' | 'forbidden' | 'unauthorized' | undefined {\n switch (status) {\n case 401:\n return 'unauthorized'\n case 403:\n return 'forbidden'\n case 404:\n return 'not-found'\n default:\n return\n }\n}\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n/**\n * This function allows you to render the [not-found.js file](https://nextjs.org/docs/app/api-reference/file-conventions/not-found)\n * within a route segment as well as inject a tag.\n *\n * `notFound()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * - In a Server Component, this will insert a `<meta name=\"robots\" content=\"noindex\" />` meta tag and set the status code to 404.\n * - In a Route Handler or Server Action, it will serve a 404 to the caller.\n *\n * Read more: [Next.js Docs: `notFound`](https://nextjs.org/docs/app/api-reference/functions/not-found)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};404`\n\nexport function notFound(): never {\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n\n throw error\n}\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `forbidden` docs\n/**\n * @experimental\n * This function allows you to render the [forbidden.js file](https://nextjs.org/docs/app/api-reference/file-conventions/forbidden)\n * within a route segment as well as inject a tag.\n *\n * `forbidden()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n * Read more: [Next.js Docs: `forbidden`](https://nextjs.org/docs/app/api-reference/functions/forbidden)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};403`\n\nexport function forbidden(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`forbidden()\\` is experimental and only allowed to be enabled when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n","import {\n HTTP_ERROR_FALLBACK_ERROR_CODE,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\n\n// TODO: Add `unauthorized` docs\n/**\n * @experimental\n * This function allows you to render the [unauthorized.js file](https://nextjs.org/docs/app/api-reference/file-conventions/unauthorized)\n * within a route segment as well as inject a tag.\n *\n * `unauthorized()` can be used in\n * [Server Components](https://nextjs.org/docs/app/building-your-application/rendering/server-components),\n * [Route Handlers](https://nextjs.org/docs/app/building-your-application/routing/route-handlers), and\n * [Server Actions](https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations).\n *\n *\n * Read more: [Next.js Docs: `unauthorized`](https://nextjs.org/docs/app/api-reference/functions/unauthorized)\n */\n\nconst DIGEST = `${HTTP_ERROR_FALLBACK_ERROR_CODE};401`\n\nexport function unauthorized(): never {\n if (!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS) {\n throw new Error(\n `\\`unauthorized()\\` is experimental and only allowed to be used when \\`experimental.authInterrupts\\` is enabled.`\n )\n }\n\n const error = new Error(DIGEST) as HTTPAccessFallbackError\n ;(error as HTTPAccessFallbackError).digest = DIGEST\n throw error\n}\n","import { InvariantError } from '../../shared/lib/invariant-error'\nimport { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolvers'\n\nexport enum RenderStage {\n Before = 1,\n EarlyStatic = 2,\n Static = 3,\n EarlyRuntime = 4,\n Runtime = 5,\n Dynamic = 6,\n Abandoned = 7,\n}\n\nexport type AdvanceableRenderStage =\n | RenderStage.Static\n | RenderStage.EarlyRuntime\n | RenderStage.Runtime\n | RenderStage.Dynamic\n\nexport class StagedRenderingController {\n currentStage: RenderStage = RenderStage.Before\n\n syncInterruptReason: Error | null = null\n staticStageEndTime: number = Infinity\n runtimeStageEndTime: number = Infinity\n\n private staticStageListeners: Array<() => void> = []\n private earlyRuntimeStageListeners: Array<() => void> = []\n private runtimeStageListeners: Array<() => void> = []\n private dynamicStageListeners: Array<() => void> = []\n\n private staticStagePromise = createPromiseWithResolvers<void>()\n private earlyRuntimeStagePromise = createPromiseWithResolvers<void>()\n private runtimeStagePromise = createPromiseWithResolvers<void>()\n private dynamicStagePromise = createPromiseWithResolvers<void>()\n\n constructor(\n private abortSignal: AbortSignal | null,\n private abandonController: AbortController | null,\n private shouldTrackSyncIO: boolean\n ) {\n if (abortSignal) {\n abortSignal.addEventListener(\n 'abort',\n () => {\n // Reject all stage promises that haven't already been resolved.\n // If a promise was already resolved via advanceStage, the reject\n // is a no-op. The ignoreReject handler suppresses unhandled\n // rejection warnings for promises that no one is awaiting.\n const { reason } = abortSignal\n this.staticStagePromise.promise.catch(ignoreReject)\n this.staticStagePromise.reject(reason)\n this.earlyRuntimeStagePromise.promise.catch(ignoreReject)\n this.earlyRuntimeStagePromise.reject(reason)\n this.runtimeStagePromise.promise.catch(ignoreReject)\n this.runtimeStagePromise.reject(reason)\n this.dynamicStagePromise.promise.catch(ignoreReject)\n this.dynamicStagePromise.reject(reason)\n },\n { once: true }\n )\n }\n\n if (abandonController) {\n abandonController.signal.addEventListener(\n 'abort',\n () => {\n this.abandonRender()\n },\n { once: true }\n )\n }\n }\n\n onStage(stage: AdvanceableRenderStage, callback: () => void) {\n if (this.currentStage >= stage) {\n callback()\n } else if (stage === RenderStage.Static) {\n this.staticStageListeners.push(callback)\n } else if (stage === RenderStage.EarlyRuntime) {\n this.earlyRuntimeStageListeners.push(callback)\n } else if (stage === RenderStage.Runtime) {\n this.runtimeStageListeners.push(callback)\n } else if (stage === RenderStage.Dynamic) {\n this.dynamicStageListeners.push(callback)\n } else {\n // This should never happen\n throw new InvariantError(`Invalid render stage: ${stage}`)\n }\n }\n\n shouldTrackSyncInterrupt(): boolean {\n if (!this.shouldTrackSyncIO) {\n return false\n }\n\n switch (this.currentStage) {\n case RenderStage.Before:\n // If we haven't started the render yet, it can't be interrupted.\n return false\n case RenderStage.EarlyStatic:\n case RenderStage.Static:\n return true\n case RenderStage.EarlyRuntime:\n // EarlyRuntime is for runtime-prefetchable segments. Sync IO\n // should error because it would abort a runtime prefetch.\n return true\n case RenderStage.Runtime:\n // Runtime is for non-prefetchable segments. Sync IO is fine there\n // because in practice this segment will never be runtime prefetched\n return false\n case RenderStage.Dynamic:\n case RenderStage.Abandoned:\n return false\n default:\n return false\n }\n }\n\n syncInterruptCurrentStageWithReason(reason: Error) {\n if (this.currentStage === RenderStage.Before) {\n return\n }\n\n // If the render has already been abandoned, there's nothing to interrupt.\n if (this.currentStage === RenderStage.Abandoned) {\n return\n }\n\n // If Sync IO occurs during an abandonable render, we trigger the abandon.\n // The abandon listener will call abandonRender which advances through\n // stages to let caches fill before marking as Abandoned.\n if (this.abandonController) {\n this.abandonController.abort()\n return\n }\n\n if (this.abortSignal) {\n // If this is an abortable render, we capture the interruption reason and stop advancing.\n // We don't release any more promises.\n // The caller is expected to abort the signal.\n this.syncInterruptReason = reason\n this.currentStage = RenderStage.Abandoned\n return\n }\n\n // If we're in a non-abandonable & non-abortable render,\n // we need to advance to the Dynamic stage and capture the interruption reason.\n // (in dev, this will be the restarted render)\n switch (this.currentStage) {\n case RenderStage.EarlyStatic:\n case RenderStage.Static:\n case RenderStage.EarlyRuntime: {\n // EarlyRuntime is for runtime-prefetchable segments. Sync IO here\n // means the prefetch would be aborted too early.\n this.syncInterruptReason = reason\n this.advanceStage(RenderStage.Dynamic)\n return\n }\n case RenderStage.Runtime: {\n // canSyncInterrupt returns false for Runtime, so we should\n // never get here. Defensive no-op.\n return\n }\n case RenderStage.Dynamic:\n default:\n }\n }\n\n getSyncInterruptReason() {\n return this.syncInterruptReason\n }\n\n getStaticStageEndTime() {\n return this.staticStageEndTime\n }\n\n getRuntimeStageEndTime() {\n return this.runtimeStageEndTime\n }\n\n private abandonRender() {\n // In staged rendering, only the initial render is abandonable.\n // We can abandon the initial render if\n // 1. We notice a cache miss, and need to wait for caches to fill\n // 2. A sync IO error occurs, and the render should be interrupted\n // (this might be a lazy intitialization of a module,\n // so we still want to restart in this case and see if it still occurs)\n // In either case, we'll be doing another render after this one,\n // so we only want to unblock the next stage, not Dynamic, because\n // unblocking the dynamic stage would likely lead to wasted (uncached) IO.\n const { currentStage } = this\n switch (currentStage) {\n case RenderStage.EarlyStatic: {\n this.resolveStaticStage()\n }\n // intentional fallthrough\n case RenderStage.Static: {\n this.resolveEarlyRuntimeStage()\n }\n // intentional fallthrough\n case RenderStage.EarlyRuntime: {\n this.resolveRuntimeStage()\n }\n // intentional fallthrough\n case RenderStage.Runtime: {\n this.currentStage = RenderStage.Abandoned\n return\n }\n case RenderStage.Dynamic:\n case RenderStage.Before:\n case RenderStage.Abandoned:\n break\n default: {\n currentStage satisfies never\n }\n }\n }\n\n advanceStage(\n stage:\n | RenderStage.EarlyStatic\n | RenderStage.Static\n | RenderStage.EarlyRuntime\n | RenderStage.Runtime\n | RenderStage.Dynamic\n ) {\n // If we're already at the target stage or beyond, do nothing.\n // (this can happen e.g. if sync IO advanced us to the dynamic stage)\n if (stage <= this.currentStage) {\n return\n }\n\n let currentStage = this.currentStage\n this.currentStage = stage\n\n if (currentStage < RenderStage.Static && stage >= RenderStage.Static) {\n this.resolveStaticStage()\n }\n if (\n currentStage < RenderStage.EarlyRuntime &&\n stage >= RenderStage.EarlyRuntime\n ) {\n this.resolveEarlyRuntimeStage()\n }\n if (currentStage < RenderStage.Runtime && stage >= RenderStage.Runtime) {\n this.staticStageEndTime = performance.now() + performance.timeOrigin\n this.resolveRuntimeStage()\n }\n if (currentStage < RenderStage.Dynamic && stage >= RenderStage.Dynamic) {\n this.runtimeStageEndTime = performance.now() + performance.timeOrigin\n this.resolveDynamicStage()\n return\n }\n }\n\n /** Fire the `onStage` listeners for the static stage and unblock any promises waiting for it. */\n private resolveStaticStage() {\n const staticListeners = this.staticStageListeners\n for (let i = 0; i < staticListeners.length; i++) {\n staticListeners[i]()\n }\n staticListeners.length = 0\n this.staticStagePromise.resolve()\n }\n\n /** Fire the `onStage` listeners for the early runtime stage and unblock any promises waiting for it. */\n private resolveEarlyRuntimeStage() {\n const earlyRuntimeListeners = this.earlyRuntimeStageListeners\n for (let i = 0; i < earlyRuntimeListeners.length; i++) {\n earlyRuntimeListeners[i]()\n }\n earlyRuntimeListeners.length = 0\n this.earlyRuntimeStagePromise.resolve()\n }\n\n /** Fire the `onStage` listeners for the runtime stage and unblock any promises waiting for it. */\n private resolveRuntimeStage() {\n const runtimeListeners = this.runtimeStageListeners\n for (let i = 0; i < runtimeListeners.length; i++) {\n runtimeListeners[i]()\n }\n runtimeListeners.length = 0\n this.runtimeStagePromise.resolve()\n }\n\n /** Fire the `onStage` listeners for the dynamic stage and unblock any promises waiting for it. */\n private resolveDynamicStage() {\n const dynamicListeners = this.dynamicStageListeners\n for (let i = 0; i < dynamicListeners.length; i++) {\n dynamicListeners[i]()\n }\n dynamicListeners.length = 0\n this.dynamicStagePromise.resolve()\n }\n\n private getStagePromise(stage: AdvanceableRenderStage): Promise<void> {\n switch (stage) {\n case RenderStage.Static: {\n return this.staticStagePromise.promise\n }\n case RenderStage.EarlyRuntime: {\n return this.earlyRuntimeStagePromise.promise\n }\n case RenderStage.Runtime: {\n return this.runtimeStagePromise.promise\n }\n case RenderStage.Dynamic: {\n return this.dynamicStagePromise.promise\n }\n default: {\n stage satisfies never\n throw new InvariantError(`Invalid render stage: ${stage}`)\n }\n }\n }\n\n waitForStage(stage: AdvanceableRenderStage) {\n return this.getStagePromise(stage)\n }\n\n delayUntilStage<T>(\n stage: AdvanceableRenderStage,\n displayName: string | undefined,\n resolvedValue: T\n ) {\n const ioTriggerPromise = this.getStagePromise(stage)\n\n const promise = makeDevtoolsIOPromiseFromIOTrigger(\n ioTriggerPromise,\n displayName,\n resolvedValue\n )\n\n // Analogously to `makeHangingPromise`, we might reject this promise if the signal is invoked.\n // (e.g. in the case where we don't want want the render to proceed to the dynamic stage and abort it).\n // We shouldn't consider this an unhandled rejection, so we attach a noop catch handler here to suppress this warning.\n if (this.abortSignal) {\n promise.catch(ignoreReject)\n }\n return promise\n }\n}\n\nfunction ignoreReject() {}\n\n// TODO(restart-on-cache-miss): the layering of `delayUntilStage`,\n// `makeDevtoolsIOPromiseFromIOTrigger` and and `makeDevtoolsIOAwarePromise`\n// is confusing, we should clean it up.\nfunction makeDevtoolsIOPromiseFromIOTrigger<T>(\n ioTrigger: Promise<any>,\n displayName: string | undefined,\n resolvedValue: T\n): Promise<T> {\n // If we create a `new Promise` and give it a displayName\n // (with no userspace code above us in the stack)\n // React Devtools will use it as the IO cause when determining \"suspended by\".\n // In particular, it should shadow any inner IO that resolved/rejected the promise\n // (in case of staged rendering, this will be the `setTimeout` that triggers the relevant stage)\n const promise = new Promise<T>((resolve, reject) => {\n ioTrigger.then(resolve.bind(null, resolvedValue), reject)\n })\n if (displayName !== undefined) {\n // @ts-expect-error\n promise.displayName = displayName\n }\n return promise\n}\n","import {\n RenderStage,\n type AdvanceableRenderStage,\n type StagedRenderingController,\n} from './app-render/staged-rendering'\nimport type {\n PrerenderStoreModernRuntime,\n RequestStore,\n} from './app-render/work-unit-async-storage.external'\n\nexport function isHangingPromiseRejectionError(\n err: unknown\n): err is HangingPromiseRejectionError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === HANGING_PROMISE_REJECTION\n}\n\nconst HANGING_PROMISE_REJECTION = 'HANGING_PROMISE_REJECTION'\n\nclass HangingPromiseRejectionError extends Error {\n public readonly digest = HANGING_PROMISE_REJECTION\n\n constructor(\n public readonly route: string,\n public readonly expression: string\n ) {\n super(\n `During prerendering, ${expression} rejects when the prerender is complete. Typically these errors are handled by React but if you move ${expression} to a different context by using \\`setTimeout\\`, \\`after\\`, or similar functions you may observe this error and you should handle it in that context. This occurred at route \"${route}\".`\n )\n }\n}\n\ntype AbortListeners = Array<(err: unknown) => void>\nconst abortListenersBySignal = new WeakMap<AbortSignal, AbortListeners>()\n\n/**\n * This function constructs a promise that will never resolve. This is primarily\n * useful for cacheComponents where we use promise resolution timing to determine which\n * parts of a render can be included in a prerender.\n *\n * @internal\n */\nexport function makeHangingPromise<T>(\n signal: AbortSignal,\n route: string,\n expression: string\n): Promise<T> {\n if (signal.aborted) {\n return Promise.reject(new HangingPromiseRejectionError(route, expression))\n } else {\n const hangingPromise = new Promise<T>((_, reject) => {\n const boundRejection = reject.bind(\n null,\n new HangingPromiseRejectionError(route, expression)\n )\n let currentListeners = abortListenersBySignal.get(signal)\n if (currentListeners) {\n currentListeners.push(boundRejection)\n } else {\n const listeners = [boundRejection]\n abortListenersBySignal.set(signal, listeners)\n signal.addEventListener(\n 'abort',\n () => {\n for (let i = 0; i < listeners.length; i++) {\n listeners[i]()\n }\n },\n { once: true }\n )\n }\n })\n // We are fine if no one actually awaits this promise. We shouldn't consider this an unhandled rejection so\n // we attach a noop catch handler here to suppress this warning. If you actually await somewhere or construct\n // your own promise out of it you'll need to ensure you handle the error when it rejects.\n hangingPromise.catch(ignoreReject)\n return hangingPromise\n }\n}\n\nfunction ignoreReject() {}\n\nexport function makeDevtoolsIOAwarePromise<T>(\n underlying: T,\n requestStore: RequestStore,\n stage: AdvanceableRenderStage\n): Promise<T> {\n if (requestStore.stagedRendering) {\n // We resolve each stage in a timeout, so React DevTools will pick this up as IO.\n return requestStore.stagedRendering.delayUntilStage(\n stage,\n undefined,\n underlying\n )\n }\n // in React DevTools if we resolve in a setTimeout we will observe\n // the promise resolution as something that can suspend a boundary or root.\n return new Promise<T>((resolve) => {\n // Must use setTimeout to be considered IO React DevTools. setImmediate will not work.\n setTimeout(() => {\n resolve(underlying)\n }, 0)\n })\n}\n\n/**\n * Returns the appropriate runtime stage for the current point in the render.\n * Runtime-prefetchable segments render in the early stages and should wait\n * for EarlyRuntime. Non-prefetchable segments render in the later stages\n * and should wait for Runtime.\n */\nexport function getRuntimeStage(\n stagedRendering: StagedRenderingController\n): RenderStage.EarlyRuntime | RenderStage.Runtime {\n if (\n stagedRendering.currentStage === RenderStage.EarlyStatic ||\n stagedRendering.currentStage === RenderStage.EarlyRuntime\n ) {\n return RenderStage.EarlyRuntime\n }\n return RenderStage.Runtime\n}\n\n/**\n * Delays until the appropriate runtime stage based on the current stage of\n * the rendering pipeline:\n *\n * - Early stages → wait for EarlyRuntime\n * (for runtime-prefetchable segments)\n * - Later stages → wait for Runtime\n * (for segments not using runtime prefetch)\n *\n * This ensures that cookies()/headers()/etc. resolve at the right time for\n * each segment type.\n */\nexport function delayUntilRuntimeStage<T>(\n prerenderStore: PrerenderStoreModernRuntime,\n result: Promise<T>\n): Promise<T> {\n const { stagedRendering } = prerenderStore\n if (!stagedRendering) {\n return result\n }\n return stagedRendering\n .waitForStage(getRuntimeStage(stagedRendering))\n .then(() => result)\n}\n","const REACT_POSTPONE_TYPE: symbol = Symbol.for('react.postpone')\n\nexport function isPostpone(error: any): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n error.$$typeof === REACT_POSTPONE_TYPE\n )\n}\n","// This has to be a shared module which is shared between client component error boundary and dynamic component\nconst BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'\n\n/** An error that should be thrown when we want to bail out to client-side rendering. */\nexport class BailoutToCSRError extends Error {\n public readonly digest = BAILOUT_TO_CSR\n\n constructor(public readonly reason: string) {\n super(`Bail out to client-side rendering: ${reason}`)\n }\n}\n\n/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */\nexport function isBailoutToCSRError(err: unknown): err is BailoutToCSRError {\n if (typeof err !== 'object' || err === null || !('digest' in err)) {\n return false\n }\n\n return err.digest === BAILOUT_TO_CSR\n}\n","import {\n isHTTPAccessFallbackError,\n type HTTPAccessFallbackError,\n} from './http-access-fallback/http-access-fallback'\nimport { isRedirectError, type RedirectError } from './redirect-error'\n\n/**\n * Returns true if the error is a navigation signal error. These errors are\n * thrown by user code to perform navigation operations and interrupt the React\n * render.\n */\nexport function isNextRouterError(\n error: unknown\n): error is RedirectError | HTTPAccessFallbackError {\n return isRedirectError(error) || isHTTPAccessFallbackError(error)\n}\n","const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE'\n\nexport class DynamicServerError extends Error {\n digest: typeof DYNAMIC_ERROR_CODE = DYNAMIC_ERROR_CODE\n\n constructor(public readonly description: string) {\n super(`Dynamic server usage: ${description}`)\n }\n}\n\nexport function isDynamicServerError(err: unknown): err is DynamicServerError {\n if (\n typeof err !== 'object' ||\n err === null ||\n !('digest' in err) ||\n typeof err.digest !== 'string'\n ) {\n return false\n }\n\n return err.digest === DYNAMIC_ERROR_CODE\n}\n","const NEXT_STATIC_GEN_BAILOUT = 'NEXT_STATIC_GEN_BAILOUT'\n\nexport class StaticGenBailoutError extends Error {\n public readonly code = NEXT_STATIC_GEN_BAILOUT\n}\n\nexport function isStaticGenBailoutError(\n error: unknown\n): error is StaticGenBailoutError {\n if (typeof error !== 'object' || error === null || !('code' in error)) {\n return false\n }\n\n return error.code === NEXT_STATIC_GEN_BAILOUT\n}\n","export const METADATA_BOUNDARY_NAME = '__next_metadata_boundary__'\nexport const VIEWPORT_BOUNDARY_NAME = '__next_viewport_boundary__'\nexport const OUTLET_BOUNDARY_NAME = '__next_outlet_boundary__'\nexport const ROOT_LAYOUT_BOUNDARY_NAME = '__next_root_layout_boundary__'\n","export type ScheduledFn<T = void> = () => T | PromiseLike<T>\nexport type SchedulerFn<T = void> = (cb: ScheduledFn<T>) => void\n\n/**\n * Schedules a function to be called on the next tick after the other promises\n * have been resolved.\n *\n * @param cb the function to schedule\n */\nexport const scheduleOnNextTick = (cb: ScheduledFn<void>) => {\n // We use Promise.resolve().then() here so that the operation is scheduled at\n // the end of the promise job queue, we then add it to the next process tick\n // to ensure it's evaluated afterwards.\n //\n // This was inspired by the implementation of the DataLoader interface: https://github.com/graphql/dataloader/blob/d336bd15282664e0be4b4a657cb796f09bafbc6b/src/index.js#L213-L255\n //\n Promise.resolve().then(() => {\n if (process.env.NEXT_RUNTIME === 'edge') {\n setTimeout(cb, 0)\n } else {\n process.nextTick(cb)\n }\n })\n}\n\n/**\n * Schedules a function to be called using `setImmediate` or `setTimeout` if\n * `setImmediate` is not available (like in the Edge runtime).\n *\n * @param cb the function to schedule\n */\nexport const scheduleImmediate = (cb: ScheduledFn<void>): void => {\n if (process.env.NEXT_RUNTIME === 'edge') {\n setTimeout(cb, 0)\n } else {\n setImmediate(cb)\n }\n}\n\n/**\n * returns a promise than resolves in a future task. There is no guarantee that the task it resolves in\n * will be the next task but if you await it you can at least be sure that the current task is over and\n * most usefully that the entire microtask queue of the current task has been emptied.\n */\nexport function atLeastOneTask() {\n return new Promise<void>((resolve) => scheduleImmediate(resolve))\n}\n\n/**\n * This utility function is extracted to make it easier to find places where we are doing\n * specific timing tricks to try to schedule work after React has rendered. This is especially\n * important at the moment because Next.js uses the edge builds of React which use setTimeout to\n * schedule work when you might expect that something like setImmediate would do the trick.\n *\n * Long term we should switch to the node versions of React rendering when possible and then\n * update this to use setImmediate rather than setTimeout\n */\nexport function waitAtLeastOneReactRenderTask(): Promise<void> {\n if (process.env.NEXT_RUNTIME === 'edge') {\n return new Promise((r) => setTimeout(r, 0))\n } else {\n return new Promise((r) => setImmediate(r))\n }\n}\n","export const INSTANT_VALIDATION_BOUNDARY_NAME =\n '__next_instant_validation_boundary__'\n","/**\n * The functions provided by this module are used to communicate certain properties\n * about the currently running code so that Next.js can make decisions on how to handle\n * the current execution in different rendering modes such as pre-rendering, resuming, and SSR.\n *\n * Today Next.js treats all code as potentially static. Certain APIs may only make sense when dynamically rendering.\n * Traditionally this meant deopting the entire render to dynamic however with PPR we can now deopt parts\n * of a React tree as dynamic while still keeping other parts static. There are really two different kinds of\n * Dynamic indications.\n *\n * The first is simply an intention to be dynamic. unstable_noStore is an example of this where\n * the currently executing code simply declares that the current scope is dynamic but if you use it\n * inside unstable_cache it can still be cached. This type of indication can be removed if we ever\n * make the default dynamic to begin with because the only way you would ever be static is inside\n * a cache scope which this indication does not affect.\n *\n * The second is an indication that a dynamic data source was read. This is a stronger form of dynamic\n * because it means that it is inappropriate to cache this at all. using a dynamic data source inside\n * unstable_cache should error. If you want to use some dynamic data inside unstable_cache you should\n * read that data outside the cache and pass it in as an argument to the cached function.\n */\n\nimport type { WorkStore } from '../app-render/work-async-storage.external'\nimport type {\n WorkUnitStore,\n PrerenderStoreLegacy,\n PrerenderStoreModern,\n ValidationStoreClient,\n} from '../app-render/work-unit-async-storage.external'\n\n// Once postpone is in stable we should switch to importing the postpone export directly\nimport React from 'react'\n\nimport { DynamicServerError } from '../../client/components/hooks-server-context'\nimport { StaticGenBailoutError } from '../../client/components/static-generation-bailout'\nimport {\n throwForMissingRequestStore,\n workUnitAsyncStorage,\n} from './work-unit-async-storage.external'\nimport { workAsyncStorage } from '../app-render/work-async-storage.external'\nimport { makeHangingPromise, getRuntimeStage } from '../dynamic-rendering-utils'\nimport {\n METADATA_BOUNDARY_NAME,\n VIEWPORT_BOUNDARY_NAME,\n OUTLET_BOUNDARY_NAME,\n ROOT_LAYOUT_BOUNDARY_NAME,\n} from '../../lib/framework/boundary-constants'\nimport { scheduleOnNextTick } from '../../lib/scheduler'\nimport { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { InvariantError } from '../../shared/lib/invariant-error'\nimport { INSTANT_VALIDATION_BOUNDARY_NAME } from './instant-validation/boundary-constants'\nimport type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'\nimport type { InstantValidationSampleTracking } from './instant-validation/instant-samples'\n\nconst hasPostpone = typeof React.unstable_postpone === 'function'\n\nexport type DynamicAccess = {\n /**\n * If debugging, this will contain the stack trace of where the dynamic access\n * occurred. This is used to provide more information to the user about why\n * their page is being rendered dynamically.\n */\n stack?: string\n\n /**\n * The expression that was accessed dynamically.\n */\n expression: string\n}\n\n// Stores dynamic reasons used during an RSC render.\nexport type DynamicTrackingState = {\n /**\n * When true, stack information will also be tracked during dynamic access.\n */\n readonly isDebugDynamicAccesses: boolean | undefined\n\n /**\n * The dynamic accesses that occurred during the render.\n */\n readonly dynamicAccesses: Array<DynamicAccess>\n\n syncDynamicErrorWithStack: null | Error\n}\n\n// Stores dynamic reasons used during an SSR render.\nexport type DynamicValidationState = {\n hasSuspenseAboveBody: boolean\n hasDynamicMetadata: boolean\n dynamicMetadata: null | Error\n hasDynamicViewport: boolean\n hasAllowedDynamic: boolean\n dynamicErrors: Array<Error>\n}\n\nexport function createDynamicTrackingState(\n isDebugDynamicAccesses: boolean | undefined\n): DynamicTrackingState {\n return {\n isDebugDynamicAccesses,\n dynamicAccesses: [],\n syncDynamicErrorWithStack: null,\n }\n}\n\nexport function createDynamicValidationState(): DynamicValidationState {\n return {\n hasSuspenseAboveBody: false,\n hasDynamicMetadata: false,\n dynamicMetadata: null,\n hasDynamicViewport: false,\n hasAllowedDynamic: false,\n dynamicErrors: [],\n }\n}\n\nexport function getFirstDynamicReason(\n trackingState: DynamicTrackingState\n): undefined | string {\n return trackingState.dynamicAccesses[0]?.expression\n}\n\n/**\n * This function communicates that the current scope should be treated as dynamic.\n *\n * In most cases this function is a no-op but if called during\n * a PPR prerender it will postpone the current sub-tree and calling\n * it during a normal prerender will cause the entire prerender to abort\n */\nexport function markCurrentScopeAsDynamic(\n store: WorkStore,\n workUnitStore: undefined | Exclude<WorkUnitStore, PrerenderStoreModern>,\n expression: string\n): void {\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'unstable-cache':\n // Inside cache scopes, marking a scope as dynamic has no effect,\n // because the outer cache scope creates a cache boundary. This is\n // subtly different from reading a dynamic data source, which is\n // forbidden inside a cache scope.\n return\n case 'private-cache':\n // A private cache scope is already dynamic by definition.\n return\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'request':\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n\n // If we're forcing dynamic rendering or we're forcing static rendering, we\n // don't need to do anything here because the entire page is already dynamic\n // or it's static and it should not throw or postpone here.\n if (store.forceDynamic || store.forceStatic) return\n\n if (store.dynamicShouldError) {\n throw new StaticGenBailoutError(\n `Route ${store.route} with \\`dynamic = \"error\"\\` couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`\n )\n }\n\n if (workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender-ppr':\n return postponeWithTracking(\n store.route,\n expression,\n workUnitStore.dynamicTracking\n )\n case 'prerender-legacy':\n workUnitStore.revalidate = 0\n\n // We aren't prerendering, but we are generating a static page. We need\n // to bail out of static generation.\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used ${expression}. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n workUnitStore.usedDynamic = true\n }\n break\n case 'generate-static-params':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\n/**\n * This function is meant to be used when prerendering without cacheComponents or PPR.\n * When called during a build it will cause Next.js to consider the route as dynamic.\n *\n * @internal\n */\nexport function throwToInterruptStaticGeneration(\n expression: string,\n store: WorkStore,\n prerenderStore: PrerenderStoreLegacy\n): never {\n // We aren't prerendering but we are generating a static page. We need to bail out of static generation\n const err = new DynamicServerError(\n `Route ${store.route} couldn't be rendered statically because it used \\`${expression}\\`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error`\n )\n\n prerenderStore.revalidate = 0\n\n store.dynamicUsageDescription = expression\n store.dynamicUsageStack = err.stack\n\n throw err\n}\n\n/**\n * This function should be used to track whether something dynamic happened even when\n * we are in a dynamic render. This is useful for Dev where all renders are dynamic but\n * we still track whether dynamic APIs were accessed for helpful messaging\n *\n * @internal\n */\nexport function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {\n switch (workUnitStore.type) {\n case 'cache':\n case 'unstable-cache':\n // Inside cache scopes, marking a scope as dynamic has no effect,\n // because the outer cache scope creates a cache boundary. This is\n // subtly different from reading a dynamic data source, which is\n // forbidden inside a cache scope.\n return\n case 'private-cache':\n // A private cache scope is already dynamic by definition.\n return\n case 'prerender':\n case 'prerender-runtime':\n case 'prerender-legacy':\n case 'prerender-ppr':\n case 'prerender-client':\n case 'validation-client':\n case 'generate-static-params':\n break\n case 'request':\n if (process.env.NODE_ENV !== 'production') {\n workUnitStore.usedDynamic = true\n }\n break\n default:\n workUnitStore satisfies never\n }\n}\n\nfunction abortOnSynchronousDynamicDataAccess(\n route: string,\n expression: string,\n prerenderStore: PrerenderStoreModern\n): void {\n const reason = `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`\n\n const error = createPrerenderInterruptedError(reason)\n\n prerenderStore.controller.abort(error)\n\n const dynamicTracking = prerenderStore.dynamicTracking\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n // When we aren't debugging, we don't need to create another error for the\n // stack trace.\n stack: dynamicTracking.isDebugDynamicAccesses\n ? new Error().stack\n : undefined,\n expression,\n })\n }\n}\n\nexport function abortOnSynchronousPlatformIOAccess(\n route: string,\n expression: string,\n errorWithStack: Error,\n prerenderStore: PrerenderStoreModern\n): void {\n const dynamicTracking = prerenderStore.dynamicTracking\n abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\n // It is important that we set this tracking value after aborting. Aborts are executed\n // synchronously except for the case where you abort during render itself. By setting this\n // value late we can use it to determine if any of the aborted tasks are the task that\n // called the sync IO expression in the first place.\n if (dynamicTracking) {\n if (dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n }\n }\n}\n\n/**\n * use this function when prerendering with cacheComponents. If we are doing a\n * prospective prerender we don't actually abort because we want to discover\n * all caches for the shell. If this is the actual prerender we do abort.\n *\n * This function accepts a prerenderStore but the caller should ensure we're\n * actually running in cacheComponents mode.\n *\n * @internal\n */\nexport function abortAndThrowOnSynchronousRequestDataAccess(\n route: string,\n expression: string,\n errorWithStack: Error,\n prerenderStore: PrerenderStoreModern\n): never {\n const prerenderSignal = prerenderStore.controller.signal\n if (prerenderSignal.aborted === false) {\n // TODO it would be better to move this aborted check into the callsite so we can avoid making\n // the error object when it isn't relevant to the aborting of the prerender however\n // since we need the throw semantics regardless of whether we abort it is easier to land\n // this way. See how this was handled with `abortOnSynchronousPlatformIOAccess` for a closer\n // to ideal implementation\n abortOnSynchronousDynamicDataAccess(route, expression, prerenderStore)\n // It is important that we set this tracking value after aborting. Aborts are executed\n // synchronously except for the case where you abort during render itself. By setting this\n // value late we can use it to determine if any of the aborted tasks are the task that\n // called the sync IO expression in the first place.\n const dynamicTracking = prerenderStore.dynamicTracking\n if (dynamicTracking) {\n if (dynamicTracking.syncDynamicErrorWithStack === null) {\n dynamicTracking.syncDynamicErrorWithStack = errorWithStack\n }\n }\n }\n throw createPrerenderInterruptedError(\n `Route ${route} needs to bail out of prerendering at this point because it used ${expression}.`\n )\n}\n\n/**\n * This component will call `React.postpone` that throws the postponed error.\n */\ntype PostponeProps = {\n reason: string\n route: string\n}\nexport function Postpone({ reason, route }: PostponeProps): never {\n const prerenderStore = workUnitAsyncStorage.getStore()\n const dynamicTracking =\n prerenderStore && prerenderStore.type === 'prerender-ppr'\n ? prerenderStore.dynamicTracking\n : null\n postponeWithTracking(route, reason, dynamicTracking)\n}\n\nexport function postponeWithTracking(\n route: string,\n expression: string,\n dynamicTracking: null | DynamicTrackingState\n): never {\n assertPostpone()\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n // When we aren't debugging, we don't need to create another error for the\n // stack trace.\n stack: dynamicTracking.isDebugDynamicAccesses\n ? new Error().stack\n : undefined,\n expression,\n })\n }\n\n React.unstable_postpone(createPostponeReason(route, expression))\n}\n\nfunction createPostponeReason(route: string, expression: string) {\n return (\n `Route ${route} needs to bail out of prerendering at this point because it used ${expression}. ` +\n `React throws this special object to indicate where. It should not be caught by ` +\n `your own try/catch. Learn more: https://nextjs.org/docs/messages/ppr-caught-error`\n )\n}\n\nexport function isDynamicPostpone(err: unknown) {\n if (\n typeof err === 'object' &&\n err !== null &&\n typeof (err as any).message === 'string'\n ) {\n return isDynamicPostponeReason((err as any).message)\n }\n return false\n}\n\nfunction isDynamicPostponeReason(reason: string) {\n return (\n reason.includes(\n 'needs to bail out of prerendering at this point because it used'\n ) &&\n reason.includes(\n 'Learn more: https://nextjs.org/docs/messages/ppr-caught-error'\n )\n )\n}\n\nif (isDynamicPostponeReason(createPostponeReason('%%%', '^^^')) === false) {\n throw new Error(\n 'Invariant: isDynamicPostpone misidentified a postpone reason. This is a bug in Next.js'\n )\n}\n\nconst NEXT_PRERENDER_INTERRUPTED = 'NEXT_PRERENDER_INTERRUPTED'\n\nfunction createPrerenderInterruptedError(message: string): Error {\n const error = new Error(message)\n ;(error as any).digest = NEXT_PRERENDER_INTERRUPTED\n return error\n}\n\ntype DigestError = Error & {\n digest: string\n}\n\nexport function isPrerenderInterruptedError(\n error: unknown\n): error is DigestError {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as any).digest === NEXT_PRERENDER_INTERRUPTED &&\n 'name' in error &&\n 'message' in error &&\n error instanceof Error\n )\n}\n\nexport function accessedDynamicData(\n dynamicAccesses: Array<DynamicAccess>\n): boolean {\n return dynamicAccesses.length > 0\n}\n\nexport function consumeDynamicAccess(\n serverDynamic: DynamicTrackingState,\n clientDynamic: DynamicTrackingState\n): DynamicTrackingState['dynamicAccesses'] {\n // We mutate because we only call this once we are no longer writing\n // to the dynamicTrackingState and it's more efficient than creating a new\n // array.\n serverDynamic.dynamicAccesses.push(...clientDynamic.dynamicAccesses)\n return serverDynamic.dynamicAccesses\n}\n\nexport function formatDynamicAPIAccesses(\n dynamicAccesses: Array<DynamicAccess>\n): string[] {\n return dynamicAccesses\n .filter(\n (access): access is Required<DynamicAccess> =>\n typeof access.stack === 'string' && access.stack.length > 0\n )\n .map(({ expression, stack }) => {\n stack = stack\n .split('\\n')\n // Remove the \"Error: \" prefix from the first line of the stack trace as\n // well as the first 4 lines of the stack trace which is the distance\n // from the user code and the `new Error().stack` call.\n .slice(4)\n .filter((line) => {\n // Exclude Next.js internals from the stack trace.\n if (line.includes('node_modules/next/')) {\n return false\n }\n\n // Exclude anonymous functions from the stack trace.\n if (line.includes(' (<anonymous>)')) {\n return false\n }\n\n // Exclude Node.js internals from the stack trace.\n if (line.includes(' (node:')) {\n return false\n }\n\n return true\n })\n .join('\\n')\n return `Dynamic API Usage Debug - ${expression}:\\n${stack}`\n })\n}\n\nfunction assertPostpone() {\n if (!hasPostpone) {\n throw new Error(\n `Invariant: React.unstable_postpone is not defined. This suggests the wrong version of React was loaded. This is a bug in Next.js`\n )\n }\n}\n\n/**\n * This is a bit of a hack to allow us to abort a render using a Postpone instance instead of an Error which changes React's\n * abort semantics slightly.\n */\nexport function createRenderInBrowserAbortSignal(): AbortSignal {\n const controller = new AbortController()\n controller.abort(new BailoutToCSRError('Render in Browser'))\n return controller.signal\n}\n\n/**\n * In a prerender, we may end up with hanging Promises as inputs due them\n * stalling on connection() or because they're loading dynamic data. In that\n * case we need to abort the encoding of arguments since they'll never complete.\n */\nexport function createHangingInputAbortSignal(\n workUnitStore: WorkUnitStore\n): AbortSignal | undefined {\n switch (workUnitStore.type) {\n case 'prerender':\n case 'prerender-runtime':\n const controller = new AbortController()\n\n if (workUnitStore.cacheSignal) {\n // If we have a cacheSignal it means we're in a prospective render. If\n // the input we're waiting on is coming from another cache, we do want\n // to wait for it so that we can resolve this cache entry too.\n workUnitStore.cacheSignal.inputReady().then(() => {\n controller.abort()\n })\n } else {\n // Otherwise we're in the final render and we should already have all\n // our caches filled.\n // If the prerender uses stages, we have wait until the runtime stage,\n // at which point all runtime inputs will be resolved.\n // (otherwise, a runtime prerender might consider `cookies()` hanging\n // even though they'd resolve in the next task.)\n //\n // We might still be waiting on some microtasks so we\n // wait one tick before giving up. When we give up, we still want to\n // render the content of this cache as deeply as we can so that we can\n // suspend as deeply as possible in the tree or not at all if we don't\n // end up waiting for the input.\n if (\n // eslint-disable-next-line no-restricted-syntax -- We are discriminating between two different refined types and don't need an addition exhaustive switch here\n workUnitStore.type === 'prerender-runtime' &&\n workUnitStore.stagedRendering\n ) {\n const { stagedRendering } = workUnitStore\n stagedRendering\n .waitForStage(getRuntimeStage(stagedRendering))\n .then(() => scheduleOnNextTick(() => controller.abort()))\n } else {\n scheduleOnNextTick(() => controller.abort())\n }\n }\n\n return controller.signal\n case 'prerender-client':\n case 'validation-client':\n case 'prerender-ppr':\n case 'prerender-legacy':\n case 'request':\n case 'cache':\n case 'private-cache':\n case 'unstable-cache':\n case 'generate-static-params':\n return undefined\n default:\n workUnitStore satisfies never\n }\n}\n\nexport function annotateDynamicAccess(\n expression: string,\n prerenderStore: PrerenderStoreModern | ValidationStoreClient\n) {\n const dynamicTracking = prerenderStore.dynamicTracking\n if (dynamicTracking) {\n dynamicTracking.dynamicAccesses.push({\n stack: dynamicTracking.isDebugDynamicAccesses\n ? new Error().stack\n : undefined,\n expression,\n })\n }\n}\n\nexport function useDynamicRouteParams(expression: string) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n if (workStore && workUnitStore) {\n switch (workUnitStore.type) {\n case 'prerender-client':\n case 'prerender': {\n const fallbackParams = workUnitStore.fallbackRouteParams\n\n if (fallbackParams && fallbackParams.size > 0) {\n // We are in a prerender with cacheComponents semantics. We are going to\n // hang here and never resolve. This will cause the currently\n // rendering component to effectively be a dynamic hole.\n React.use(\n makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n expression\n )\n )\n }\n break\n }\n case 'prerender-ppr': {\n const fallbackParams = workUnitStore.fallbackRouteParams\n if (fallbackParams && fallbackParams.size > 0) {\n return postponeWithTracking(\n workStore.route,\n expression,\n workUnitStore.dynamicTracking\n )\n }\n break\n }\n case 'validation-client': {\n // Don't check fallbackRouteParams here. We handle params that weren't\n // provided in the samples using a proxy that throws when accessed.\n break\n }\n case 'prerender-runtime':\n throw new InvariantError(\n `\\`${expression}\\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n )\n case 'cache':\n case 'private-cache':\n throw new InvariantError(\n `\\`${expression}\\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n )\n case 'generate-static-params':\n throw new InvariantError(\n `\\`${expression}\\` was called in \\`generateStaticParams\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`\n )\n case 'prerender-legacy':\n case 'request':\n case 'unstable-cache':\n break\n default:\n workUnitStore satisfies never\n }\n }\n}\n\nexport function useDynamicSearchParams(expression: string) {\n const workStore = workAsyncStorage.getStore()\n const workUnitStore = workUnitAsyncStorage.getStore()\n\n if (!workStore) {\n // We assume pages router context and just return\n return\n }\n\n if (!workUnitStore) {\n throwForMissingRequestStore(expression)\n }\n\n switch (workUnitStore.type) {\n case 'validation-client':\n // During instant validation we try to behave as close to client as possible,\n // so this shouldn't hang during SSR.\n return\n case 'prerender-client': {\n React.use(\n makeHangingPromise(\n workUnitStore.renderSignal,\n workStore.route,\n expression\n )\n )\n break\n }\n case 'prerender-legacy':\n case 'prerender-ppr': {\n if (workStore.forceStatic) {\n return\n }\n throw new BailoutToCSRError(expression)\n }\n case 'prerender':\n case 'prerender-runtime':\n throw new InvariantError(\n `\\`${expression}\\` was called from a Server Component. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n )\n case 'cache':\n case 'unstable-cache':\n case 'private-cache':\n throw new InvariantError(\n `\\`${expression}\\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`\n )\n case 'generate-static-params':\n throw new InvariantError(\n `\\`${expression}\\` was called in \\`generateStaticParams\\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`\n )\n case 'request':\n return\n default:\n workUnitStore satisfies never\n }\n}\n\nconst hasSuspenseRegex = /\\n\\s+at Suspense \\(<anonymous>\\)/\n\n// Common implicit body tags that React will treat as body when placed directly in html\nconst bodyAndImplicitTags =\n 'body|div|main|section|article|aside|header|footer|nav|form|p|span|h1|h2|h3|h4|h5|h6'\n\n// Detects when RootLayoutBoundary (our framework marker component) appears\n// after Suspense in the component stack, indicating the root layout is wrapped\n// within a Suspense boundary. Ensures no body/html/implicit-body components are in between.\n//\n// Example matches:\n// at Suspense (<anonymous>)\n// at __next_root_layout_boundary__ (<anonymous>)\n//\n// Or with other components in between (but not body/html/implicit-body):\n// at Suspense (<anonymous>)\n// at SomeComponent (<anonymous>)\n// at __next_root_layout_boundary__ (<anonymous>)\nconst hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex = new RegExp(\n `\\\\n\\\\s+at Suspense \\\\(<anonymous>\\\\)(?:(?!\\\\n\\\\s+at (?:${bodyAndImplicitTags}) \\\\(<anonymous>\\\\))[\\\\s\\\\S])*?\\\\n\\\\s+at ${ROOT_LAYOUT_BOUNDARY_NAME} \\\\([^\\\\n]*\\\\)`\n)\n\nconst hasMetadataRegex = new RegExp(\n `\\\\n\\\\s+at ${METADATA_BOUNDARY_NAME}[\\\\n\\\\s]`\n)\nconst hasViewportRegex = new RegExp(\n `\\\\n\\\\s+at ${VIEWPORT_BOUNDARY_NAME}[\\\\n\\\\s]`\n)\nconst hasOutletRegex = new RegExp(`\\\\n\\\\s+at ${OUTLET_BOUNDARY_NAME}[\\\\n\\\\s]`)\n\nconst hasInstantValidationBoundaryRegex = new RegExp(\n `\\\\n\\\\s+at ${INSTANT_VALIDATION_BOUNDARY_NAME}[\\\\n\\\\s]`\n)\n\nexport function trackAllowedDynamicAccess(\n workStore: WorkStore,\n componentStack: string,\n dynamicValidation: DynamicValidationState,\n clientDynamic: DynamicTrackingState\n) {\n if (hasOutletRegex.test(componentStack)) {\n // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n return\n } else if (hasMetadataRegex.test(componentStack)) {\n dynamicValidation.hasDynamicMetadata = true\n return\n } else if (hasViewportRegex.test(componentStack)) {\n dynamicValidation.hasDynamicViewport = true\n return\n } else if (\n hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n componentStack\n )\n ) {\n // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n dynamicValidation.hasAllowedDynamic = true\n dynamicValidation.hasSuspenseAboveBody = true\n return\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it so we don't need to report it as a source\n // of disallowed\n dynamicValidation.hasAllowedDynamic = true\n return\n } else if (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(\n clientDynamic.syncDynamicErrorWithStack\n )\n return\n } else {\n const message =\n `Route \"${workStore.route}\": Uncached data was accessed outside of ` +\n '<Suspense>. This delays the entire page from rendering, resulting in a ' +\n 'slow user experience. Learn more: ' +\n 'https://nextjs.org/docs/messages/blocking-route'\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicErrors.push(error)\n return\n }\n}\n\nexport enum DynamicHoleKind {\n /** We know that this hole is caused by runtime data. */\n Runtime = 1,\n /** We know that this hole is caused by dynamic data. */\n Dynamic = 2,\n}\n\n/** Stores dynamic reasons used during an SSR render in instant validation. */\nexport type InstantValidationState = {\n hasDynamicMetadata: boolean\n hasAllowedClientDynamicAboveBoundary: boolean\n dynamicMetadata: null | Error\n hasDynamicViewport: boolean\n hasAllowedDynamic: boolean\n dynamicErrors: Array<Error>\n validationPreventingErrors: Array<Error>\n thrownErrorsOutsideBoundary: Array<unknown>\n createInstantStack: (() => Error) | null\n}\n\nexport function createInstantValidationState(\n createInstantStack: (() => Error) | null\n): InstantValidationState {\n return {\n hasDynamicMetadata: false,\n hasAllowedClientDynamicAboveBoundary: false,\n dynamicMetadata: null,\n hasDynamicViewport: false,\n hasAllowedDynamic: false,\n dynamicErrors: [],\n validationPreventingErrors: [],\n thrownErrorsOutsideBoundary: [],\n createInstantStack,\n }\n}\n\nexport function trackDynamicHoleInNavigation(\n workStore: WorkStore,\n componentStack: string,\n dynamicValidation: InstantValidationState,\n clientDynamic: DynamicTrackingState,\n kind: DynamicHoleKind,\n boundaryState: ValidationBoundaryTracking\n) {\n if (hasOutletRegex.test(componentStack)) {\n // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n return\n }\n if (hasMetadataRegex.test(componentStack)) {\n const usageDescription =\n kind === DynamicHoleKind.Runtime\n ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments.`\n : `Uncached data or \\`connection()\\` was accessed inside \\`generateMetadata\\`.`\n const message = `Route \"${workStore.route}\": ${usageDescription} Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n const error = addErrorContext(\n new Error(message),\n componentStack,\n dynamicValidation.createInstantStack\n )\n dynamicValidation.dynamicMetadata = error\n return\n }\n if (hasViewportRegex.test(componentStack)) {\n const usageDescription =\n kind === DynamicHoleKind.Runtime\n ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateViewport\\`.`\n : `Uncached data or \\`connection()\\` was accessed inside \\`generateViewport\\`.`\n const message = `Route \"${workStore.route}\": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n const error = addErrorContext(\n new Error(message),\n componentStack,\n dynamicValidation.createInstantStack\n )\n dynamicValidation.dynamicErrors.push(error)\n return\n }\n\n const boundaryLocation =\n hasInstantValidationBoundaryRegex.exec(componentStack)\n if (!boundaryLocation) {\n // We don't see the validation boundary in the component stack,\n // so this hole must be coming from a shared parent.\n // Shared parents are fully resolved and don't have RSC holes,\n // but they can still suspend in a client component during SSR.\n\n // If we managed to render all the validation boundaries, that means\n // that the client holes aren't blocking validation and we can disregard them.\n // Note that we don't even care whether they have suspense or not.\n if (boundaryState.expectedIds.size === boundaryState.renderedIds.size) {\n dynamicValidation.hasAllowedClientDynamicAboveBoundary = true\n dynamicValidation.hasAllowedDynamic = true // Holes outside the boundary contribute to allowing dynamic metadata\n return\n } else {\n // TODO(instant-validation) TODO(NAR-787)\n // If shared parents blocked us from validating, we should only log\n // the errors from the innermost (segments), i.e. omit layouts whose\n // slots managed to render (because clearly they didn't block validation)\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because a Client Component in a parent segment prevented the page from rendering.`\n const error = addErrorContext(\n new Error(message),\n componentStack,\n dynamicValidation.createInstantStack\n )\n dynamicValidation.validationPreventingErrors.push(error)\n return\n }\n } else {\n // The hole originates inside the validation boundary.\n //\n // Check if we have a Suspense above the hole, but below the validation boundary.\n // If we do, then this dynamic usage wouldn't block a navigation to this subtree.\n // Conversely, if the nearest suspense is above the validation boundary, then this subtree would block.\n //\n // Note that in the component stack, children come before parents.\n //\n // Valid:\n // ...\n // at Suspense\n // ...\n // at __next_prefetch_validation_boundary__\n //\n // Invalid:\n // ...\n // at __next_prefetch_validation_boundary__\n // ...\n // at Suspense\n //\n const suspenseLocation = hasSuspenseRegex.exec(componentStack)\n if (suspenseLocation) {\n if (suspenseLocation.index < boundaryLocation.index) {\n dynamicValidation.hasAllowedDynamic = true\n return\n } else {\n // invalid - fallthrough\n }\n }\n }\n\n if (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n const syncError = clientDynamic.syncDynamicErrorWithStack\n if (\n dynamicValidation.createInstantStack !== null &&\n syncError.cause === undefined\n ) {\n syncError.cause = dynamicValidation.createInstantStack()\n }\n dynamicValidation.dynamicErrors.push(syncError)\n return\n }\n\n const usageDescription =\n kind === DynamicHoleKind.Runtime\n ? `Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`.`\n : `Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`.`\n const message = `Route \"${workStore.route}\": ${usageDescription} This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`\n const error = addErrorContext(\n new Error(message),\n componentStack,\n dynamicValidation.createInstantStack\n )\n dynamicValidation.dynamicErrors.push(error)\n return\n}\n\nexport function trackThrownErrorInNavigation(\n workStore: WorkStore,\n dynamicValidation: InstantValidationState,\n thrownValue: unknown,\n componentStack: string\n) {\n const boundaryLocation =\n hasInstantValidationBoundaryRegex.exec(componentStack)\n if (!boundaryLocation) {\n // There's no validation boundary on the component stack.\n // This error may have blocked a boundary from rendering.\n\n // Wrap the error to provide component context.\n // This helps for errors from node_modules which would otherwise\n // have no useful stack information due to ignore-listing,\n // e.g. next/dynamic with `ssr: false`.\n const error = addErrorContext(\n new Error(\n 'An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.',\n { cause: thrownValue }\n ),\n componentStack,\n null\n )\n dynamicValidation.thrownErrorsOutsideBoundary.push(error)\n } else {\n // There's validation boundary on the component stack,\n // so we know this error didn't block a validation boundary from rendering.\n // However, this error might be hiding be hiding dynamic content that would\n // cause validation to fail.\n const suspenseLocation = hasSuspenseRegex.exec(componentStack)\n if (suspenseLocation) {\n if (suspenseLocation.index < boundaryLocation.index) {\n // There's a Suspense below the validation boundary but above this error's location.\n // This subtree can't fail instant validation because any potential\n // dynamic holes would be guarded by the Suspense anyway,\n // so we can allow this.\n return\n } else {\n // invalid - fallthrough\n }\n }\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because an error prevented the target segment from rendering.`\n const error = addErrorContext(\n new Error(message, { cause: thrownValue }),\n componentStack,\n null // TODO(instant-validation-build): conflicting use of cause\n )\n dynamicValidation.validationPreventingErrors.push(error)\n }\n}\n\nexport function trackDynamicHoleInRuntimeShell(\n workStore: WorkStore,\n componentStack: string,\n dynamicValidation: DynamicValidationState,\n clientDynamic: DynamicTrackingState\n) {\n if (hasOutletRegex.test(componentStack)) {\n // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n return\n } else if (hasMetadataRegex.test(componentStack)) {\n const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed inside \\`generateMetadata\\`. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicMetadata = error\n return\n } else if (hasViewportRegex.test(componentStack)) {\n // TODO(instant-validation): If the page only has holes caused by runtime data,\n // we won't find out if there's a suspense-above-body and error for dynamic viewport\n // even if there is in fact a suspense-above-body\n const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed inside \\`generateViewport\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicErrors.push(error)\n return\n } else if (\n hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n componentStack\n )\n ) {\n // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n dynamicValidation.hasAllowedDynamic = true\n dynamicValidation.hasSuspenseAboveBody = true\n return\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it so we don't need to report it as a source\n // of disallowed\n dynamicValidation.hasAllowedDynamic = true\n return\n } else if (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(\n clientDynamic.syncDynamicErrorWithStack\n )\n return\n }\n\n const message = `Route \"${workStore.route}\": Uncached data or \\`connection()\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicErrors.push(error)\n return\n}\n\nexport function trackDynamicHoleInStaticShell(\n workStore: WorkStore,\n componentStack: string,\n dynamicValidation: DynamicValidationState,\n clientDynamic: DynamicTrackingState\n) {\n if (hasOutletRegex.test(componentStack)) {\n // We don't need to track that this is dynamic. It is only so when something else is also dynamic.\n return\n } else if (hasMetadataRegex.test(componentStack)) {\n const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateMetadata\\` or you have file-based metadata such as icons that depend on dynamic params segments. Except for this instance, the page would have been entirely prerenderable which may have been the intended behavior. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicMetadata = error\n return\n } else if (hasViewportRegex.test(componentStack)) {\n const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed inside \\`generateViewport\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicErrors.push(error)\n return\n } else if (\n hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex.test(\n componentStack\n )\n ) {\n // For Suspense within body, the prelude wouldn't be empty so it wouldn't violate the empty static shells rule.\n // But if you have Suspense above body, the prelude is empty but we allow that because having Suspense\n // is an explicit signal from the user that they acknowledge the empty shell and want dynamic rendering.\n dynamicValidation.hasAllowedDynamic = true\n dynamicValidation.hasSuspenseAboveBody = true\n return\n } else if (hasSuspenseRegex.test(componentStack)) {\n // this error had a Suspense boundary above it so we don't need to report it as a source\n // of disallowed\n dynamicValidation.hasAllowedDynamic = true\n return\n } else if (clientDynamic.syncDynamicErrorWithStack) {\n // This task was the task that called the sync error.\n dynamicValidation.dynamicErrors.push(\n clientDynamic.syncDynamicErrorWithStack\n )\n return\n } else {\n const message = `Route \"${workStore.route}\": Runtime data such as \\`cookies()\\`, \\`headers()\\`, \\`params\\`, or \\`searchParams\\` was accessed outside of \\`<Suspense>\\`. This delays the entire page from rendering, resulting in a slow user experience. Learn more: https://nextjs.org/docs/messages/blocking-route`\n const error = addErrorContext(new Error(message), componentStack, null)\n dynamicValidation.dynamicErrors.push(error)\n return\n }\n}\n\n/**\n * In dev mode, we prefer using the owner stack, otherwise the provided\n * component stack is used.\n *\n * Accepts an already-created Error so the SWC error-code plugin can see the\n * `new Error(...)` call at each call site and auto-assign error codes.\n */\nfunction addErrorContext(\n error: Error,\n componentStack: string,\n createInstantStack: (() => Error) | null\n) {\n const ownerStack =\n process.env.NODE_ENV !== 'production' && React.captureOwnerStack\n ? React.captureOwnerStack()\n : null\n\n if (createInstantStack !== null) {\n error.cause = createInstantStack()\n }\n // TODO go back to owner stack here if available. This is temporarily using componentStack to get the right\n //\n error.stack =\n error.name + ': ' + error.message + (ownerStack || componentStack)\n return error\n}\n\nexport enum PreludeState {\n Full = 0,\n Empty = 1,\n Errored = 2,\n}\n\nexport function logDisallowedDynamicError(\n workStore: WorkStore,\n error: Error\n): void {\n console.error(error)\n\n if (process.env.NODE_ENV !== 'development') {\n console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:\n - Start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.\n - Rerun the production build with \\`next build --debug-prerender\\` to generate better stack traces.`)\n } else if (!process.env.__NEXT_DEV_SERVER) {\n console.error(\n `To debug the issue, start the app in development mode by running \\`next dev\\`, then open \"${workStore.route}\" in your browser to investigate the error.`\n )\n }\n}\n\nexport function throwIfDisallowedDynamic(\n workStore: WorkStore,\n prelude: PreludeState,\n dynamicValidation: DynamicValidationState,\n serverDynamic: DynamicTrackingState\n): void {\n if (serverDynamic.syncDynamicErrorWithStack) {\n logDisallowedDynamicError(\n workStore,\n serverDynamic.syncDynamicErrorWithStack\n )\n throw new StaticGenBailoutError()\n }\n\n if (prelude !== PreludeState.Full) {\n if (dynamicValidation.hasSuspenseAboveBody) {\n // This route has opted into allowing fully dynamic rendering\n // by including a Suspense boundary above the body. In this case\n // a lack of a shell is not considered disallowed so we simply return\n return\n }\n\n // We didn't have any sync bailouts but there may be user code which\n // blocked the root. We would have captured these during the prerender\n // and can log them here and then terminate the build/validating render\n const dynamicErrors = dynamicValidation.dynamicErrors\n if (dynamicErrors.length > 0) {\n for (let i = 0; i < dynamicErrors.length; i++) {\n logDisallowedDynamicError(workStore, dynamicErrors[i])\n }\n\n throw new StaticGenBailoutError()\n }\n\n // If we got this far then the only other thing that could be blocking\n // the root is dynamic Viewport. If this is dynamic then\n // you need to opt into that by adding a Suspense boundary above the body\n // to indicate your are ok with fully dynamic rendering.\n if (dynamicValidation.hasDynamicViewport) {\n console.error(\n `Route \"${workStore.route}\" has a \\`generateViewport\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) without explicitly allowing fully dynamic rendering. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-viewport`\n )\n throw new StaticGenBailoutError()\n }\n\n if (prelude === PreludeState.Empty) {\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n // We still adhere to the constraint that you must produce a shell but invite the\n // user to report this as a bug in Next.js.\n console.error(\n `Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason. This is a bug in Next.js.`\n )\n throw new StaticGenBailoutError()\n }\n } else {\n if (\n dynamicValidation.hasAllowedDynamic === false &&\n dynamicValidation.hasDynamicMetadata\n ) {\n console.error(\n `Route \"${workStore.route}\" has a \\`generateMetadata\\` that depends on Request data (\\`cookies()\\`, etc...) or uncached external data (\\`fetch(...)\\`, etc...) when the rest of the route does not. See more info here: https://nextjs.org/docs/messages/next-prerender-dynamic-metadata`\n )\n throw new StaticGenBailoutError()\n }\n }\n}\n\nexport function getStaticShellDisallowedDynamicReasons(\n workStore: WorkStore,\n prelude: PreludeState,\n dynamicValidation: DynamicValidationState,\n configAllowsBlocking: boolean\n): Array<Error> {\n if (configAllowsBlocking || dynamicValidation.hasSuspenseAboveBody) {\n // This route has opted into allowing fully dynamic rendering\n // by including a Suspense boundary above the body. In this case\n // a lack of a shell is not considered disallowed so we simply return\n return []\n }\n\n if (prelude !== PreludeState.Full) {\n // We didn't have any sync bailouts but there may be user code which\n // blocked the root. We would have captured these during the prerender\n // and can log them here and then terminate the build/validating render\n const dynamicErrors = dynamicValidation.dynamicErrors\n if (dynamicErrors.length > 0) {\n return dynamicErrors\n }\n\n if (prelude === PreludeState.Empty) {\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n // We still adhere to the constraint that you must produce a shell but invite the\n // user to report this as a bug in Next.js.\n return [\n new InvariantError(\n `Route \"${workStore.route}\" did not produce a static shell and Next.js was unable to determine a reason.`\n ),\n ]\n }\n } else {\n // We have a prelude but we might still have dynamic metadata without any other dynamic access\n if (\n dynamicValidation.hasAllowedDynamic === false &&\n dynamicValidation.dynamicErrors.length === 0 &&\n dynamicValidation.dynamicMetadata\n ) {\n return [dynamicValidation.dynamicMetadata]\n }\n }\n // We had a non-empty prelude and there are no dynamic holes\n return []\n}\n\nexport function getNavigationDisallowedDynamicReasons(\n workStore: WorkStore,\n prelude: PreludeState,\n dynamicValidation: InstantValidationState,\n validationSampleTracking: InstantValidationSampleTracking | null,\n boundaryState: ValidationBoundaryTracking\n): Array<Error> {\n // If we have errors related to missing samples, those should take precedence over everything else.\n if (validationSampleTracking) {\n const { missingSampleErrors } = validationSampleTracking\n if (missingSampleErrors.length > 0) {\n return missingSampleErrors\n }\n }\n\n const { validationPreventingErrors } = dynamicValidation\n if (validationPreventingErrors.length > 0) {\n return validationPreventingErrors\n }\n\n if (boundaryState.renderedIds.size < boundaryState.expectedIds.size) {\n const { thrownErrorsOutsideBoundary, createInstantStack } =\n dynamicValidation\n if (thrownErrorsOutsideBoundary.length === 0) {\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering for an unknown reason.`\n const error =\n createInstantStack !== null ? createInstantStack() : new Error()\n error.name = 'Error'\n error.message = message\n return [error]\n } else if (thrownErrorsOutsideBoundary.length === 1) {\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to the following error.`\n const error =\n createInstantStack !== null ? createInstantStack() : new Error()\n error.name = 'Error'\n error.message = message\n return [error, thrownErrorsOutsideBoundary[0] as Error]\n } else {\n const message = `Route \"${workStore.route}\": Could not validate \\`unstable_instant\\` because the target segment was prevented from rendering, likely due to one of the following errors.`\n const error =\n createInstantStack !== null ? createInstantStack() : new Error()\n error.name = 'Error'\n error.message = message\n return [error, ...(thrownErrorsOutsideBoundary as Error[])]\n }\n }\n\n // NOTE: We don't care about Suspense above body here,\n // we're only concerned with the validation boundary\n if (prelude !== PreludeState.Full) {\n const dynamicErrors = dynamicValidation.dynamicErrors\n if (dynamicErrors.length > 0) {\n return dynamicErrors\n }\n\n if (prelude === PreludeState.Empty) {\n // If a client component suspended prevented us from rendering a shell\n // but didn't block validation, we don't require a prelude.\n if (dynamicValidation.hasAllowedClientDynamicAboveBoundary) {\n return []\n }\n // If we ever get this far then we messed up the tracking of invalid dynamic.\n return [\n new InvariantError(\n `Route \"${workStore.route}\" failed to render during instant validation and Next.js was unable to determine a reason.`\n ),\n ]\n }\n } else {\n const dynamicErrors = dynamicValidation.dynamicErrors\n if (dynamicErrors.length > 0) {\n return dynamicErrors\n }\n\n if (\n dynamicValidation.hasAllowedDynamic === false &&\n dynamicValidation.dynamicMetadata\n ) {\n return [dynamicValidation.dynamicMetadata]\n }\n }\n // We had a non-empty prelude and there are no dynamic holes\n return []\n}\n","import { isHangingPromiseRejectionError } from '../../server/dynamic-rendering-utils'\nimport { isPostpone } from '../../server/lib/router-utils/is-postpone'\nimport { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'\nimport { isNextRouterError } from './is-next-router-error'\nimport {\n isDynamicPostpone,\n isPrerenderInterruptedError,\n} from '../../server/app-render/dynamic-rendering'\nimport { isDynamicServerError } from './hooks-server-context'\n\nexport function unstable_rethrow(error: unknown): void {\n if (\n isNextRouterError(error) ||\n isBailoutToCSRError(error) ||\n isDynamicServerError(error) ||\n isDynamicPostpone(error) ||\n isPostpone(error) ||\n isHangingPromiseRejectionError(error) ||\n isPrerenderInterruptedError(error)\n ) {\n throw error\n }\n\n if (error instanceof Error && 'cause' in error) {\n unstable_rethrow(error.cause)\n }\n}\n","/**\n * This function should be used to rethrow internal Next.js errors so that they can be handled by the framework.\n * When wrapping an API that uses errors to interrupt control flow, you should use this function before you do any error handling.\n * This function will rethrow the error if it is a Next.js error so it can be handled, otherwise it will do nothing.\n *\n * Read more: [Next.js Docs: `unstable_rethrow`](https://nextjs.org/docs/app/api-reference/functions/unstable_rethrow)\n */\nexport const unstable_rethrow =\n typeof window === 'undefined'\n ? (\n require('./unstable-rethrow.server') as typeof import('./unstable-rethrow.server')\n ).unstable_rethrow\n : (\n require('./unstable-rethrow.browser') as typeof import('./unstable-rethrow.browser')\n ).unstable_rethrow\n","import { ReadonlyURLSearchParams } from './readonly-url-search-params'\n\nexport function unstable_isUnrecognizedActionError(): boolean {\n throw new Error(\n '`unstable_isUnrecognizedActionError` can only be used on the client.'\n )\n}\n\nexport { redirect, permanentRedirect } from './redirect'\nexport { notFound } from './not-found'\nexport { forbidden } from './forbidden'\nexport { unauthorized } from './unauthorized'\nexport { unstable_rethrow } from './unstable-rethrow'\nexport { ReadonlyURLSearchParams }\n\nexport const RedirectType = {\n push: 'push',\n replace: 'replace',\n} as const\n","import type { Params } from '../../server/request/params'\n\nimport React, { useContext, useMemo, use } from 'react'\nimport {\n AppRouterContext,\n LayoutRouterContext,\n type AppRouterInstance,\n} from '../../shared/lib/app-router-context.shared-runtime'\nimport {\n SearchParamsContext,\n PathnameContext,\n PathParamsContext,\n NavigationPromisesContext,\n ReadonlyURLSearchParams,\n} from '../../shared/lib/hooks-client-context.shared-runtime'\nimport {\n computeSelectedLayoutSegment,\n getSelectedLayoutSegmentPath,\n} from '../../shared/lib/segment'\n\nconst useDynamicRouteParams =\n typeof window === 'undefined'\n ? (\n require('../../server/app-render/dynamic-rendering') as typeof import('../../server/app-render/dynamic-rendering')\n ).useDynamicRouteParams\n : undefined\n\nconst useDynamicSearchParams =\n typeof window === 'undefined'\n ? (\n require('../../server/app-render/dynamic-rendering') as typeof import('../../server/app-render/dynamic-rendering')\n ).useDynamicSearchParams\n : undefined\n\nconst {\n instrumentParamsForClientValidation,\n instrumentSearchParamsForClientValidation,\n expectCompleteParamsInClientValidation,\n} =\n typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS\n ? (require('../../server/app-render/instant-validation/instant-samples-client') as typeof import('../../server/app-render/instant-validation/instant-samples-client'))\n : {}\n\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you *read* the current URL's search parameters.\n *\n * Learn more about [`URLSearchParams` on MDN](https://developer.mozilla.org/docs/Web/API/URLSearchParams)\n *\n * @example\n * ```ts\n * \"use client\"\n * import { useSearchParams } from 'next/navigation'\n *\n * export default function Page() {\n * const searchParams = useSearchParams()\n * searchParams.get('foo') // returns 'bar' when ?foo=bar\n * // ...\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useSearchParams`](https://nextjs.org/docs/app/api-reference/functions/use-search-params)\n */\n// Client components API\nexport function useSearchParams(): ReadonlyURLSearchParams {\n useDynamicSearchParams?.('useSearchParams()')\n\n const searchParams = useContext(SearchParamsContext)\n\n // In the case where this is `null`, the compat types added in\n // `next-env.d.ts` will add a new overload that changes the return type to\n // include `null`.\n const readonlySearchParams = useMemo((): ReadonlyURLSearchParams => {\n if (!searchParams) {\n // When the router is not ready in pages, we won't have the search params\n // available.\n return null!\n }\n\n return new ReadonlyURLSearchParams(searchParams)\n }, [searchParams])\n\n // During build-time instant validation, wrap with an proxy\n // so that accessing undeclared search params throws an error.\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n readonlySearchParams\n ) {\n return instrumentSearchParamsForClientValidation!(readonlySearchParams)\n }\n\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext)\n if (navigationPromises) {\n return use(navigationPromises.searchParams)\n }\n }\n\n return readonlySearchParams\n}\n\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read the current URL's pathname.\n *\n * @example\n * ```ts\n * \"use client\"\n * import { usePathname } from 'next/navigation'\n *\n * export default function Page() {\n * const pathname = usePathname() // returns \"/dashboard\" on /dashboard?foo=bar\n * // ...\n * }\n * ```\n *\n * Read more: [Next.js Docs: `usePathname`](https://nextjs.org/docs/app/api-reference/functions/use-pathname)\n */\n// Client components API\nexport function usePathname(): string {\n useDynamicRouteParams?.('usePathname()')\n\n // In the case where this is `null`, the compat types added in `next-env.d.ts`\n // will add a new overload that changes the return type to include `null`.\n const pathname = useContext(PathnameContext) as string\n\n // During build-time instant validation, error if fallback params exist\n // because usePathname() can't return a sensible value without all params.\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n pathname\n ) {\n expectCompleteParamsInClientValidation!('usePathname()')\n return pathname\n }\n\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext)\n if (navigationPromises) {\n return use(navigationPromises.pathname)\n }\n }\n\n return pathname\n}\n\n// Client components API\nexport {\n ServerInsertedHTMLContext,\n useServerInsertedHTML,\n} from '../../shared/lib/server-inserted-html.shared-runtime'\n\n/**\n *\n * This hook allows you to programmatically change routes inside [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components).\n *\n * @example\n * ```ts\n * \"use client\"\n * import { useRouter } from 'next/navigation'\n *\n * export default function Page() {\n * const router = useRouter()\n * // ...\n * router.push('/dashboard') // Navigate to /dashboard\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useRouter`](https://nextjs.org/docs/app/api-reference/functions/use-router)\n */\n// Client components API\nexport function useRouter(): AppRouterInstance {\n const router = useContext(AppRouterContext)\n if (router === null) {\n throw new Error('invariant expected app router to be mounted')\n }\n\n return router\n}\n\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read a route's dynamic params filled in by the current URL.\n *\n * @example\n * ```ts\n * \"use client\"\n * import { useParams } from 'next/navigation'\n *\n * export default function Page() {\n * // on /dashboard/[team] where pathname is /dashboard/nextjs\n * const { team } = useParams() // team === \"nextjs\"\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useParams`](https://nextjs.org/docs/app/api-reference/functions/use-params)\n */\n// Client components API\nexport function useParams<T extends Params = Params>(): T {\n useDynamicRouteParams?.('useParams()')\n\n const params = useContext(PathParamsContext) as T\n\n // During build-time instant validation, wrap with a proxy\n // so that accessing undeclared params throws an error.\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n params\n ) {\n return instrumentParamsForClientValidation!(params)\n }\n\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext)\n if (navigationPromises) {\n return use(navigationPromises.params) as T\n }\n }\n\n return params\n}\n\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read the active route segments **below** the Layout it is called from.\n *\n * @example\n * ```ts\n * 'use client'\n *\n * import { useSelectedLayoutSegments } from 'next/navigation'\n *\n * export default function ExampleClientComponent() {\n * const segments = useSelectedLayoutSegments()\n *\n * return (\n * <ul>\n * {segments.map((segment, index) => (\n * <li key={index}>{segment}</li>\n * ))}\n * </ul>\n * )\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useSelectedLayoutSegments`](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segments)\n */\n// Client components API\nexport function useSelectedLayoutSegments(\n parallelRouteKey: string = 'children'\n): string[] {\n useDynamicRouteParams?.('useSelectedLayoutSegments()')\n\n const context = useContext(LayoutRouterContext)\n // @ts-expect-error This only happens in `pages`. Type is overwritten in navigation.d.ts\n if (!context) return null\n\n // During build-time instant validation, error if fallback params exist\n // because useSelectedLayoutSegments() can't return a sensible value without all params.\n if (\n typeof window === 'undefined' &&\n process.env.__NEXT_CACHE_COMPONENTS &&\n context\n ) {\n expectCompleteParamsInClientValidation!('useSelectedLayoutSegments()')\n }\n\n // Instrument with Suspense DevTools (dev-only)\n if (process.env.NODE_ENV !== 'production' && 'use' in React) {\n const navigationPromises = use(NavigationPromisesContext)\n if (navigationPromises) {\n const promise =\n navigationPromises.selectedLayoutSegmentsPromises?.get(parallelRouteKey)\n if (promise) {\n // We should always have a promise here, but if we don't, it's not worth erroring over.\n // We just won't be able to instrument it, but can still provide the value.\n return use(promise)\n }\n }\n }\n\n return getSelectedLayoutSegmentPath(context.parentTree, parallelRouteKey)\n}\n\n/**\n * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook\n * that lets you read the active route segment **one level below** the Layout it is called from.\n *\n * @example\n * ```ts\n * 'use client'\n * import { useSelectedLayoutSegment } from 'next/navigation'\n *\n * export default function ExampleClientComponent() {\n * const segment = useSelectedLayoutSegment()\n *\n * return <p>Active segment: {segment}</p>\n * }\n * ```\n *\n * Read more: [Next.js Docs: `useSelectedLayoutSegment`](https://nextjs.org/docs/app/api-reference/functions/use-selected-layout-segment)\n */\n// Client components API\nexport function useSelectedLayoutSegment(\n parallelRouteKey: string = 'children'\n): string | null {\n useDynamicRouteParams?.('useSelectedLayoutSegment()')\n const navigationPromises = useContext(NavigationPromisesContext)\n const selectedLayoutSegments = useSelectedLayoutSegments(parallelRouteKey)\n\n // During build-time instant validation, error if fallback params exist\n // because useSelectedLayoutSegment() can't return a sensible value without all params.\n if (typeof window === 'undefined' && process.env.__NEXT_CACHE_COMPONENTS) {\n expectCompleteParamsInClientValidation!('useSelectedLayoutSegment()')\n }\n\n // Instrument with Suspense DevTools (dev-only)\n if (\n process.env.NODE_ENV !== 'production' &&\n navigationPromises &&\n 'use' in React\n ) {\n const promise =\n navigationPromises.selectedLayoutSegmentPromises?.get(parallelRouteKey)\n if (promise) {\n // We should always have a promise here, but if we don't, it's not worth erroring over.\n // We just won't be able to instrument it, but can still provide the value.\n return use(promise)\n }\n }\n\n return computeSelectedLayoutSegment(selectedLayoutSegments, parallelRouteKey)\n}\n\nexport { unstable_isUnrecognizedActionError } from './unrecognized-action-error'\n\n// Shared components APIs\nexport {\n // We need the same class that was used to instantiate the context value\n // Otherwise instanceof checks will fail in usercode\n ReadonlyURLSearchParams,\n}\nexport {\n notFound,\n forbidden,\n unauthorized,\n redirect,\n permanentRedirect,\n RedirectType,\n unstable_rethrow,\n} from './navigation.react-server'\n","module.exports = require('./dist/client/components/navigation')\n","'use client';\n\nimport Link from 'next/link';\nimport { usePathname } from 'next/navigation';\n\nexport default function Nav() {\n const pathname = usePathname();\n\n const navItems = [\n { href: '/', label: '配置' },\n { href: '/ide', label: 'IDE' },\n { href: '/providers', label: '供应商' },\n { href: '/models', label: '模型' },\n { href: '/tokenizer', label: 'Tokenizer' },\n { href: '/logs', label: '日志' },\n ];\n\n return (\n <nav className=\"bg-white/70 backdrop-blur-xl border-b border-emerald-100/30 sticky top-0 z-50\">\n <div className=\"max-w-7xl mx-auto px-6 sm:px-8 lg:px-10\">\n <div className=\"flex items-center justify-between h-16\">\n <div className=\"flex items-center space-x-12\">\n <Link href=\"/\" className=\"flex flex-col group transition-all duration-300\">\n <span className=\"text-xl font-bold text-emerald-700 group-hover:text-emerald-600 transition-colors duration-300 leading-none\">\n AAR\n </span>\n <span className=\"text-[9px] font-medium text-slate-400 tracking-wider uppercase mt-0.5 leading-none\">\n AI Agent Router\n </span>\n </Link>\n <div className=\"hidden sm:flex sm:items-center\">\n {navItems.map((item) => {\n const isActive = pathname === item.href;\n return (\n <Link\n key={item.href}\n href={item.href}\n className=\"relative inline-flex items-center justify-center min-w-[68px] px-3 h-9 text-xs font-medium transition-colors duration-300 group\"\n >\n {/* 固定宽度和高度,完全避免抖动 - 使用绝对定位确保位置不变 */}\n <span \n className={`absolute inset-0 flex items-center justify-center transition-colors duration-300 ${\n isActive \n ? 'text-emerald-700 font-semibold' \n : 'text-slate-500 group-hover:text-slate-700'\n }`}\n >\n {item.label}\n </span>\n {/* 选中状态背景 - 固定尺寸,不改变布局 */}\n <span \n className={`absolute inset-0 rounded-lg transition-all duration-300 ${\n isActive \n ? 'bg-emerald-50/60' \n : 'bg-transparent group-hover:bg-slate-50/40'\n }`}\n />\n </Link>\n );\n })}\n </div>\n </div>\n </div>\n </div>\n </nav>\n );\n}\n"],"names":["_getRequireWildcardCache","nodeInterop","WeakMap","cacheBabelInterop","cacheNodeInterop","_interop_require_wildcard","obj","__esModule","default","cache","has","get","newObj","__proto__","hasPropertyDescriptor","Object","defineProperty","getOwnPropertyDescriptor","key","prototype","hasOwnProperty","call","desc","set","exports","_","assign","searchParamsToUrlQuery","urlQueryToSearchParams","searchParams","query","value","entries","existing","Array","isArray","push","stringifyUrlQueryParam","param","isNaN","String","URLSearchParams","item","append","target","searchParamsList","keys","delete","formatUrl","formatWithValidation","urlObjectKeys","slashedProtocols","urlObj","auth","hostname","protocol","pathname","hash","host","encodeURIComponent","replace","indexOf","port","querystring","search","endsWith","slashes","test","url","process","env","NODE_ENV","forEach","includes","console","warn","useMergedRef","refA","refB","cleanupA","useRef","cleanupB","useCallback","current","cleanupFnA","cleanupFnB","applyRef","cleanup","DecodeError","MiddlewareNotFoundError","MissingStaticPage","NormalizeError","PageNotFoundError","SP","ST","WEB_VITALS","execOnce","getDisplayName","getLocationOrigin","getURL","isAbsoluteUrl","isResSent","loadGetInitialProps","normalizeRepeatedSlashes","stringifyError","fn","used","result","args","ABSOLUTE_URL_REGEX","window","location","href","origin","substring","length","Component","displayName","name","res","finished","headersSent","urlParts","split","urlNoQuery","slice","join","App","ctx","getInitialProps","message","Error","pageProps","props","performance","every","method","constructor","page","code","error","JSON","stringify","stack","parsePath","path","hashIndex","queryIndex","hasQuery","undefined","addPathPrefix","prefix","startsWith","removeTrailingSlash","route","normalizePathTrailingSlash","__NEXT_MANUAL_TRAILING_SLASH","__NEXT_TRAILING_SLASH","addBasePath","basePath","__NEXT_ROUTER_BASEPATH","required","__NEXT_MANUAL_CLIENT_BASE_PATH","warnOnce","warnings","Set","msg","add","ACTION_HMR_REFRESH","ACTION_NAVIGATE","ACTION_REFRESH","ACTION_RESTORE","ACTION_SERVER_ACTION","ACTION_SERVER_PATCH","PrefetchKind","ScrollBehavior","FetchStrategy","NavigationResultTag","PrefetchPriority","createCacheKey","originalHref","nextUrl","originalUrl","URL","cacheKey","PrefetchHint","matchSegment","existingSegment","segment","readVaryParams","thenable","then","noop","status","ACTION_HEADER","FLIGHT_HEADERS","NEXT_ACTION_NOT_FOUND_HEADER","NEXT_ACTION_REVALIDATED_HEADER","NEXT_DID_POSTPONE_HEADER","NEXT_HMR_REFRESH_HASH_COOKIE","NEXT_HMR_REFRESH_HEADER","NEXT_HTML_REQUEST_ID_HEADER","NEXT_INSTANT_PREFETCH_HEADER","NEXT_INSTANT_TEST_COOKIE","NEXT_IS_PRERENDER_HEADER","NEXT_REQUEST_ID_HEADER","NEXT_REWRITTEN_PATH_HEADER","NEXT_REWRITTEN_QUERY_HEADER","NEXT_ROUTER_PREFETCH_HEADER","NEXT_ROUTER_SEGMENT_PREFETCH_HEADER","NEXT_ROUTER_STALE_TIME_HEADER","NEXT_ROUTER_STATE_TREE_HEADER","NEXT_RSC_UNION_QUERY","NEXT_URL","RSC_CONTENT_TYPE_HEADER","RSC_HEADER","InvariantError","options","isThenable","promise","dispatchAppRouterAction","dispatchGestureState","refreshOnInstantNavigationUnlock","useActionQueue","dispatch","__NEXT_EXPOSE_TESTING_API","type","bypassCacheInvalidation","reload","action","setGestureRouterState","state","__DEV__","promisesWithDebugInfo","actionQueue","canonicalState","setState","React","useState","setGesture","useOptimistic","nextDispatch","useAppDevRenderingIndicator","require","appDevRenderingIndicator","stateWithDebugInfo","useMemo","promiseWithDebugInfo","debugInfo","Promise","resolve","asyncState","_debugInfo","use","callServer","actionId","actionArgs","reject","startTransition","findSourceMapURL","__NEXT_DEV_SERVER","filename","document","DEFAULT_SEGMENT_KEY","NOT_FOUND_SEGMENT_KEY","PAGE_SEGMENT_KEY","addSearchParamsIfPageSegment","computeSelectedLayoutSegment","getSegmentValue","getSelectedLayoutSegmentPath","isGroupSegment","isParallelRouteSegment","isPageSegment","stringifiedQuery","segments","parallelRouteKey","rawSegment","tree","first","segmentPath","node","parallelRoutes","children","values","segmentValue","HEAD_REQUEST_KEY","ROOT_SEGMENT_REQUEST_KEY","appendSegmentRequestKeyPart","convertSegmentPathToStaticExportFilename","createSegmentRequestKeyPart","safeName","encodeToFilesystemAndURLSafeString","paramType","encodedName","parentRequestKey","childRequestKeyPart","slotKey","simpleParamValueRegex","base64url","btoa","doesStaticSegmentAppearInURL","getCacheKeyForDynamicParam","getParamValueFromCacheKey","getRenderedPathname","getRenderedSearch","parseDynamicParamFromURLPart","urlSearchParamsToParsedUrlQuery","urlToUrlWithoutFlightMarker","response","rewrittenQuery","headers","rewrittenPath","pathnameParts","partIndex","map","s","i","paramValue","renderedSearch","pageSegmentWithSearchParams","fromEntries","urlWithoutFlightParameters","__NEXT_CONFIG_OUTPUT","paramCacheKey","isCatchAll","createHrefFromUrl","includeHash","createInitialRSCPayloadFromFallbackPrerender","getFlightDataPartsFromPath","getNextFlightSegmentPath","normalizeFlightData","prepareFlightRouterStateForRequest","flightDataPath","flightDataPathLength","seedData","head","isHeadPartial","pathToSegment","isRootRender","fallbackInitialRSCPayload","renderedPathname","canonicalUrl","originalFlightDataPath","f","originalFlightRouterState","payload","c","q","fillInFallbackFlightRouterState","m","G","S","h","b","flightRouterState","filter","p","index","fillInFallbackFlightRouterStateImpl","pathnamePartsIndex","originalSegment","newSegment","doesAppearInURL","paramName","staticSiblings","childPathnamePartsIndex","newChildren","childFlightRouterState","newState","flightSegmentPath","flightData","isHmrRefresh","stripClientOnlyDataFromFlightRouterState","_refreshState","refreshMarker","prefetchHints","cleanedSegment","stripClientOnlyDataFromSegment","cleanedParallelRoutes","childState","djb2Hash","hexHash","str","char","charCodeAt","toString","computeCacheBustingSearchParam","prefetchHeader","segmentPrefetchHeader","stateTreeHeader","nextUrlHeader","setCacheBustingSearchParam","setCacheBustingSearchParamWithHash","uniqueCacheKey","existingSearch","rawQuery","pairs","pair","getAssetToken","getAssetTokenQuery","getDeploymentId","getDeploymentIdQuery","deploymentId","documentElement","dataset","dplId","NEXT_DEPLOYMENT_ID","ampersand","id","NEXT_IMMUTABLE_ASSET_TOKEN","getNavigationBuildId","setNavigationBuildId","globalBuildId","buildId","ACTION_SUFFIX","APP_DIR_ALIAS","CACHE_ONE_YEAR_SECONDS","DOT_NEXT_ALIAS","ESLINT_DEFAULT_DIRS","GSP_NO_RETURNED_VALUE","GSSP_COMPONENT_MEMBER_ERROR","GSSP_NO_RETURNED_VALUE","HTML_CONTENT_TYPE_HEADER","INFINITE_CACHE","INSTRUMENTATION_HOOK_FILENAME","JSON_CONTENT_TYPE_HEADER","MATCHED_PATH_HEADER","MIDDLEWARE_FILENAME","MIDDLEWARE_LOCATION_REGEXP","NEXT_BODY_SUFFIX","NEXT_CACHE_IMPLICIT_TAG_ID","NEXT_CACHE_REVALIDATED_TAGS_HEADER","NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER","NEXT_CACHE_ROOT_PARAM_TAG_ID","NEXT_CACHE_SOFT_TAG_MAX_LENGTH","NEXT_CACHE_TAGS_HEADER","NEXT_CACHE_TAG_MAX_ITEMS","NEXT_CACHE_TAG_MAX_LENGTH","NEXT_DATA_SUFFIX","NEXT_INTERCEPTION_MARKER_PREFIX","NEXT_META_SUFFIX","NEXT_NAV_DEPLOYMENT_ID_HEADER","NEXT_QUERY_PARAM_PREFIX","NEXT_RESUME_HEADER","NEXT_RESUME_STATE_LENGTH_HEADER","NON_STANDARD_NODE_ENV","PAGES_DIR_ALIAS","PRERENDER_REVALIDATE_HEADER","PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER","PROXY_FILENAME","PROXY_LOCATION_REGEXP","PUBLIC_DIR_MIDDLEWARE_CONFLICT","ROOT_DIR_ALIAS","RSC_ACTION_CLIENT_WRAPPER_ALIAS","RSC_ACTION_ENCRYPTION_ALIAS","RSC_ACTION_PROXY_ALIAS","RSC_ACTION_VALIDATE_ALIAS","RSC_CACHE_WRAPPER_ALIAS","RSC_DYNAMIC_IMPORT_WRAPPER_ALIAS","RSC_MOD_REF_PROXY_ALIAS","RSC_SEGMENTS_DIR_SUFFIX","RSC_SEGMENT_SUFFIX","RSC_SUFFIX","SERVER_PROPS_EXPORT_ERROR","SERVER_PROPS_GET_INIT_PROPS_CONFLICT","SERVER_PROPS_SSG_CONFLICT","SERVER_RUNTIME","SSG_FALLBACK_EXPORT_ERROR","SSG_GET_INITIAL_PROPS_CONFLICT","STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR","TEXT_PLAIN_CONTENT_TYPE_HEADER","UNSTABLE_REVALIDATE_RENAME_ERROR","WEBPACK_LAYERS","WEBPACK_RESOURCE_QUERIES","WEB_SOCKET_MAX_RECONNECTIONS","edge","experimentalEdge","nodejs","WEBPACK_LAYERS_NAMES","shared","reactServerComponents","serverSideRendering","actionBrowser","apiNode","apiEdge","middleware","instrument","edgeAsset","appPagesBrowser","pagesDirBrowser","pagesDirEdge","pagesDirNode","GROUP","builtinReact","serverOnly","neutralTarget","clientOnly","bundled","appPages","edgeSSREntry","metadata","metadataRoute","metadataImageMeta","isNavigatingToNewRootLayout","currentTree","nextTree","currentTreeSegment","nextTreeSegment","currentIsRootLayout","IsRootLayout","nextIsRootLayout","slots","currentTreeChildren","slot","nextTreeChild","currentTreeChild","getLastCommittedTree","setLastCommittedTree","lastCommittedTree","deleteFromLru","lruPut","updateLruSize","lruSize","maxLruSize","prev","next","size","ensureCleanupIsScheduled","tail","newNodeSize","prevNodeSize","deleted","pingPrefetchScheduler","ninetyPercentMax","deleteMapEntry","Fallback","createCacheMap","deleteFromCacheMap","getFromCacheMap","isValueExpired","setInCacheMap","setSizeInCacheMap","Revalidation","cacheMap","parent","getOrInitialize","isRevalidation","entry","remainingKeys","previousKey","existingEntry","Map","newEntry","now","currentCacheVersion","rootEntry","getEntryWithFallbackImpl","staleAt","version","lazilyEvictIfNeeded","fallbackEntry","setMapEntryValue","dropRef","oldEntry","ref","parentMap","revalidatingEntry","appendLayoutVaryPath","clonePageVaryPathWithNewSearchParams","finalizeLayoutVaryPath","finalizeMetadataVaryPath","finalizePageVaryPath","getFulfilledRouteVaryPath","getFulfilledSegmentVaryPath","getPartialLayoutVaryPath","getPartialPageVaryPath","getRenderedSearchFromVaryPath","getRouteVaryPath","getSegmentVaryPathForRequest","varyPath","couldBeIntercepted","parentPath","varyPathPart","requestKey","layoutVaryPath","finalizedVaryPath","pageVaryPath","pageRequestKey","fetchStrategy","originalVaryPath","isPage","doesVaryOnSearchParams","Full","PPRRuntime","searchParamsVaryPath","pathParamsVaryPath","patchedVaryPath","newSearch","clonedVaryPath","original","varyParams","clone","discoverKnownRoute","matchKnownRoute","resetKnownRoutes","createEmptyPart","staticChildren","dynamicChild","dynamicChildParamName","dynamicChildParamType","pattern","knownRouteTreeRoot","pendingEntry","routeTree","metadataVaryPath","supportsPerSegmentPrefetching","hasDynamicRewrite","firstPart","remainingParts","fulfilledEntry","fulfillRouteCacheEntry","discoverKnownRoutePart","discoverDynamicChild","part","newChild","mutablePart","parentKnownRoutePart","urlPart","fullTree","segmentAppearsInURL","knownRoutePart","nextUrlPart","nextRemainingParts","writeRouteIntoCache","sibling","existingChild","resultFromChildren","childRouteTree","refreshState","resolvedParams","match","matchKnownRoutePart","matchedPart","acc","reifiedTree","reifyRouteTree","reifiedMetadata","createMetadataRouteTree","syntheticEntry","EntryStatus","Fulfilled","blockedTasks","staticChild","dynamicPart","dynamicPattern","parentPartialVaryPath","partialVaryPath","newValue","newCacheKey","newSlots","newVaryPath","FreshnessPolicy","createInitialCacheNodeForHydration","isDeferredRsc","spawnDynamicRequests","startPPRNavigation","navigatedAt","initialTree","seedHead","seedDynamicStaleAt","accumulation","separateRefreshUrls","scrollRef","task","createCacheNodeOnNavigation","oldUrl","oldRenderedSearch","oldCacheNode","oldRouterState","newRouteTree","newMetadataVaryPath","freshness","isSamePageNavigation","didFindRootLayout","parentNeedsDynamicRequest","parentRefreshState","oldRootRefreshState","updateCacheNodeOnNavigation","oldSegment","createSegmentFromRouteTree","oldRouterStateChildren","seedDataChildren","childDidFindRootLayout","shouldRefreshDynamicData","isLeafSegment","newCacheNode","needsDynamicRequest","dropPrefetchRsc","reuseSharedCacheNode","seedRsc","createCacheNodeForSegment","cacheNode","maybeRefreshState","accumulateRefreshUrl","patchedRouterStateChildren","taskChildren","childNeedsDynamicRequest","dynamicRequestTreeChildren","newCacheNodeSlots","oldCacheNodeSlots","newRouteTreeChild","oldRouterStateChild","seedDataChild","oldSegmentChild","newSegmentChild","seedHeadChild","reuseActiveSegmentInDefaultSlot","oldCacheNodeChild","taskChild","taskChildRoute","dynamicRequestTreeChild","dynamicRequestTree","newFlightRouterState","createDynamicRequestTree","accumulateScrollRef","patchRouterStateWithNewChildren","baseRouterState","newRouterState","refreshUrl","parentRouteTree","reusedUrl","reusedRenderedSearch","oldRefreshState","reusedRouteTree","convertReusedFlightRouterStateToRouteTree","existingCacheNode","createCacheNode","rsc","prefetchRsc","prefetchHead","dynamicStaleAt","bfcacheEntry","readFromBFCacheDuringRegularNavigation","writeToBFCache","writeHeadToBFCache","readFromBFCache","oldRsc","oldRscDidResolve","cachedRsc","isCachedRscPartial","segmentEntry","readSegmentCacheEntry","isPartial","Pending","promiseForFulfilledEntry","waitForSegmentCacheEntry","Empty","Rejected","doesSegmentNeedDynamicRequest","createDeferredRsc","doesHeadNeedDynamicRequest","cachedHead","isCachedHeadPartial","metadataEntry","__NEXT_OPTIMISTIC_ROUTING","previousNavigationDidMismatch","primaryUrl","freshnessPolicy","routeCacheEntry","navigateType","primaryRequestPromise","fetchMissingDynamicData","refreshRequestPromises","scopedDynamicRequestTree","voidPromise","finishNavigationTask","exitStatus","waitForRequestsToFinish","abortRemainingPendingTasks","isHardRetry","primaryRequestResult","dispatchRetryDueToTreeMismatch","seed","onFulfill","remainingCount","onReject","refreshRequestPromise","retryUrl","retryNextUrl","baseTree","originalNavigateType","markRouteEntryAsDynamicRewrite","Date","invalidateRouteCacheEntries","lastCommitted","retryNavigateType","retryAction","previousTree","mpa","fetchServerResponse","convertServerPatchToFullTree","dynamicStaleTime","waitForNavigationLock","staticStageData","staticStageResponse","isResponsePartial","getStaleAt","responseHeaders","writeStaticStageResponseIntoCache","catch","runtimePrefetchStream","processRuntimePrefetchStream","processed","writeDynamicRenderResponseIntoCache","flightDatas","headVaryParams","navigationSeed","computeDynamicStaleAt","didReceiveUnknownParallelRoute","writeDynamicDataIntoNavigationTask","data","serverRouteTree","dynamicData","dynamicHead","finishPendingCacheNode","updateBFCacheEntryStaleAt","serverChildren","dynamicDataChildren","serverRouteTreeChild","dynamicDataChild","taskSegment","serverSegment","childDidReceiveUnknownParallelRoute","dynamicSegmentData","abortPendingCacheNode","childExitStatus","DEFERRED","Symbol","tag","pendingRsc","rej","responseDebugInfo","fulfilledRsc","apply","rejectedRsc","reason","waitForNavigationLockIfActive","ensureLeadingSlash","compareAppPaths","normalizeAppPath","normalizeRscURL","reduce","a","aHasSlot","bHasSlot","localeCompare","INTERCEPTION_ROUTE_MARKERS","extractInterceptionRouteInformation","isInterceptionRouteAppPath","find","interceptingRoute","marker","interceptedRoute","concat","splitInterceptingRoute","computeChangedPath","extractPathFromFlightRouterState","extractSourcePageFromFlightRouterState","getSelectedParams","removeLeadingSlash","segmentToPathname","segmentToSourcePagePathname","dynamicParamType","normalizeSegments","some","childrenPath","childPath","extractSourcePageSegmentsFromFlightRouterState","sourcePageSegments","computeChangedPathImpl","treeA","treeB","segmentA","parallelRoutesA","segmentB","parallelRoutesB","normalizedSegmentA","normalizedSegmentB","parallelRouterKey","changedPath","params","parallelRoute","isDynamicParameter","isJavaScriptURLString","isJavaScriptProtocol","isNavigationLocked","startListeningForInstantNavigationCookie","transitionToCapturedSPA","updateCapturedSPAToTree","parseCookieValue","raw","parsed","parse","rawState","writeCookieValue","cookieStore","domain","lockState","acquireLock","r","releaseLock","self","__next_instant_test","cookie","Math","random","addEventListener","event","changed","fromTree","toTree","from","to","completeHardNavigation","completeSoftNavigation","completeTraverseNavigation","navigate","navigateToKnownRoute","currentUrl","currentRenderedSearch","currentCacheNode","currentFlightRouterState","scrollBehavior","ensurePrefetchThenNavigate","navigateImpl","readRouteCacheEntry","navigateUsingPrefetchedRouteTree","optimisticRoute","deprecated_requestOptimisticRouteCacheEntry","navigateToUnknownRoute","Gesture","prefetchSeed","UnknownDynamicStaleTime","DynamicRequestTreeForEntireRoute","Default","HistoryTraversal","Hydration","RefreshAll","HMRRefresh","promiseForDynamicServerResponse","redirectUrl","pushRef","pendingPush","mpaNavigation","preserveCustomHistoryState","focusAndScrollRef","previousNextUrl","oldState","referringNextUrl","collectedDebugInfo","nextUrlForNewRoute","onlyHashChange","activeScrollRef","forceScroll","NoScroll","oldScrollRef","hashFragment","decodeURIComponent","dynamicStaleTimeSeconds","baseData","treePatch","dataPatch","headPatch","convertServerPatchToFullTreeImpl","finalFlightRouterState","convertRootFlightRouterStateToRouteTree","updatedParallelRouteKey","baseTreeChildren","baseSeedDataChildren","newTreeChildren","newSeedDataChildren","childBaseRouterState","childBaseSeedData","clonedTree","clonedSeedData","compressedRefreshState","isEmptySeedDataPartial","link","getLinkForCurrentNavigation","PPR","schedulePrefetchTask","DYNAMIC_STALETIME_MS","STATIC_STALETIME_MS","navigateReducer","Number","__NEXT_CLIENT_ROUTER_DYNAMIC_STALETIME","getStaleTimeMs","__NEXT_CLIENT_ROUTER_STATIC_STALETIME","isExternalUrl","getElementById","navigateUsingSegmentCache","invalidateBfCache","bfcacheMap","currentBfCacheVersion","newStaleAt","createFetch","createFromNextReadableStream","decodeStaticStage","processFetch","resolveStaticStageData","createFromReadableStream","createFromReadableStreamBrowser","createFromFetch","createFromFetchBrowser","createDebugChannel","__NEXT_REACT_DEBUG_CHANNEL","doMpaNavigation","isPageUnloading","isLegacyPPR","__NEXT_PPR","__NEXT_CACHE_COMPONENTS","shouldImmediatelyDecode","responseUrl","redirected","contentType","interception","postponed","isFlightResponse","ok","body","TURBOPACK","waitForWebpackRuntimeHotUpdate","flightResponsePromise","allowPartialStream","flightResponse","cacheData","all","normalizedFlightData","d","err","stream","stripIsPartialByte","responseStream","__NEXT_EXPERIMENTAL_CACHED_NAVIGATIONS","stream1","stream2","tee","responseBodyClone","strippedResponse","Response","statusText","cancel","l","staticStageByteLengthPromise","staticStageByteLength","truncatedStream","truncateStream","fetchPriority","signal","__NEXT_TEST_MODE","__next_r","crypto","getRandomValues","Uint32Array","fetchOptions","credentials","priority","fetchUrl","fetch","fetchPromise","createFromNextFetch","browserResponse","__NEXT_CLIENT_VALIDATE_RSC_REQUEST_HEADERS","MAX_REDIRECTS","n","rscResponse","flightStream","requestHeaders","debugChannel","unstable_allowPartialStream","promiseForResponse","byteLength","reader","getReader","remaining","ReadableStream","pull","controller","close","done","read","enqueue","subarray","createPromiseWithResolvers","attemptToFulfillDynamicSegmentFromBFCache","attemptToUpgradeSegmentFromBFCache","canNewFetchStrategyProvideMoreContent","convertRouteTreeToFlightRouterState","createDetachedSegmentCacheEntry","fetchInlinedSegmentsOnCacheMiss","fetchRouteOnCacheMiss","fetchSegmentOnCacheMiss","fetchSegmentPrefetchesUsingDynamicRequest","getCurrentRouteCacheVersion","getCurrentSegmentCacheVersion","invalidateEntirePrefetchCache","invalidateSegmentCacheEntries","overwriteRevalidatingSegmentCacheEntry","pingInvalidationListeners","readOrCreateRevalidatingSegmentEntry","readOrCreateRouteCacheEntry","readOrCreateSegmentCacheEntry","upgradeToPendingSegment","upsertSegmentEntry","staleTimeSeconds","max","isOutputExportMode","MetadataOnlyRequestTree","routeCacheMap","segmentCacheMap","invalidationListeners","currentRouteCacheVersion","currentSegmentCacheVersion","pingVisibleLinks","attachInvalidationListener","onInvalidate","notifyInvalidationListener","reportError","tasks","isPrefetchTaskDirty","readRevalidatingSegmentCacheEntry","promiseWithResolvers","createDetachedRouteCacheEntry","Infinity","requestedUrl","requestedSearch","urlWithoutSearchParams","routeWithNoSearchParams","createPrefetchRequestKey","canonicalUrlForRouteWithNoSearchParams","optimisticCanonicalSearch","optimisticRenderedSearch","optimisticUrl","optimisticCanonicalUrl","optimisticRouteTree","deprecated_createOptimisticRouteTree","optimisticMetadataTree","optimisticEntry","newRenderedSearch","clonedSlots","originalSlots","childTree","varyPathForRequest","candidateEntry","rejectedEntry","emptyEntry","dynamicPrefetchStaleAt","pendingSegment","fulfillSegmentCacheEntry","segmentVaryPath","upserted","pingBlockedTasks","pingPrefetchTask","segmentCacheEntry","rejectRouteCacheEntry","rejectSegmentCacheEntry","convertRootTreePrefetchToRouteTree","rootTree","rootSegment","convertTreePrefetchToRouteTree","prefetch","prefetchSlots","childPrefetch","childSegmentName","childParam","childDoesAppearInURL","childSegment","childPartialVaryPath","childParamValue","childParamKey","siblings","childRequestKey","convertFlightRouterStateToRouteTree","requestKeyPart","parentRenderedSearch","childRouterState","addInstantPrefetchHeaderIfLocked","urlAfterRedirects","headResponse","fetchPrefetchResponse","addSegmentPathToUrlInOutputExportMode","varyHeader","closed","routeIsPPREnabled","prefetchStream","responseSize","createNonTaskyPrefetchResponseStream","serverData","headVaryParamsThenable","writeDynamicTreeResponseIntoCache","LoadingBoundary","fulfilledVaryPath","routeKey","normalizedRequestKey","requestUrl","staleTime","__NEXT_VARY_PARAMS","spawnedEntries","rejectSegmentEntriesIfStillPending","fillInlinedSegmentEntries","headStaleAt","headKey","ownedHeadEntry","inlinedNode","ownedEntry","childInlinedNode","fulfilledEntries","bufferedResponseSize","createIncrementalPrefetchResponseStream","onResponseSizeUpdate","totalBytesReceivedSoFar","averageSize","originalPathname","normalizedFlightDataResult","getStaleAtFromHeader","metadataTree","flightDataEntry","writeSeedDataIntoCache","fulfillEntrySpawnedByRuntimePrefetch","entriesOwnedByCurrentTask","varyParamsThenable","childSeedData","segmentVaryParams","possiblyNewEntry","chunks","buffer","Uint8Array","offset","chunk","start","originalFlightStream","onStreamClose","totalByteLength","staticUrl","routeDir","staticExportFilename","currentStrategy","newStrategy","parseInt","staleTimeMs","staleTimeIterable","defaultIsPartial","firstByte","hasMarker","remainder","cancelPrefetchTask","reschedulePrefetchTask","startRevalidationCooldown","scheduleMicrotask","queueMicrotask","setTimeout","taskHeap","inProgressRequests","sortIdCounter","didScheduleMicrotask","mostRecentlyHoveredLink","REVALIDATION_COOLDOWN_MS","revalidationCooldownTimeoutHandle","clearTimeout","treeAtTimeOfPrefetch","_onComplete","routeCacheVersion","segmentCacheVersion","phase","hasBackgroundWork","spawnedRuntimePrefetches","sortId","isCanceled","_heapIndex","trackMostRecentlyHoveredLink","heapPush","heapDelete","onComplete","Intent","heapResift","Background","processQueueInMicrotask","hasNetworkBandwidth","spawnPrefetchSubtask","prefetchSubtask","onPrefetchConnectionClosed","heapPeek","pingRoute","heapPop","background","pingRootRouteTree","keyWithoutSearch","routeWithoutSearch","SubtreeHasInstant","pingStaticHead","pingSharedPartOfCacheComponentsTree","pingRuntimeHead","requestTree","pingRuntimePrefetches","diffRouteTreeAgainstCurrent","pingStaticSegmentData","pingRouteTreeAndIncludeDynamicData","oldTree","newTree","oldTreeChildren","newTreeChild","newTreeChildSegment","oldTreeChild","oldTreeChildSegment","doesCurrentSegmentMatchCachedSegment","pingNewPartOfCacheComponentsTree","HasRuntimePrefetch","requestTreeChildren","requestTreeChild","subtreeHasLoadingBoundary","SegmentHasLoadingBoundary","SubtreeHasLoadingBoundary","pingPPRDisabledRouteTreeUpToLoadingBoundary","refetchMarkerContext","refetchMarker","segmentHasLoadingBoundary","isInsideRefetchingParent","spawnedSegment","fulfilled","pingFullSegmentRevalidation","__NEXT_PREFETCH_INLINING","inlinedEntries","collectInlinedEntries","pingPPRSegmentRevalidation","collectInlinedEntriesImpl","headEntry","revalidatingSegment","nonEmptyRevalidatingSegment","emptySegment","currentSegment","cachedSegment","compareQueuePriority","priorityDiff","phaseDiff","heap","heapSiftUp","last","pop","heapSiftDown","parentIndex","halfLength","leftIndex","left","rightIndex","right","IDLE_LINK_STATUS","PENDING_LINK_STATUS","mountFormInstance","mountLinkInstance","onLinkVisibilityChanged","onNavigationIntent","setLinkForCurrentNavigation","unmountLinkForCurrentNavigation","unmountPrefetchableInstance","linkForMostRecentNavigation","pending","setOptimisticLinkStatus","prefetchable","prefetchableAndVisible","observer","IntersectionObserver","handleIntersect","rootMargin","observeVisibility","element","instance","existingInstance","observe","coercePrefetchableUrl","createPrefetchURL","reportErrorFn","router","prefetchEnabled","prefetchURL","isVisible","prefetchTask","prefetchHref","unobserve","intersectionRatio","rescheduleLinkPrefetch","unstable_upgradeToDynamicPrefetch","__NEXT_DYNAMIC_ON_HOVER","existingPrefetchTask","getCurrentAppRouterState","appRouterState","scheduleSegmentPrefetchTask","pathHasPrefix","hasBasePath","isLocalURL","locationOrigin","resolved","errorOnce","errors","LinkComponent","useLinkStatus","isModifiedEvent","eventTarget","currentTarget","getAttribute","metaKey","ctrlKey","shiftKey","altKey","nativeEvent","which","linkClicked","e","linkInstanceRef","scroll","onNavigate","transitionTypes","nodeName","isAnchorNodeName","toUpperCase","hasAttribute","preventDefault","isDefaultPrevented","dispatchNavigateAction","formatStringOrUrl","urlObjOrString","linkStatus","hrefProp","as","asProp","childrenProp","prefetchProp","passHref","shallow","onClick","onMouseEnter","onMouseEnterProp","onTouchStart","onTouchStartProp","legacyBehavior","forwardedRef","unstable_dynamicOnHover","restProps","useContext","AppRouterContext","getFetchStrategyFromPrefetchProp","createPropError","expected","actual","requiredPropsGuard","requiredProps","optionalPropsGuard","optionalProps","valType","resolvedHref","formattedHref","locale","hasDynamicSegment","child","$$typeof","for","Children","only","childRef","observeLinkVisibilityOnMount","mergedRef","childProps","defaultPrevented","upgradeToDynamicPrefetch","__NEXT_LINK_NO_TOUCH_START","cloneElement","LinkStatusContext","Provider","createContext","UnrecognizedActionError","unstable_isUnrecognizedActionError","ReadonlyURLSearchParams","ReadonlyURLSearchParamsError","sort","RedirectStatusCode","REDIRECT_ERROR_CODE","isRedirectError","digest","errorCode","destination","at","statusCode","getRedirectError","getRedirectStatusCodeFromError","getRedirectTypeFromError","getURLFromRedirectError","permanentRedirect","redirect","actionAsyncStorage","TemporaryRedirect","getStore","isAction","PermanentRedirect","HTTPAccessErrorStatus","HTTP_ERROR_FALLBACK_ERROR_CODE","getAccessFallbackErrorTypeByStatus","getAccessFallbackHTTPStatus","isHTTPAccessFallbackError","NOT_FOUND","FORBIDDEN","UNAUTHORIZED","ALLOWED_CODES","httpStatus","notFound","DIGEST","forbidden","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","unauthorized","RenderStage","StagedRenderingController","abortSignal","abandonController","shouldTrackSyncIO","currentStage","syncInterruptReason","staticStageEndTime","runtimeStageEndTime","staticStageListeners","earlyRuntimeStageListeners","runtimeStageListeners","dynamicStageListeners","staticStagePromise","earlyRuntimeStagePromise","runtimeStagePromise","dynamicStagePromise","ignoreReject","once","abandonRender","onStage","stage","callback","shouldTrackSyncInterrupt","syncInterruptCurrentStageWithReason","abort","advanceStage","getSyncInterruptReason","getStaticStageEndTime","getRuntimeStageEndTime","resolveStaticStage","resolveEarlyRuntimeStage","resolveRuntimeStage","timeOrigin","resolveDynamicStage","staticListeners","earlyRuntimeListeners","runtimeListeners","dynamicListeners","getStagePromise","waitForStage","delayUntilStage","resolvedValue","ioTriggerPromise","makeDevtoolsIOPromiseFromIOTrigger","ioTrigger","bind","delayUntilRuntimeStage","getRuntimeStage","isHangingPromiseRejectionError","makeDevtoolsIOAwarePromise","makeHangingPromise","HANGING_PROMISE_REJECTION","HangingPromiseRejectionError","expression","abortListenersBySignal","aborted","hangingPromise","boundRejection","currentListeners","listeners","underlying","requestStore","stagedRendering","EarlyStatic","EarlyRuntime","Runtime","prerenderStore","isPostpone","REACT_POSTPONE_TYPE","BailoutToCSRError","isBailoutToCSRError","BAILOUT_TO_CSR","isNextRouterError","DynamicServerError","isDynamicServerError","DYNAMIC_ERROR_CODE","description","StaticGenBailoutError","isStaticGenBailoutError","NEXT_STATIC_GEN_BAILOUT","METADATA_BOUNDARY_NAME","OUTLET_BOUNDARY_NAME","ROOT_LAYOUT_BOUNDARY_NAME","VIEWPORT_BOUNDARY_NAME","atLeastOneTask","scheduleImmediate","scheduleOnNextTick","waitAtLeastOneReactRenderTask","cb","NEXT_RUNTIME","nextTick","setImmediate","INSTANT_VALIDATION_BOUNDARY_NAME","DynamicHoleKind","Postpone","PreludeState","abortAndThrowOnSynchronousRequestDataAccess","abortOnSynchronousPlatformIOAccess","accessedDynamicData","annotateDynamicAccess","consumeDynamicAccess","createDynamicTrackingState","createDynamicValidationState","createHangingInputAbortSignal","createInstantValidationState","createRenderInBrowserAbortSignal","formatDynamicAPIAccesses","getFirstDynamicReason","getNavigationDisallowedDynamicReasons","getStaticShellDisallowedDynamicReasons","isDynamicPostpone","isPrerenderInterruptedError","logDisallowedDynamicError","markCurrentScopeAsDynamic","postponeWithTracking","throwIfDisallowedDynamic","throwToInterruptStaticGeneration","trackAllowedDynamicAccess","trackDynamicDataInDynamicRender","trackDynamicHoleInNavigation","trackDynamicHoleInRuntimeShell","trackDynamicHoleInStaticShell","trackThrownErrorInNavigation","useDynamicRouteParams","useDynamicSearchParams","hasPostpone","unstable_postpone","isDebugDynamicAccesses","dynamicAccesses","syncDynamicErrorWithStack","hasSuspenseAboveBody","hasDynamicMetadata","dynamicMetadata","hasDynamicViewport","hasAllowedDynamic","dynamicErrors","trackingState","store","workUnitStore","forceDynamic","forceStatic","dynamicShouldError","dynamicTracking","revalidate","dynamicUsageDescription","dynamicUsageStack","usedDynamic","abortOnSynchronousDynamicDataAccess","createPrerenderInterruptedError","errorWithStack","prerenderSignal","workUnitAsyncStorage","assertPostpone","createPostponeReason","isDynamicPostponeReason","NEXT_PRERENDER_INTERRUPTED","serverDynamic","clientDynamic","access","line","AbortController","cacheSignal","inputReady","workStore","workAsyncStorage","fallbackParams","fallbackRouteParams","renderSignal","throwForMissingRequestStore","hasSuspenseRegex","bodyAndImplicitTags","hasSuspenseBeforeRootLayoutWithoutBodyOrImplicitBodyRegex","RegExp","hasMetadataRegex","hasViewportRegex","hasOutletRegex","hasInstantValidationBoundaryRegex","componentStack","dynamicValidation","addErrorContext","createInstantStack","hasAllowedClientDynamicAboveBoundary","validationPreventingErrors","thrownErrorsOutsideBoundary","kind","boundaryState","usageDescription","boundaryLocation","exec","expectedIds","renderedIds","suspenseLocation","syncError","cause","thrownValue","ownerStack","captureOwnerStack","prelude","configAllowsBlocking","validationSampleTracking","missingSampleErrors","unstable_rethrow","RedirectType","ServerInsertedHTMLContext","useParams","usePathname","useRouter","useSearchParams","useSelectedLayoutSegment","useSelectedLayoutSegments","useServerInsertedHTML","instrumentParamsForClientValidation","instrumentSearchParamsForClientValidation","expectCompleteParamsInClientValidation","SearchParamsContext","readonlySearchParams","navigationPromises","NavigationPromisesContext","PathnameContext","PathParamsContext","context","LayoutRouterContext","selectedLayoutSegmentsPromises","parentTree","selectedLayoutSegments","selectedLayoutSegmentPromises","module","Nav","navItems","label","className","isActive"],"mappings":"6CAEA,SAASA,EAAyBC,CAAW,EACzC,GAAuB,YAAnB,OAAOC,QAAwB,OAAO,KA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,MAAO,IAAK,EAC9B,CAgBqBz5C,GAAG,CAAC,AAAChR,IACb,IAAM2qD,EAAW7pD,IAAad,EAAKsE,IAAI,CACvC,MACE,CAAA,EAAA,EAAA,IAAA,EAAC,EAAA,OAAI,CAAA,CAEHA,KAAMtE,EAAKsE,IAAI,CACfomD,UAAU,4IAGV,CAAA,EAAA,EAAA,GAAA,EAAC,OAAA,CACCA,UAAW,CAAC,iFAAiF,EAC3FC,EACI,iCACA,4CAAA,CACJ,UAED3qD,EAAKyqD,KAAK,GAGb,CAAA,EAAA,EAAA,GAAA,EAAC,OAAA,CACCC,UAAW,CAAC,wDAAwD,EAClEC,EACI,mBACA,4CAAA,CACJ,KApBC3qD,EAAKsE,IAAI,CAwBpB,aAOd","ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84]}