@wular/pnext 0.1.5 → 0.1.7

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 (302) hide show
  1. package/bin/pnext +9 -2
  2. package/dist/server/_chunks/aliases-j47a10ce.js +44 -0
  3. package/dist/server/_chunks/analyze-arswqe6s.js +445 -0
  4. package/dist/server/_chunks/boot-af0mv3dy.js +36 -0
  5. package/dist/server/_chunks/build-spy3dxp4.js +84 -0
  6. package/dist/server/_chunks/build-t9h0hec3.js +3550 -0
  7. package/dist/server/_chunks/build-tier-m7yvqz61.js +2472 -0
  8. package/dist/server/_chunks/compile-53j02j27.js +22 -0
  9. package/dist/server/_chunks/config-1yzwexq6.js +27 -0
  10. package/dist/server/_chunks/config-n2z7yxps.js +22 -0
  11. package/dist/server/_chunks/create-meec9hs6.js +134 -0
  12. package/dist/server/_chunks/dev-fjmqg6en.js +220 -0
  13. package/dist/server/_chunks/esbuild-yyktfrtt.js +15 -0
  14. package/dist/server/_chunks/generate-n9sh6hzt.js +21 -0
  15. package/dist/server/_chunks/index-0374j2b9.js +66 -0
  16. package/dist/server/_chunks/index-06nyqntx.js +213 -0
  17. package/dist/server/_chunks/index-1011cscr.js +5263 -0
  18. package/dist/server/_chunks/index-11sfk4hb.js +170 -0
  19. package/dist/server/_chunks/index-20ppawv7.js +297 -0
  20. package/dist/server/_chunks/index-2dv4y4wd.js +1065 -0
  21. package/dist/server/_chunks/index-2vz0wzdn.js +59 -0
  22. package/dist/server/_chunks/index-2wfv4kvx.js +182 -0
  23. package/dist/server/_chunks/index-357na4a8.js +109 -0
  24. package/dist/server/_chunks/index-3b3at80h.js +109 -0
  25. package/dist/server/_chunks/index-3tf1xjsp.js +6166 -0
  26. package/dist/server/_chunks/index-3xbr4eyv.js +105 -0
  27. package/dist/server/_chunks/index-4399bvd2.js +18 -0
  28. package/dist/server/_chunks/index-4hgjrqh7.js +851 -0
  29. package/dist/server/_chunks/index-4q2gbfwk.js +2530 -0
  30. package/dist/server/_chunks/index-4t92hdxd.js +172 -0
  31. package/dist/server/_chunks/index-4zzebszd.js +10 -0
  32. package/dist/server/_chunks/index-5gyr4emz.js +107 -0
  33. package/dist/server/_chunks/index-5hr4062s.js +70 -0
  34. package/dist/server/_chunks/index-68m3mwbd.js +84 -0
  35. package/dist/server/_chunks/index-6b009mt0.js +56 -0
  36. package/dist/server/_chunks/index-6e4fqv30.js +588 -0
  37. package/dist/server/_chunks/index-6gex3pfa.js +15 -0
  38. package/dist/server/_chunks/index-6kp9r0d9.js +11 -0
  39. package/dist/server/_chunks/index-6q7zvrap.js +134 -0
  40. package/dist/server/_chunks/index-73z4esab.js +38 -0
  41. package/dist/server/_chunks/index-79ngvam8.js +60 -0
  42. package/dist/server/_chunks/index-7wc9n8be.js +25 -0
  43. package/dist/server/_chunks/index-8k7pfejn.js +1599 -0
  44. package/dist/server/_chunks/index-8kcxdfya.js +206 -0
  45. package/dist/server/_chunks/index-91x12ykq.js +274 -0
  46. package/dist/server/_chunks/index-9ch50vtq.js +18 -0
  47. package/dist/server/_chunks/index-9hx2641q.js +28 -0
  48. package/dist/server/_chunks/index-9n2914ww.js +535 -0
  49. package/dist/server/_chunks/index-9ych9ma8.js +207 -0
  50. package/dist/server/_chunks/index-b6wtkdp4.js +24 -0
  51. package/dist/server/_chunks/index-bcws5eh2.js +35 -0
  52. package/dist/server/_chunks/index-c0g2wf3z.js +92 -0
  53. package/dist/server/_chunks/index-cf4rvxv6.js +95 -0
  54. package/dist/server/_chunks/index-cjgqs13g.js +65 -0
  55. package/dist/server/_chunks/index-ckkdpht5.js +41 -0
  56. package/dist/server/_chunks/index-cyfednwb.js +87 -0
  57. package/dist/server/_chunks/index-danncfhy.js +311 -0
  58. package/dist/server/_chunks/index-dg0f05zs.js +199 -0
  59. package/dist/server/_chunks/index-e3a6yx84.js +18 -0
  60. package/dist/server/_chunks/index-e88tyv35.js +45 -0
  61. package/dist/server/_chunks/index-eajaspjk.js +1253 -0
  62. package/dist/server/_chunks/index-eeaanp2e.js +483 -0
  63. package/dist/server/_chunks/index-egykcqg3.js +101 -0
  64. package/dist/server/_chunks/index-en7n9f7m.js +22 -0
  65. package/dist/server/_chunks/index-ezgj0tr1.js +88 -0
  66. package/dist/server/_chunks/index-fkp000p1.js +590 -0
  67. package/dist/server/_chunks/index-fn1chkkd.js +214 -0
  68. package/dist/server/_chunks/index-fp8r0sqs.js +64 -0
  69. package/dist/server/_chunks/index-ggk2j965.js +9432 -0
  70. package/dist/server/_chunks/index-grta8ap3.js +238 -0
  71. package/dist/server/_chunks/index-h2a70tg4.js +7 -0
  72. package/dist/server/_chunks/index-h4xy648y.js +51 -0
  73. package/dist/server/_chunks/index-hkdfj58q.js +92 -0
  74. package/dist/server/_chunks/index-j2zrcp1k.js +66 -0
  75. package/dist/server/_chunks/index-jcsjq3d1.js +20 -0
  76. package/dist/server/_chunks/index-jepjvcrf.js +198 -0
  77. package/dist/server/_chunks/index-jks0x0a1.js +14 -0
  78. package/dist/server/_chunks/index-jx7bqvw1.js +57 -0
  79. package/dist/server/_chunks/index-k1g3epw0.js +1299 -0
  80. package/dist/server/_chunks/index-knp0s912.js +7 -0
  81. package/dist/server/_chunks/index-kq8kpzye.js +472 -0
  82. package/dist/server/_chunks/index-kqyy1d4f.js +50 -0
  83. package/dist/server/_chunks/index-kresp2n8.js +445 -0
  84. package/dist/server/_chunks/index-ms9v9tnx.js +31 -0
  85. package/dist/server/_chunks/index-n4hxpng2.js +11 -0
  86. package/dist/server/_chunks/index-ncnes8c6.js +17 -0
  87. package/dist/server/_chunks/index-nqh3xhdc.js +57 -0
  88. package/dist/server/_chunks/index-nyrba2kr.js +4130 -0
  89. package/dist/server/_chunks/index-p77b4kcx.js +296 -0
  90. package/dist/server/_chunks/index-pym1cezq.js +39 -0
  91. package/dist/server/_chunks/index-q738kkhj.js +100 -0
  92. package/dist/server/_chunks/index-qjj6gddn.js +54 -0
  93. package/dist/server/_chunks/index-qm6kmhqs.js +110 -0
  94. package/dist/server/_chunks/index-qn4z5s3c.js +819 -0
  95. package/dist/server/_chunks/index-qpwsgt3a.js +158 -0
  96. package/dist/server/_chunks/index-r97ptz1q.js +97 -0
  97. package/dist/server/_chunks/index-ras0sdab.js +26 -0
  98. package/dist/server/_chunks/index-rcs322t1.js +19 -0
  99. package/dist/server/_chunks/index-rn8dyr1f.js +126 -0
  100. package/dist/server/_chunks/index-rt9qq1va.js +4 -0
  101. package/dist/server/_chunks/index-rthrsed5.js +356 -0
  102. package/dist/server/_chunks/index-sctcgyvv.js +185 -0
  103. package/dist/server/_chunks/index-sjpckxqn.js +213 -0
  104. package/dist/server/_chunks/index-sq3kvz3g.js +200 -0
  105. package/dist/server/_chunks/index-stbk3jhn.js +31 -0
  106. package/dist/server/_chunks/index-sv8m6789.js +266 -0
  107. package/dist/server/_chunks/index-tgcakdxc.js +125 -0
  108. package/dist/server/_chunks/index-tgsfjmep.js +74 -0
  109. package/dist/server/_chunks/index-tq0pc7eg.js +154 -0
  110. package/dist/server/_chunks/index-tq1f96v7.js +51 -0
  111. package/dist/server/_chunks/index-tqn2qnnn.js +241 -0
  112. package/dist/server/_chunks/index-tvqkq6e6.js +128 -0
  113. package/dist/server/_chunks/index-v1ags1na.js +132 -0
  114. package/dist/server/_chunks/index-vvmmknm1.js +1431 -0
  115. package/dist/server/_chunks/index-vvq7rqtn.js +329 -0
  116. package/dist/server/_chunks/index-vz0km5qk.js +33 -0
  117. package/dist/server/_chunks/index-w6h8m6vp.js +138 -0
  118. package/dist/server/_chunks/index-web361b8.js +138 -0
  119. package/dist/server/_chunks/index-wpfhfbs4.js +194 -0
  120. package/dist/server/_chunks/index-x0y005nh.js +283 -0
  121. package/dist/server/_chunks/index-x3yn4ywm.js +22 -0
  122. package/dist/server/_chunks/index-x93hv0sc.js +271 -0
  123. package/dist/server/_chunks/index-xvj80c3a.js +30 -0
  124. package/dist/server/_chunks/index-xywjg2vc.js +100 -0
  125. package/dist/server/_chunks/index-y2jr2n72.js +152 -0
  126. package/dist/server/_chunks/index-y36a0ybw.js +57 -0
  127. package/dist/server/_chunks/index-ye9hmsvf.js +47 -0
  128. package/dist/server/_chunks/index-yhxkxghe.js +56 -0
  129. package/dist/server/_chunks/index-ym67zqxp.js +130 -0
  130. package/dist/server/_chunks/index-ytjvpbm2.js +736 -0
  131. package/dist/server/_chunks/index-yz54pxrh.js +960 -0
  132. package/dist/server/_chunks/index-z4z9zv3b.js +733 -0
  133. package/dist/server/_chunks/index-z84ab1w0.js +1270 -0
  134. package/dist/server/_chunks/index-z88qv16t.js +11 -0
  135. package/dist/server/_chunks/index-zqpqyg8p.js +666 -0
  136. package/dist/server/_chunks/loader-7yw0j98z.js +78 -0
  137. package/dist/server/_chunks/modules-jn8bmbn8.js +74 -0
  138. package/dist/server/_chunks/pipeline-yy9jhydf.js +832 -0
  139. package/dist/server/_chunks/production-jar9ztm3.js +44 -0
  140. package/dist/server/_chunks/proxy-config-j84dgksn.js +21 -0
  141. package/dist/server/_chunks/proxy-w1d0wmsn.js +33 -0
  142. package/dist/server/_chunks/router-k1reahfn.js +498 -0
  143. package/dist/server/_chunks/routes-2s277fc6.js +64 -0
  144. package/dist/server/_chunks/run-pvd8bs1t.js +696 -0
  145. package/dist/server/_chunks/server-mt4a994c.js +1835 -0
  146. package/dist/server/_chunks/tsconfig-defaults-1nb3308g.js +20 -0
  147. package/dist/server/_chunks/typegen-0qr0459b.js +35 -0
  148. package/dist/server/api/client-cache.js +14 -0
  149. package/dist/server/cli/index.js +378 -0
  150. package/dist/server/cli/start.js +137 -0
  151. package/dist/server/client/reference.js +16 -0
  152. package/dist/server/compat/next/cache.js +56 -0
  153. package/dist/server/compat/next/canonical-url.js +13 -0
  154. package/dist/server/compat/next/client-cache.js +57 -0
  155. package/dist/server/compat/next/client-navigation.js +232 -0
  156. package/dist/server/compat/next/client-only.js +1 -0
  157. package/dist/server/compat/next/client-script.js +178 -0
  158. package/dist/server/compat/next/client-server.js +34 -0
  159. package/dist/server/compat/next/config-headers.js +32 -0
  160. package/dist/server/compat/next/config-loader.js +25 -0
  161. package/dist/server/compat/next/config.js +10 -0
  162. package/dist/server/compat/next/constants.js +18 -0
  163. package/dist/server/compat/next/custom-server.js +10 -0
  164. package/dist/server/compat/next/dist/client/components/app-router-headers.js +48 -0
  165. package/dist/server/compat/next/dist/server/web/spec-extension/revalidate.js +27 -0
  166. package/dist/server/compat/next/dist/server/web/spec-extension/unstable-cache.js +25 -0
  167. package/dist/server/compat/next/dist/server/web/spec-extension/unstable-no-store.js +25 -0
  168. package/dist/server/compat/next/dynamic.js +32 -0
  169. package/dist/server/compat/next/error.js +112 -0
  170. package/dist/server/compat/next/font/cache.js +14 -0
  171. package/dist/server/compat/next/font/google.js +3 -0
  172. package/dist/server/compat/next/font/index.js +1 -0
  173. package/dist/server/compat/next/font/local.js +22 -0
  174. package/dist/server/compat/next/font/runtime-client.js +33 -0
  175. package/dist/server/compat/next/font/runtime.js +41 -0
  176. package/dist/server/compat/next/font/shared.js +22 -0
  177. package/dist/server/compat/next/form.js +129 -0
  178. package/dist/server/compat/next/head.js +10 -0
  179. package/dist/server/compat/next/headers.js +30 -0
  180. package/dist/server/compat/next/image/client.js +11 -0
  181. package/dist/server/compat/next/image/config.js +18 -0
  182. package/dist/server/compat/next/image/optimizer.js +25 -0
  183. package/dist/server/compat/next/image/patterns.js +12 -0
  184. package/dist/server/compat/next/image/props.js +16 -0
  185. package/dist/server/compat/next/image/shared.js +86 -0
  186. package/dist/server/compat/next/image/static-metadata.js +32 -0
  187. package/dist/server/compat/next/image/validate.js +8 -0
  188. package/dist/server/compat/next/image.js +59 -0
  189. package/dist/server/compat/next/index.js +1 -0
  190. package/dist/server/compat/next/legacy-image.js +78 -0
  191. package/dist/server/compat/next/legacy-request-apis.js +24 -0
  192. package/dist/server/compat/next/link-transform.js +14 -0
  193. package/dist/server/compat/next/link.js +14 -0
  194. package/dist/server/compat/next/navigation.js +190 -0
  195. package/dist/server/compat/next/offline.js +45 -0
  196. package/dist/server/compat/next/og.js +8 -0
  197. package/dist/server/compat/next/preferred-region.js +8 -0
  198. package/dist/server/compat/next/redirects.js +30 -0
  199. package/dist/server/compat/next/resource-hints.js +30 -0
  200. package/dist/server/compat/next/rewrites.js +41 -0
  201. package/dist/server/compat/next/root-params.js +121 -0
  202. package/dist/server/compat/next/route-state.js +23 -0
  203. package/dist/server/compat/next/router.js +103 -0
  204. package/dist/server/compat/next/script.js +37 -0
  205. package/dist/server/compat/next/server-only.js +1 -0
  206. package/dist/server/compat/next/server.js +131 -0
  207. package/dist/server/compat/next/svgr.js +14 -0
  208. package/dist/server/compat/next/telemetry.js +10 -0
  209. package/dist/server/compat/next/usage.js +13 -0
  210. package/dist/server/compat/next/user-agent.js +12 -0
  211. package/dist/server/compat/next/web-vitals.js +35 -0
  212. package/dist/server/compat/react/action-state.js +11 -0
  213. package/dist/server/compat/react/client-lite.js +83 -0
  214. package/dist/server/compat/react/client.js +131 -0
  215. package/dist/server/compat/react/compiler-runtime.js +42 -0
  216. package/dist/server/compat/react/dom-client.js +106 -0
  217. package/dist/server/compat/react/dom-react-server.js +37 -0
  218. package/dist/server/compat/react/dom-server.js +40 -0
  219. package/dist/server/compat/react/dom.js +52 -0
  220. package/dist/server/compat/react/hooks-extra.js +12 -0
  221. package/dist/server/compat/react/internals.js +14 -0
  222. package/dist/server/compat/react/parity.js +11 -0
  223. package/dist/server/compat/react/preact.js +113 -0
  224. package/dist/server/compat/react/react-server.js +133 -0
  225. package/dist/server/compat/react/router-shim.js +8 -0
  226. package/dist/server/compat/react/server-component-use.js +14 -0
  227. package/dist/server/compat/react/server-inserted-html.js +14 -0
  228. package/dist/server/compat/react/server.js +194 -0
  229. package/dist/server/compat/react/style-values.js +10 -0
  230. package/dist/server/compat/react/use.js +10 -0
  231. package/dist/server/compat/react/view-transition.js +12 -0
  232. package/dist/server/generation.json +1 -0
  233. package/package.json +4 -1
  234. package/src/api/dynamic.tsx +2 -0
  235. package/src/api/server.ts +24 -6
  236. package/src/cli/adapters/vercel-warm.ts +315 -61
  237. package/src/cli/adapters/vercel.ts +348 -71
  238. package/src/cli/build.ts +58 -33
  239. package/src/cli/index.ts +23 -10
  240. package/src/cli/serve/entry.ts +21 -159
  241. package/src/cli/serve/immutable.ts +31 -0
  242. package/src/cli/serve/pipeline.ts +82 -84
  243. package/src/cli/start.ts +3 -1
  244. package/src/client/chunk-fold.ts +19 -6
  245. package/src/client/react-tier.ts +3 -2
  246. package/src/client/reference-stub.ts +21 -2
  247. package/src/compat/actions/client-plugin.ts +4 -2
  248. package/src/compat/actions/config.ts +6 -5
  249. package/src/compat/actions/extensions.ts +2 -3
  250. package/src/compat/aliases.ts +8 -1
  251. package/src/compat/bundler/config.ts +88 -0
  252. package/src/compat/bundler/optimize-package-imports.ts +86 -26
  253. package/src/compat/bundler/relay-transform.ts +15 -3
  254. package/src/compat/cache-control.ts +16 -8
  255. package/src/compat/css/modules.ts +18 -5
  256. package/src/compat/lifecycle/error-funnel.ts +1 -1
  257. package/src/compat/lifecycle/instrumentation.ts +117 -24
  258. package/src/compat/lifecycle/testmode.ts +3 -2
  259. package/src/compat/next/config-loader.ts +137 -13
  260. package/src/compat/next/font/runtime.ts +22 -2
  261. package/src/compat/next/og.ts +3 -3
  262. package/src/compat/next/usage.ts +3 -2
  263. package/src/compat/pages/api.ts +83 -14
  264. package/src/compat/pages/router.ts +30 -14
  265. package/src/compat/register/bundler.ts +3 -1
  266. package/src/compat/register/middleware.ts +1 -1
  267. package/src/compat/register/otel.ts +5 -9
  268. package/src/compat/register/render.ts +3 -1
  269. package/src/compat/register/use-cache.ts +3 -1
  270. package/src/compat/release.ts +46 -0
  271. package/src/compat/segment/serve.ts +1 -1
  272. package/src/compat/validation/validate.ts +10 -7
  273. package/src/config.ts +51 -7
  274. package/src/css/assets.ts +213 -0
  275. package/src/css/build.ts +174 -238
  276. package/src/dev/server.ts +27 -8
  277. package/src/extensions.ts +4 -0
  278. package/src/render/hooks.ts +13 -0
  279. package/src/render/renderer.ts +52 -32
  280. package/src/request/context.ts +9 -0
  281. package/src/resolve/dynamic.ts +3 -1
  282. package/src/resolve/imports.ts +12 -52
  283. package/src/resolve/package-json.ts +56 -0
  284. package/src/resolve/scan-facts.ts +65 -0
  285. package/src/routing/href.ts +10 -3
  286. package/src/routing/match.ts +287 -0
  287. package/src/routing/metadata-files.ts +19 -5
  288. package/src/routing/proxy-config.ts +137 -0
  289. package/src/routing/proxy.ts +35 -134
  290. package/src/routing/routes.ts +22 -281
  291. package/src/runtime/fingerprint.ts +23 -8
  292. package/src/runtime/load.ts +170 -0
  293. package/src/runtime/loader.ts +215 -43
  294. package/src/runtime/module-cache.ts +13 -0
  295. package/src/runtime/modules.ts +370 -81
  296. package/src/runtime/prebundle.ts +81 -0
  297. package/src/runtime/production.ts +391 -0
  298. package/src/runtime/release-graph.ts +334 -0
  299. package/src/runtime/vendor-build.ts +724 -13
  300. package/src/runtime/vendor.ts +16 -3
  301. package/src/types.ts +2 -0
  302. package/src/utils/fs.ts +89 -3
@@ -0,0 +1,1835 @@
1
+ // @bun
2
+ import {
3
+ contentType,
4
+ withForwardedHeaders
5
+ } from "./index-5hr4062s.js";
6
+ import {
7
+ DEFERRED_DYNAMIC_SIDECAR,
8
+ buildClientEntries,
9
+ buildClientEntry,
10
+ clientCacheKeyParts,
11
+ clientCacheStaticHash,
12
+ clientSourceHash,
13
+ deferredDynamicRefById,
14
+ prebuiltRuntimeDir,
15
+ registerDeferredDynamicRef
16
+ } from "./index-nyrba2kr.js";
17
+ import {
18
+ writeTypegen
19
+ } from "./index-wpfhfbs4.js";
20
+ import {
21
+ handleRouteModule
22
+ } from "./index-qpwsgt3a.js";
23
+ import {
24
+ assertNoServerActionsWithoutCompat,
25
+ materializeRouteFactsPaced,
26
+ routeFactsResolved,
27
+ routeFactsVersion,
28
+ scanRoutes,
29
+ setRouteFactsStore
30
+ } from "./index-8k7pfejn.js";
31
+ import {
32
+ clearDevRouteBundleKeys,
33
+ devClientModuleHref,
34
+ devClientReferenceGroups,
35
+ devClientReferenceModules,
36
+ devModuleGraph,
37
+ devRouteModuleLoaders,
38
+ devServerModuleHref,
39
+ drainPreplanBuilds,
40
+ importDevModule,
41
+ warmDevModulePipeline
42
+ } from "./index-1011cscr.js";
43
+ import {
44
+ getClientActionBundler
45
+ } from "./index-n4hxpng2.js";
46
+ import"./index-x3yn4ywm.js";
47
+ import {
48
+ cacheRoot,
49
+ deferServerRuntimePlugins,
50
+ installServerRuntimePlugins,
51
+ registerServerRuntime,
52
+ setDevWatcherFreshness
53
+ } from "./index-vvmmknm1.js";
54
+ import"./index-91x12ykq.js";
55
+ import {
56
+ clearMetadataFileCaches,
57
+ clientEntryName,
58
+ discoverStaticMetadataFiles,
59
+ errorLogTrace,
60
+ flushDevProfileLines,
61
+ formatProfileDuration,
62
+ internalErrorHtml,
63
+ metadataRouteHandlerModule,
64
+ recordDevProfileLine,
65
+ renderGlobalNotFoundResponse,
66
+ renderPageResponse,
67
+ staticMetadataCacheControl,
68
+ withDevReloadScript
69
+ } from "./index-3tf1xjsp.js";
70
+ import {
71
+ findLayouts,
72
+ matchRoute,
73
+ parseNavState,
74
+ selectRouteForRequest
75
+ } from "./index-jepjvcrf.js";
76
+ import {
77
+ applyProxyResponse,
78
+ createProxyRunner,
79
+ validateProxyFiles
80
+ } from "./index-kq8kpzye.js";
81
+ import {
82
+ serverBundleTargetForRuntime
83
+ } from "./index-3xbr4eyv.js";
84
+ import"./index-rn8dyr1f.js";
85
+ import {
86
+ buildClientReferenceCss,
87
+ buildGlobalCss,
88
+ buildRouteCss,
89
+ clearGlobalCssSourceCache,
90
+ isCssFile,
91
+ setGlobalCssSourceStore,
92
+ warmCssPipeline
93
+ } from "./index-2dv4y4wd.js";
94
+ import {
95
+ formatDuration
96
+ } from "./index-73z4esab.js";
97
+ import"./index-y2jr2n72.js";
98
+ import {
99
+ getFontExtensions,
100
+ nextCompatEnabled
101
+ } from "./index-web361b8.js";
102
+ import {
103
+ restartCacheEnabled
104
+ } from "./index-knp0s912.js";
105
+ import {
106
+ frameworkFingerprint
107
+ } from "./index-c0g2wf3z.js";
108
+ import {
109
+ escapeHtml
110
+ } from "./index-ye9hmsvf.js";
111
+ import {
112
+ setRequestRuntime
113
+ } from "./index-z88qv16t.js";
114
+ import"./index-fp8r0sqs.js";
115
+ import"./index-cjgqs13g.js";
116
+ import"./index-yhxkxghe.js";
117
+ import"./index-fkp000p1.js";
118
+ import"./index-p77b4kcx.js";
119
+ import {
120
+ ensureDir,
121
+ exactNameIndex,
122
+ hasExactName,
123
+ listFiles,
124
+ writeFileAtomic,
125
+ writeText
126
+ } from "./index-20ppawv7.js";
127
+ import {
128
+ markBoot
129
+ } from "./index-tq1f96v7.js";
130
+ import {
131
+ traceEnabled
132
+ } from "./index-vz0km5qk.js";
133
+ import {
134
+ abortUpstreamFetchOnDisconnect,
135
+ bootstrapCompat,
136
+ bootstrapCompatBoot
137
+ } from "./index-5gyr4emz.js";
138
+ import"./index-y36a0ybw.js";
139
+ import"./index-x93hv0sc.js";
140
+ import {
141
+ markErrorLogged
142
+ } from "./index-jcsjq3d1.js";
143
+ import"./index-tqn2qnnn.js";
144
+ import"./index-6kp9r0d9.js";
145
+ import {
146
+ ssrClientReference
147
+ } from "./index-ras0sdab.js";
148
+ import {
149
+ flushWorkUnit,
150
+ flushWorkUnitOnClose,
151
+ getWorkUnit,
152
+ runWithWorkUnit,
153
+ setPhase,
154
+ setWorkUnitRoute
155
+ } from "./index-grta8ap3.js";
156
+ import"./index-kresp2n8.js";
157
+ import"./index-e3a6yx84.js";
158
+ import"./index-z4z9zv3b.js";
159
+ import {
160
+ clearAppTreeResolutions,
161
+ clearResolverFsCache,
162
+ workspacePackageRoots
163
+ } from "./index-yz54pxrh.js";
164
+ import"./index-7wc9n8be.js";
165
+ import"./index-pym1cezq.js";
166
+ import {
167
+ finalizeResponse,
168
+ getAssetExtensions,
169
+ getBundlerExtensions,
170
+ getRequestExtensions,
171
+ getRouterProtocolExtensions,
172
+ reportRequestError,
173
+ runInitHooks,
174
+ runRequestWarmHooks,
175
+ withRouteRuntime
176
+ } from "./index-zqpqyg8p.js";
177
+ import"./index-qjj6gddn.js";
178
+ import"./index-4399bvd2.js";
179
+ import"./index-rt9qq1va.js";
180
+
181
+ // src/dev/server.ts
182
+ import { existsSync as existsSync2, readFileSync as readFileSync5, statSync as statSync2 } from "fs";
183
+ import { readFile as readFile3, readdir as readdir2, rm as rm2, stat as stat3, watch } from "fs/promises";
184
+ import path5 from "path";
185
+
186
+ // src/dev/restart/client-key.ts
187
+ import { readFileSync, writeFileSync } from "fs";
188
+ import { mkdir, readFile, stat } from "fs/promises";
189
+ import path from "path";
190
+ var INDEX_VERSION = 1;
191
+ var caches = new Map;
192
+ function keyCache(config) {
193
+ const file = path.join(config.outPath, "cache", "client", "keys.json");
194
+ const existing = caches.get(file);
195
+ if (existing)
196
+ return existing;
197
+ const created = { file, routes: readIndex(file), dirty: false, retries: 0 };
198
+ caches.set(file, created);
199
+ process.on("exit", () => {
200
+ if (!created.dirty)
201
+ return;
202
+ created.dirty = false;
203
+ try {
204
+ writeFileSync(created.file, serializeIndex(created.routes));
205
+ } catch {}
206
+ });
207
+ return created;
208
+ }
209
+ async function devClientCacheKey(config, route, nextCompat) {
210
+ if (!restartCacheEnabled())
211
+ return (await clientCacheKeyParts(route, nextCompat, config)).key;
212
+ const cache = keyCache(config);
213
+ const staticHash = clientCacheStaticHash(route, nextCompat, config);
214
+ const entry = cache.routes.get(route.id);
215
+ if (entry?.static === staticHash) {
216
+ const revalidated = await revalidate(entry.files);
217
+ if (revalidated) {
218
+ if (revalidated !== entry.files) {
219
+ cache.routes.set(route.id, { ...entry, files: revalidated });
220
+ persist(cache);
221
+ }
222
+ return entry.key;
223
+ }
224
+ }
225
+ const parts = await clientCacheKeyParts(route, nextCompat, config, staticHash);
226
+ cache.routes.set(route.id, {
227
+ static: parts.staticHash,
228
+ key: parts.key,
229
+ files: parts.sources.map(sourceEntry)
230
+ });
231
+ persist(cache);
232
+ return parts.key;
233
+ }
234
+ function sourceEntry(source) {
235
+ return [source.file, source.mtimeMs, source.size, source.hash];
236
+ }
237
+ async function revalidate(files) {
238
+ let moved = false;
239
+ const checked = await Promise.all(files.map(async (entry) => {
240
+ const [file, mtimeMs, size, hash] = entry;
241
+ const stats = await stat(file).catch(() => {
242
+ return;
243
+ });
244
+ if (!stats)
245
+ return;
246
+ if (stats.mtimeMs === mtimeMs && stats.size === size)
247
+ return entry;
248
+ const source = await readFile(file, "utf8").catch(() => {
249
+ return;
250
+ });
251
+ if (source === undefined || clientSourceHash(source) !== hash)
252
+ return;
253
+ moved = true;
254
+ return [file, stats.mtimeMs, stats.size, hash];
255
+ }));
256
+ if (checked.some((entry) => entry === undefined))
257
+ return;
258
+ return moved ? checked : files;
259
+ }
260
+ function persist(cache) {
261
+ cache.dirty = true;
262
+ if (cache.flush)
263
+ return;
264
+ cache.flush = setTimeout(async () => {
265
+ cache.flush = undefined;
266
+ if (!cache.dirty)
267
+ return;
268
+ const contents = serializeIndex(cache.routes);
269
+ try {
270
+ await mkdir(path.dirname(cache.file), { recursive: true });
271
+ await writeFileAtomic(cache.file, contents);
272
+ cache.dirty = false;
273
+ } catch {
274
+ if (++cache.retries < 3)
275
+ persist(cache);
276
+ }
277
+ }, 50);
278
+ cache.flush.unref?.();
279
+ }
280
+ function readIndex(file) {
281
+ const routes = new Map;
282
+ let parsed;
283
+ try {
284
+ parsed = JSON.parse(readFileSync(file, "utf8"));
285
+ } catch {
286
+ return routes;
287
+ }
288
+ if (parsed?.version !== INDEX_VERSION)
289
+ return routes;
290
+ for (const [id, entry] of Object.entries(parsed.routes ?? {})) {
291
+ if (entry?.key && entry.static && Array.isArray(entry.files))
292
+ routes.set(id, entry);
293
+ }
294
+ return routes;
295
+ }
296
+ function serializeIndex(routes) {
297
+ return JSON.stringify({
298
+ version: INDEX_VERSION,
299
+ routes: Object.fromEntries(routes)
300
+ });
301
+ }
302
+
303
+ // src/dev/client-chunk-store.ts
304
+ import { createHash } from "crypto";
305
+ import { link, mkdir as mkdir2, readFile as readFile2, readdir, rm, stat as stat2, unlink } from "fs/promises";
306
+ import path2 from "path";
307
+ function clientChunkStoreDir(outPath) {
308
+ return path2.join(outPath, "cache", "client-store");
309
+ }
310
+ function contentHash(data) {
311
+ return createHash("sha1").update(data).digest("hex");
312
+ }
313
+ async function contentAddressDir(dir, storeDir) {
314
+ await mkdir2(storeDir, { recursive: true });
315
+ const files = await listFiles(dir);
316
+ await Promise.all(files.map((file) => contentAddressFile(file, storeDir)));
317
+ }
318
+ async function contentAddressFile(file, storeDir) {
319
+ const data = await readFile2(file);
320
+ const storePath = path2.join(storeDir, `${contentHash(data)}${path2.extname(file)}`);
321
+ if (!await pathExists(storePath)) {
322
+ try {
323
+ await link(file, storePath);
324
+ return;
325
+ } catch {
326
+ await copyFileFallback(file, storePath);
327
+ return;
328
+ }
329
+ }
330
+ try {
331
+ await unlink(file);
332
+ await link(storePath, file);
333
+ } catch {}
334
+ }
335
+ async function copyFileFallback(file, storePath) {
336
+ try {
337
+ const data = await readFile2(file);
338
+ await Bun.write(storePath, data);
339
+ } catch {}
340
+ }
341
+ async function pathExists(target) {
342
+ return stat2(target).then(() => true).catch(() => false);
343
+ }
344
+ async function sweepClientChunkStore(storeDir) {
345
+ let entries;
346
+ try {
347
+ entries = await readdir(storeDir);
348
+ } catch {
349
+ return;
350
+ }
351
+ await Promise.allSettled(entries.map(async (entry) => {
352
+ const full = path2.join(storeDir, entry);
353
+ const info = await stat2(full).catch(() => null);
354
+ if (info && info.nlink <= 1)
355
+ await rm(full, { force: true });
356
+ }));
357
+ }
358
+
359
+ // src/dev/restart/route-facts.ts
360
+ import { mkdirSync, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
361
+ import path3 from "path";
362
+
363
+ // src/dev/restart/record.ts
364
+ import { readFileSync as readFileSync2, statSync } from "fs";
365
+ var hash = (value) => Bun.hash(value).toString(36);
366
+ function recordCacheKey(config, version) {
367
+ try {
368
+ const shape = JSON.stringify(config, (_key, value) => typeof value === "function" ? "[fn]" : value);
369
+ return hash(`${version}
370
+ ${frameworkFingerprint(cacheRoot(config.outPath))}
371
+ ${shape}`);
372
+ } catch {
373
+ return;
374
+ }
375
+ }
376
+ function lazyRecordCacheKey(config, version) {
377
+ let key;
378
+ let computed = false;
379
+ return () => {
380
+ if (!computed) {
381
+ computed = true;
382
+ key = recordCacheKey(config, version);
383
+ }
384
+ return key;
385
+ };
386
+ }
387
+ function sourceEntries(files) {
388
+ const entries = [];
389
+ for (const file of files) {
390
+ const entry = sourceEntry2(file);
391
+ if (!entry)
392
+ return;
393
+ entries.push(entry);
394
+ }
395
+ return entries;
396
+ }
397
+ function sourceEntry2(file) {
398
+ try {
399
+ const source = readFileSync2(file, "utf8");
400
+ const info = statSync(file, { throwIfNoEntry: false });
401
+ if (!info)
402
+ return;
403
+ return [file, info.mtimeMs, info.size, hash(source)];
404
+ } catch {
405
+ return;
406
+ }
407
+ }
408
+ function revalidate2(files) {
409
+ let moved = false;
410
+ const checked = [];
411
+ for (const entry of files) {
412
+ const [file, mtimeMs, size, contentHash2] = entry;
413
+ const info = statSync(file, { throwIfNoEntry: false });
414
+ if (!info)
415
+ return;
416
+ if (info.mtimeMs === mtimeMs && info.size === size) {
417
+ checked.push(entry);
418
+ continue;
419
+ }
420
+ let source;
421
+ try {
422
+ source = readFileSync2(file, "utf8");
423
+ } catch {
424
+ return;
425
+ }
426
+ if (hash(source) !== contentHash2)
427
+ return;
428
+ moved = true;
429
+ checked.push([file, info.mtimeMs, info.size, contentHash2]);
430
+ }
431
+ return moved ? checked : files;
432
+ }
433
+
434
+ // src/dev/restart/route-facts.ts
435
+ var RECORD_VERSION = 1;
436
+ function installRouteFactsCache(config) {
437
+ if (!restartCacheEnabled())
438
+ return;
439
+ if (process.env.PNEXT_DEV_FACTS_CACHE === "0")
440
+ return;
441
+ const cache = {
442
+ dir: path3.join(config.outPath, "cache", "route-facts"),
443
+ key: lazyRecordCacheKey(config, RECORD_VERSION),
444
+ written: new Set
445
+ };
446
+ setRouteFactsStore(createStore(cache));
447
+ }
448
+ function recordFile(cache, routeId) {
449
+ return path3.join(cache.dir, `${hash(routeId)}.json`);
450
+ }
451
+ function createStore(cache) {
452
+ return {
453
+ load(routeId) {
454
+ const record = readRecord(cache, routeId);
455
+ if (!record) {
456
+ stats.misses += 1;
457
+ return;
458
+ }
459
+ const revalidated = revalidate2(record.files);
460
+ if (!revalidated) {
461
+ stats.misses += 1;
462
+ return;
463
+ }
464
+ stats.hits += 1;
465
+ if (revalidated !== record.files) {
466
+ cache.written.delete(routeId);
467
+ write(cache, routeId, revalidated, record.facts);
468
+ }
469
+ return record.facts;
470
+ },
471
+ save(routeId, facts) {
472
+ const files = factsSources(facts);
473
+ if (!files)
474
+ return;
475
+ write(cache, routeId, files, facts);
476
+ }
477
+ };
478
+ }
479
+ function readRecord(cache, routeId) {
480
+ let parsed;
481
+ try {
482
+ parsed = JSON.parse(readFileSync3(recordFile(cache, routeId), "utf8"));
483
+ } catch {
484
+ return;
485
+ }
486
+ if (parsed?.version !== RECORD_VERSION || parsed.key !== cache.key())
487
+ return;
488
+ if (!parsed.facts || !Array.isArray(parsed.files))
489
+ return;
490
+ return parsed;
491
+ }
492
+ function write(cache, routeId, files, facts) {
493
+ const key = cache.key();
494
+ if (!key || cache.written.has(routeId))
495
+ return;
496
+ cache.written.add(routeId);
497
+ const contents = JSON.stringify({
498
+ version: RECORD_VERSION,
499
+ key,
500
+ files,
501
+ facts
502
+ });
503
+ try {
504
+ mkdirSync(cache.dir, { recursive: true });
505
+ writeFileSync2(recordFile(cache, routeId), contents);
506
+ } catch {}
507
+ }
508
+ function factsSources(facts) {
509
+ const entries = [];
510
+ for (const file of facts.sourceFiles) {
511
+ const entry = sourceEntry2(file);
512
+ if (!entry)
513
+ return;
514
+ entries.push(entry);
515
+ }
516
+ return entries;
517
+ }
518
+ var stats = { hits: 0, misses: 0 };
519
+ if (traceEnabled("server")) {
520
+ process.on("exit", () => console.log(`route-facts hits=${stats.hits} misses=${stats.misses}`));
521
+ }
522
+
523
+ // src/dev/restart/global-css.ts
524
+ import { mkdirSync as mkdirSync2, existsSync, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
525
+ import path4 from "path";
526
+ var RECORD_VERSION2 = 1;
527
+ function installGlobalCssCache(config) {
528
+ if (!restartCacheEnabled())
529
+ return;
530
+ if (process.env.PNEXT_DEV_GLOBAL_CSS_CACHE === "0")
531
+ return;
532
+ const dir = path4.join(config.outPath, "cache", "global-css");
533
+ setGlobalCssSourceStore(createStore2(dir, lazyRecordCacheKey(config, RECORD_VERSION2)));
534
+ }
535
+ function createStore2(dir, cacheKey) {
536
+ const written = new Map;
537
+ const recordFile2 = (walkKey) => path4.join(dir, `${hash(walkKey)}.json`);
538
+ return {
539
+ load(walkKey) {
540
+ const key = cacheKey();
541
+ const record = key ? readRecord2(recordFile2(walkKey), key) : undefined;
542
+ if (!key || !record) {
543
+ stats2.misses += 1;
544
+ return;
545
+ }
546
+ if (record.missing.some((file) => existsSync(file))) {
547
+ stats2.misses += 1;
548
+ return;
549
+ }
550
+ const revalidated = revalidate2(record.files);
551
+ if (!revalidated) {
552
+ stats2.misses += 1;
553
+ return;
554
+ }
555
+ stats2.hits += 1;
556
+ if (revalidated !== record.files) {
557
+ write2(recordFile2(walkKey), key, written, walkKey, revalidated, record.missing, record.sources);
558
+ }
559
+ return record.sources;
560
+ },
561
+ save(walkKey, sources, visited, missing) {
562
+ const key = cacheKey();
563
+ if (!key)
564
+ return;
565
+ const files = sourceEntries(visited);
566
+ if (!files)
567
+ return;
568
+ write2(recordFile2(walkKey), key, written, walkKey, files, missing, sources);
569
+ }
570
+ };
571
+ }
572
+ function readRecord2(file, key) {
573
+ let parsed;
574
+ try {
575
+ parsed = JSON.parse(readFileSync4(file, "utf8"));
576
+ } catch {
577
+ return;
578
+ }
579
+ if (parsed?.version !== RECORD_VERSION2 || parsed.key !== key)
580
+ return;
581
+ if (!Array.isArray(parsed.files) || !Array.isArray(parsed.sources))
582
+ return;
583
+ if (!Array.isArray(parsed.missing))
584
+ return;
585
+ return parsed;
586
+ }
587
+ function write2(file, key, written, walkKey, files, missing, sources) {
588
+ const contents = JSON.stringify({
589
+ version: RECORD_VERSION2,
590
+ key,
591
+ files,
592
+ missing,
593
+ sources
594
+ });
595
+ if (written.get(walkKey) === contents)
596
+ return;
597
+ written.set(walkKey, contents);
598
+ try {
599
+ mkdirSync2(path4.dirname(file), { recursive: true });
600
+ writeFileSync3(file, contents);
601
+ } catch {}
602
+ }
603
+ var stats2 = { hits: 0, misses: 0 };
604
+ if (traceEnabled("server")) {
605
+ process.on("exit", () => console.log(`global-css hits=${stats2.hits} misses=${stats2.misses}`));
606
+ }
607
+
608
+ // src/dev/server.ts
609
+ import { malformedUrlResponse, repeatedSlashRedirect, trailingSlashRedirect } from "../../../src/routing/href.ts";
610
+ import { runWithCacheScope } from "../../../src/request/cache.ts";
611
+ var DEV_IDLE_TIMEOUT_SECONDS = 60;
612
+ var DEV_IDLE_TIMEOUT_MS = DEV_IDLE_TIMEOUT_SECONDS * 1000;
613
+ var DEV_PAGE_STALL_WARNING_MS = 20000;
614
+ var clientBuilds = new Map;
615
+ var clientChunks = new Map;
616
+ var clientBuildStopWaiters = new Set;
617
+ function failInFlightClientBuilds(reason) {
618
+ const err = new Error(reason);
619
+ for (const reject of clientBuildStopWaiters)
620
+ reject(err);
621
+ clientBuildStopWaiters.clear();
622
+ clientBuilds.clear();
623
+ }
624
+ var indexedClientDirs = new Set;
625
+ var routeLayoutFiles = new Map;
626
+ var assetBuilds = new Map;
627
+ var routeCacheKeys = new Map;
628
+ var appKey = (outPath, key) => `${outPath}\x00${key}`;
629
+ function clearAppKeyed(map, outPath) {
630
+ for (const key of map.keys())
631
+ if (key.startsWith(`${outPath}\x00`))
632
+ map.delete(key);
633
+ }
634
+ var compiledRoutes = new Set;
635
+ function invalidateDevCaches(config, changed, structural) {
636
+ devModuleGraph(config).invalidate(changed);
637
+ if (structural) {
638
+ clearResolverFsCache();
639
+ clearAppTreeResolutions();
640
+ clearMetadataFileCaches();
641
+ routeLayoutFiles.clear();
642
+ }
643
+ clearGlobalCssSourceCache();
644
+ clearDevRouteBundleKeys();
645
+ clearAppKeyed(assetBuilds, config.outPath);
646
+ clearAppKeyed(routeCacheKeys, config.outPath);
647
+ indexedClientDirs.clear();
648
+ compiledRoutes.clear();
649
+ evictStaleClientCaches(config.outPath);
650
+ }
651
+ async function evictStaleClientCaches(outPath) {
652
+ const keep = Number(process.env.PNEXT_DEV_CLIENT_CACHE_KEEP || 32);
653
+ if (!Number.isFinite(keep) || keep <= 0)
654
+ return;
655
+ const clientRoot = path5.join(outPath, "cache", "client");
656
+ try {
657
+ const entries = await readdir2(clientRoot);
658
+ if (entries.length <= keep)
659
+ return;
660
+ const dated = await Promise.all(entries.map(async (entry) => {
661
+ const full = path5.join(clientRoot, entry);
662
+ const info = await stat3(full).catch(() => null);
663
+ return { full, mtime: info?.mtimeMs ?? 0 };
664
+ }));
665
+ dated.sort((a, b) => b.mtime - a.mtime);
666
+ await Promise.allSettled(dated.slice(keep).map((entry) => rm2(entry.full, { recursive: true, force: true })));
667
+ await sweepClientChunkStore(clientChunkStoreDir(outPath));
668
+ } catch {}
669
+ }
670
+ async function removeLeakedStaleCaches(outPath) {
671
+ try {
672
+ const entries = await readdir2(outPath);
673
+ await Promise.allSettled(entries.filter((entry) => entry.startsWith(".cache-stale-")).map((entry) => rm2(path5.join(outPath, entry), { recursive: true, force: true })));
674
+ } catch {}
675
+ }
676
+ async function startDevServer(options) {
677
+ const { config, port, hostname } = options;
678
+ const bootTime = Date.now();
679
+ warmCssPipeline(config, { dev: true });
680
+ markBoot("boot:css-warm");
681
+ await bootstrapCompatBoot(config);
682
+ markBoot("boot:compat");
683
+ deferServerRuntimePlugins();
684
+ registerServerRuntime(config);
685
+ runInitHooks(config);
686
+ removeLeakedStaleCaches(config.outPath);
687
+ evictStaleClientCaches(config.outPath);
688
+ installRouteFactsCache(config);
689
+ installGlobalCssCache(config);
690
+ markBoot("boot:registry");
691
+ let routes = await scanRoutes(config.appPath, config.workspaceRoot);
692
+ setDevClientRoutes(config, routes);
693
+ markBoot("boot:scanRoutes");
694
+ await validateProxyFiles(config);
695
+ let proxyRunner = createProxyRunner(config);
696
+ const exactNames = exactNameIndex(config.root);
697
+ markBoot("boot:proxy");
698
+ let devImportVersion = String(Date.now());
699
+ if (restartCacheEnabled())
700
+ proxyRunner.warm({ dev: true, devImportVersion });
701
+ markBoot("boot:proxy-warm");
702
+ publishRuntime();
703
+ const clients = new Set;
704
+ let generation = 0;
705
+ let watcher;
706
+ let inFlight = 0;
707
+ function publishRuntime() {
708
+ setRequestRuntime({ config, routes, dev: true, devImportVersion });
709
+ }
710
+ const TYPEGEN_MAX_WAIT_MS = 3000;
711
+ async function typegenPause() {
712
+ if (process.env.PNEXT_DEV_TYPEGEN_PACE === "0")
713
+ return;
714
+ const deadline = performance.now() + TYPEGEN_MAX_WAIT_MS;
715
+ do {
716
+ await new Promise((resolve) => setTimeout(resolve, inFlight > 0 ? 25 : 0));
717
+ } while (inFlight > 0 && performance.now() < deadline);
718
+ }
719
+ async function typegenInBackground() {
720
+ const generation2 = routes;
721
+ try {
722
+ await writeTypegen(config, await materializeRouteFactsPaced(generation2, typegenPause));
723
+ } catch (error) {
724
+ if (generation2 === routes)
725
+ logDevPreloadError("typegen", error);
726
+ }
727
+ if (generation2 === routes)
728
+ syncWatchRoots();
729
+ }
730
+ async function reload(change) {
731
+ const structural = change.renamed && change.files.some((file) => !existsSync2(file) || !devModuleGraph(config).knows(file));
732
+ invalidateDevCaches(config, change.files, structural);
733
+ if (isCssOnlyChange(change.files)) {
734
+ generation++;
735
+ broadcast(clients, "css-update");
736
+ return;
737
+ }
738
+ if (structural) {
739
+ routes = await scanRoutes(config.appPath, config.workspaceRoot);
740
+ setDevClientRoutes(config, routes);
741
+ }
742
+ await validateProxyFiles(config);
743
+ proxyRunner = createProxyRunner(config);
744
+ devImportVersion = `${Date.now()}`;
745
+ proxyRunner.warm({ dev: true, devImportVersion });
746
+ publishRuntime();
747
+ typegenInBackground();
748
+ watchedFactsVersion = -1;
749
+ syncWatchRoots();
750
+ generation++;
751
+ broadcast(clients, "reload");
752
+ }
753
+ function eagerInvalidate(file) {
754
+ devModuleGraph(config).invalidate([file]);
755
+ clearDevRouteBundleKeys();
756
+ clearAppKeyed(routeCacheKeys, config.outPath);
757
+ }
758
+ let watchedFactsVersion = -1;
759
+ function syncWatchRoots() {
760
+ if (watchedFactsVersion === routeFactsVersion())
761
+ return;
762
+ watchedFactsVersion = routeFactsVersion();
763
+ watcher = refreshWatcher(config, routes, watcher, reload, bootTime, eagerInvalidate);
764
+ }
765
+ syncWatchRoots();
766
+ markBoot("boot:watcher");
767
+ const server = Bun.serve({
768
+ hostname,
769
+ port,
770
+ idleTimeout: DEV_IDLE_TIMEOUT_SECONDS,
771
+ fetch(request, server2) {
772
+ inFlight++;
773
+ return runWithWorkUnit("render", () => handleDevRequest(request, server2)).catch((error) => devLastResortResponse(error, request)).finally(() => {
774
+ inFlight--;
775
+ });
776
+ },
777
+ error: (error) => devLastResortError(error)
778
+ });
779
+ async function handleDevRequest(request, server2) {
780
+ const prologueStart = performance.now();
781
+ await bootstrapCompat(config, { serve: true });
782
+ installServerRuntimePlugins();
783
+ const unit = getWorkUnit();
784
+ const badRequest = malformedUrlResponse(request);
785
+ if (badRequest)
786
+ return badRequest;
787
+ request = withForwardedHeaders(request, server2);
788
+ let url = new URL(request.url);
789
+ const slashRedirect = repeatedSlashRedirect(url);
790
+ if (slashRedirect)
791
+ return slashRedirect;
792
+ const profile = devRequestProfile(request, url);
793
+ if (profile)
794
+ logDevProfile(profile, "prologue (bootstrap/headers/url)", prologueStart);
795
+ let pageLog = startDevPageStallTimer(pendingDevPageLoadLog(routes, request, url));
796
+ let afterResponse;
797
+ const logAbort = () => {
798
+ const pending = pageLog;
799
+ pageLog = undefined;
800
+ logDevPageAbort(pending);
801
+ };
802
+ request.signal.addEventListener("abort", logAbort, { once: true });
803
+ const finish = async (response) => {
804
+ const pending = pageLog;
805
+ pageLog = undefined;
806
+ request.signal.removeEventListener("abort", logAbort);
807
+ const finalized = await profileDevStep(profile, "finalize response", () => finalizeResponse(response, { method: request.method, url: new URL(request.url), headers: request.headers }, { routeKind: unit?.routeKind ?? "html", routeMode: unit?.routeMode, dev: true }));
808
+ const logged = logDevPageResponse(pending, finalized);
809
+ const tasks = afterResponse;
810
+ afterResponse = undefined;
811
+ setTimeout(() => {
812
+ tasks?.();
813
+ syncWatchRoots();
814
+ }, 0);
815
+ if (profile)
816
+ flushDevProfileLines();
817
+ abortUpstreamFetchOnDisconnect(logged.body, request.signal);
818
+ return flushWorkUnitOnClose(logged, unit, request.signal);
819
+ };
820
+ try {
821
+ const canonicalRedirect = trailingSlashRedirect(config, url);
822
+ if (canonicalRedirect)
823
+ return finish(canonicalRedirect);
824
+ const initialPrefetchResponse = maybeDevPagePrefetchResponse(routes, url.pathname, request);
825
+ if (initialPrefetchResponse)
826
+ return finish(initialPrefetchResponse);
827
+ let proxyResponse;
828
+ const proxyResult = await profileDevStep(profile, "proxy", () => proxyRunner(request, { dev: true, devImportVersion }));
829
+ if (proxyResult instanceof Response)
830
+ return finish(proxyResult);
831
+ if (proxyResult) {
832
+ request = proxyResult.request;
833
+ proxyResponse = proxyResult.response;
834
+ url = new URL(request.url);
835
+ const rewrittenLog = pendingDevPageLoadLog(routes, request, url, pageLog?.start);
836
+ clearDevPageStallTimer(pageLog);
837
+ pageLog = startDevPageStallTimer(rewrittenLog);
838
+ const rewrittenPrefetchResponse = maybeDevPagePrefetchResponse(routes, url.pathname, request);
839
+ if (rewrittenPrefetchResponse)
840
+ return finish(applyProxyResponse(rewrittenPrefetchResponse, proxyResponse));
841
+ }
842
+ if (url.pathname === "/__pnext/events") {
843
+ server2.timeout(request, 0);
844
+ return finish(eventStream(clients, generation));
845
+ }
846
+ const assetResponse = await profileDevStep(profile, "built asset lookup", () => maybeBuiltAsset(config, routes, url.pathname));
847
+ if (assetResponse)
848
+ return finish(applyProxyResponse(assetResponse, proxyResponse));
849
+ const clientChunkResponse = await profileDevStep(profile, "client chunk lookup", () => maybeDevClientChunk(config, url.pathname));
850
+ if (clientChunkResponse)
851
+ return finish(applyProxyResponse(clientChunkResponse, proxyResponse));
852
+ const runtimeResponse = maybePrebuiltRuntime(config, url.pathname);
853
+ if (runtimeResponse)
854
+ return finish(applyProxyResponse(runtimeResponse, proxyResponse));
855
+ const dynChunkMatch = /^\/__pnext\/client-dyn\/([A-Za-z0-9-]+)\.js$/.exec(url.pathname);
856
+ if (dynChunkMatch?.[1]) {
857
+ const id = dynChunkMatch[1];
858
+ const file = await profileDevStep(profile, `client dyn chunk ${id}`, () => devDynamicEntryFile(config, routes, id, url.searchParams.get("r")));
859
+ if (!file)
860
+ return finish(applyProxyResponse(new Response("not found", { status: 404 }), proxyResponse));
861
+ return finish(applyProxyResponse(devResponse(await readFile3(file), "text/javascript; charset=utf-8"), proxyResponse));
862
+ }
863
+ const clientMatch = /^\/__pnext\/client\/(.+)\.js$/.exec(url.pathname);
864
+ if (clientMatch?.[1]) {
865
+ const route = routes.find((item) => item.id === clientMatch[1] && (item.client || item.clientReferences.length > 0 || item.needsRouterEntry));
866
+ if (!route)
867
+ return finish(applyProxyResponse(new Response("not found", { status: 404 }), proxyResponse));
868
+ const file = await profileDevStep(profile, `client build ${route.route}`, () => buildDevClient(config, route));
869
+ return finish(applyProxyResponse(devResponse(await profileDevStep(profile, "client read", () => readFile3(file)), "text/javascript; charset=utf-8"), proxyResponse));
870
+ }
871
+ const metadataFile = await profileDevStep(profile, "static metadata file", () => maybeStaticMetadataFile(config, url));
872
+ if (metadataFile) {
873
+ setWorkUnitRoute("static-asset");
874
+ return finish(applyProxyResponse(metadataFile, proxyResponse));
875
+ }
876
+ const staticResponse = await profileDevStep(profile, "static lookup", () => maybeStaticFile(config.publicPath, url.pathname, exactNames));
877
+ if (staticResponse) {
878
+ setWorkUnitRoute("static-asset", "static");
879
+ return finish(applyProxyResponse(staticResponse, proxyResponse));
880
+ }
881
+ if (getAssetExtensions().staticAssetPublicPrefixes().some((prefix) => url.pathname.startsWith(prefix))) {
882
+ const emitted = await maybeStaticFile(path5.join(config.outPath, "public"), url.pathname, exactNames);
883
+ if (emitted) {
884
+ setWorkUnitRoute("static-asset", "static");
885
+ return finish(applyProxyResponse(emitted, proxyResponse));
886
+ }
887
+ }
888
+ const staticAssetPathname = getNextStaticAssetPathname(url.pathname, config.basePath, config.assetPrefix);
889
+ if (staticAssetPathname) {
890
+ const outPublicStatic = await maybeStaticFile(path5.join(config.outPath, "public"), staticAssetPathname, exactNames);
891
+ if (outPublicStatic) {
892
+ setWorkUnitRoute("static-asset", "static");
893
+ return finish(applyProxyResponse(outPublicStatic, proxyResponse));
894
+ }
895
+ const staticChunk = maybeStaticClientChunk(config, staticAssetPathname);
896
+ if (staticChunk) {
897
+ setWorkUnitRoute("static-asset", "static");
898
+ return finish(applyProxyResponse(staticChunk, proxyResponse));
899
+ }
900
+ setWorkUnitRoute("static-asset", "static");
901
+ return finish(applyProxyResponse(new Response("Not Found", {
902
+ status: 404,
903
+ headers: {
904
+ "cache-control": "private, no-cache, no-store, max-age=0, must-revalidate",
905
+ "content-type": "text/plain;charset=utf-8"
906
+ }
907
+ }), proxyResponse));
908
+ }
909
+ const canonicalRequest = request;
910
+ const canonicalUrl = new URL(request.url);
911
+ for (const [index, interceptor] of getRequestExtensions().interceptors.entries()) {
912
+ const result = await profileDevStep(profile, `interceptor ${interceptor.name || index}`, () => interceptor(request, { config }));
913
+ if (result instanceof Response)
914
+ return finish(applyProxyResponse(result, proxyResponse));
915
+ if (result) {
916
+ request = result.request;
917
+ url = new URL(request.url);
918
+ }
919
+ }
920
+ const nav = parseNavState(request);
921
+ const matched = profileDevSyncStep(profile, "match route", () => selectRouteForRequest(routes, url.pathname, nav));
922
+ if (!matched) {
923
+ return finish(applyProxyResponse(await renderGlobalNotFoundResponse({
924
+ config,
925
+ url,
926
+ request: canonicalRequest,
927
+ dev: true,
928
+ devImportVersion
929
+ }), proxyResponse));
930
+ }
931
+ if (matched.route.kind === "handler") {
932
+ setWorkUnitRoute("route-handler");
933
+ setPhase("handler");
934
+ return finish(applyProxyResponse(await profileDevStep(profile, `handler ${matched.route.route}`, () => handleRoute(config, matched.route, canonicalRequest, matched.params, devImportVersion)), proxyResponse));
935
+ }
936
+ setWorkUnitRoute("html", matched.route.mode === "static" ? "static" : "dynamic");
937
+ assertNoServerActionsWithoutCompat([matched.route], nextCompatEnabled(config), config.root);
938
+ pageRequestsSeen++;
939
+ noteDevCompileStart(matched.route);
940
+ noteDevRouteServed(config, matched.route);
941
+ const eagerClient = !deferClientStage();
942
+ if (eagerClient)
943
+ preloadDevClient(config, matched.route, profile);
944
+ const preloadAssets = () => {
945
+ preloadDevPageAssets(config, matched.route, profile);
946
+ if (!eagerClient)
947
+ preloadDevClient(config, matched.route, profile);
948
+ };
949
+ afterResponse = preloadAssets;
950
+ if (!deferAssetPreload()) {
951
+ afterResponse = undefined;
952
+ preloadAssets();
953
+ }
954
+ const layoutFiles = profileDevSyncStep(profile, "find layouts", () => devLayoutFiles(config, matched.route.file));
955
+ let loaders;
956
+ preloadDevClientReferences(config, matched.route, profile);
957
+ try {
958
+ loaders = await profileDevStep(profile, `route module loaders ${matched.route.route}`, () => devRouteModuleLoaders(config, matched.route, layoutFiles));
959
+ } catch (error) {
960
+ logDevRouteLoaderFallback(matched.route, error);
961
+ }
962
+ preloadDevFonts(config, profile);
963
+ return finish(applyProxyResponse(await profileDevStep(profile, `render page ${matched.route.route}`, () => withRouteRuntime(matched.route.segmentConfig?.runtime, () => renderPageResponse({
964
+ config,
965
+ route: matched.route,
966
+ params: matched.params,
967
+ url: canonicalUrl,
968
+ request: request.method.toUpperCase() === "POST" ? new Request(canonicalRequest.url, { headers: canonicalRequest.headers }) : canonicalRequest,
969
+ dev: true,
970
+ devImportVersion,
971
+ layoutFiles,
972
+ moduleLoader: loaders?.moduleLoader,
973
+ clientModuleLoader: loaders?.clientModuleLoader,
974
+ ...nav ? {
975
+ nav: {
976
+ soft: true,
977
+ state: nav,
978
+ childrenPath: matched.childrenPath,
979
+ targetPath: matched.targetPath
980
+ }
981
+ } : {}
982
+ }))), proxyResponse));
983
+ } catch (error) {
984
+ request.signal.removeEventListener("abort", logAbort);
985
+ await reportRequestError(error, { method: request.method, url: request.url, headers: request.headers }, { phase: unit?.phase, routeKind: unit?.routeKind });
986
+ logDevPageError(pageLog);
987
+ flushWorkUnit(unit);
988
+ return devLastResortResponse(error, request);
989
+ }
990
+ }
991
+ const warmup = options.warm ? afterReady(() => warmDev(config, routes)).catch((error) => logDevPreloadError("warm", error)) : undefined;
992
+ Promise.resolve(warmup).then(typegenInBackground);
993
+ return Object.assign(server, { warmup });
994
+ }
995
+ function devLastResortResponse(error, request) {
996
+ let route = request.url;
997
+ try {
998
+ route = new URL(request.url).pathname;
999
+ } catch {}
1000
+ return devLastResortError(error, route, request.url, request);
1001
+ }
1002
+ function devLastResortError(error, route = "(unknown)", url = route, request) {
1003
+ const resolved = error instanceof Error ? error : new Error(String(error));
1004
+ if (markErrorLogged(resolved))
1005
+ console.error(errorLogTrace(resolved));
1006
+ let html;
1007
+ try {
1008
+ html = internalErrorHtml({
1009
+ error: resolved,
1010
+ route,
1011
+ url,
1012
+ digest: resolved.digest
1013
+ });
1014
+ } catch {
1015
+ html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>pnext error</title></head><body><h1>pnext could not render this request</h1><pre>${escapeHtml(resolved.stack ?? resolved.message)}</pre></body></html>`;
1016
+ }
1017
+ return new Response(withDevReloadScript(html, request), {
1018
+ status: 500,
1019
+ headers: { "content-type": "text/html; charset=utf-8" }
1020
+ });
1021
+ }
1022
+ function afterReady(task) {
1023
+ return new Promise((resolve) => setTimeout(() => resolve(task()), 0));
1024
+ }
1025
+ async function warmDev(config, routes) {
1026
+ await bootstrapCompat(config, { serve: true });
1027
+ installServerRuntimePlugins();
1028
+ runRequestWarmHooks(config);
1029
+ await warmDevModulePipeline(config);
1030
+ await warmDevRoutes(config, routes);
1031
+ }
1032
+ var WARM_ROUTES = 3;
1033
+ var pageRequestsSeen = 0;
1034
+ async function warmDevRoutes(config, routes) {
1035
+ const wanted = readDevRouteHistory(config).map((id) => routes.find((route) => route.id === id && route.kind === "page")).filter((route) => Boolean(route)).slice(0, WARM_ROUTES);
1036
+ if (wanted.length === 0)
1037
+ return;
1038
+ if (deferAssetPreload() && pageRequestsSeen > 0)
1039
+ return;
1040
+ await buildDevAsset(config, "/assets/global.css", () => buildGlobalCss(config, { dev: true }));
1041
+ for (const route of wanted) {
1042
+ if (pageRequestsSeen > 0)
1043
+ return;
1044
+ await warmDevRoute(config, route).catch(() => {
1045
+ return;
1046
+ });
1047
+ }
1048
+ }
1049
+ async function warmDevRoute(config, route) {
1050
+ noteDevCompileStart(route);
1051
+ const start = performance.now();
1052
+ const layoutFiles = devLayoutFiles(config, route.file);
1053
+ const hasClient = route.client || route.clientReferences.length > 0;
1054
+ await Promise.allSettled([
1055
+ route.cssImports.length > 0 ? buildDevAsset(config, `/assets/${route.id}.css`, () => buildRouteCss(config, route, { dev: true })) : Promise.resolve(),
1056
+ devRouteModuleLoaders(config, route, layoutFiles),
1057
+ hasClient ? buildDevClient(config, route) : Promise.resolve(),
1058
+ warmDevClientReferences(config, route),
1059
+ warmDevPageModule(config, route)
1060
+ ]);
1061
+ noteDevCompileDone(route, performance.now() - start);
1062
+ }
1063
+ async function warmDevPageModule(config, route) {
1064
+ if (process.env.PNEXT_DEV_WARM_PAGE_MODULE === "0" || !route.client || route.kind !== "page") {
1065
+ return;
1066
+ }
1067
+ const href = await devServerModuleHref(config, route.file, undefined, {
1068
+ conditionTarget: serverBundleTargetForRuntime(route.segmentConfig?.runtime)
1069
+ });
1070
+ await drainPreplanBuilds();
1071
+ await import(href);
1072
+ }
1073
+ async function warmDevClientReferences(config, route) {
1074
+ if (process.env.PNEXT_DEV_WARM_CLIENT_REFS === "0")
1075
+ return;
1076
+ const evaluate = process.env.PNEXT_DEV_PRELOAD_REF_IMPORTS !== "0";
1077
+ const target = serverBundleTargetForRuntime(route.segmentConfig?.runtime);
1078
+ const { batched, perModule } = devClientReferenceGroups(config, route);
1079
+ await Promise.allSettled([
1080
+ batched.length > 0 ? devClientReferenceModules(config, route, { evaluate }).catch((error) => {
1081
+ console.debug(`PNext dev warm failed for the client references of ${route.route}; falling back to per-module loading.`, error);
1082
+ throw error;
1083
+ }) : Promise.resolve(),
1084
+ ...perModule.map(async (file) => {
1085
+ const href = await devClientModuleHref(config, file, undefined, target);
1086
+ if (evaluate) {
1087
+ try {
1088
+ await importDevModule(href, { warm: true });
1089
+ } catch (error) {
1090
+ console.debug(`PNext dev warm evaluation failed for client reference ${file}.`, error);
1091
+ throw error;
1092
+ }
1093
+ }
1094
+ })
1095
+ ]);
1096
+ }
1097
+ var HISTORY_LIMIT = 8;
1098
+ var history;
1099
+ var historyWrite;
1100
+ function historyFile(config) {
1101
+ return path5.join(cacheRoot(config.outPath), "warm.json");
1102
+ }
1103
+ function readDevRouteHistory(config) {
1104
+ if (history)
1105
+ return history;
1106
+ try {
1107
+ const parsed = JSON.parse(readFileSync5(historyFile(config), "utf8"));
1108
+ history = Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
1109
+ } catch {
1110
+ history = [];
1111
+ }
1112
+ return history;
1113
+ }
1114
+ function noteDevRouteServed(config, route) {
1115
+ if (route.kind !== "page")
1116
+ return;
1117
+ const seen = readDevRouteHistory(config);
1118
+ if (seen[0] === route.id)
1119
+ return;
1120
+ history = [route.id, ...seen.filter((id) => id !== route.id)].slice(0, HISTORY_LIMIT);
1121
+ if (historyWrite)
1122
+ return;
1123
+ historyWrite = setTimeout(() => {
1124
+ historyWrite = undefined;
1125
+ writeText(historyFile(config), JSON.stringify(history ?? [])).catch(() => {
1126
+ return;
1127
+ });
1128
+ }, 500);
1129
+ historyWrite.unref?.();
1130
+ }
1131
+ function logDevRouteLoaderFallback(route, error) {
1132
+ console.error([
1133
+ `PNext dev route bundle failed for ${route.route}; falling back to per-module loading.`,
1134
+ error instanceof Error ? error.stack ?? error.message : String(error)
1135
+ ].join(`
1136
+ `));
1137
+ }
1138
+ function devRequestProfile(request, url) {
1139
+ if (!traceEnabled("server"))
1140
+ return;
1141
+ return {
1142
+ label: `${request.method} ${url.pathname}`,
1143
+ start: performance.now()
1144
+ };
1145
+ }
1146
+ async function profileDevStep(profile, label, task) {
1147
+ if (!profile)
1148
+ return task();
1149
+ const start = performance.now();
1150
+ try {
1151
+ return await task();
1152
+ } finally {
1153
+ logDevProfile(profile, label, start);
1154
+ }
1155
+ }
1156
+ function profileDevSyncStep(profile, label, task) {
1157
+ if (!profile)
1158
+ return task();
1159
+ const start = performance.now();
1160
+ try {
1161
+ return task();
1162
+ } finally {
1163
+ logDevProfile(profile, label, start);
1164
+ }
1165
+ }
1166
+ function logDevProfile(profile, label, start) {
1167
+ const end = performance.now();
1168
+ recordDevProfileLine(`dev-profile ${profile.label} ${label} in ${formatProfileDuration(end - start)} (@${formatProfileDuration(start - profile.start)}..+${formatProfileDuration(end - profile.start)})`);
1169
+ }
1170
+ async function handleRoute(config, route, request, params, devImportVersion) {
1171
+ const routeHref = await devServerModuleHref(config, route.file, devImportVersion, {
1172
+ conditionTarget: serverBundleTargetForRuntime(route.segmentConfig?.runtime)
1173
+ });
1174
+ await drainPreplanBuilds();
1175
+ const imported = await import(routeHref);
1176
+ const module = metadataRouteHandlerModule(imported, route) ?? imported;
1177
+ return withRouteRuntime(route.segmentConfig?.runtime, () => runWithCacheScope(() => handleRouteModule(module, request, params, { routeFile: route.file })));
1178
+ }
1179
+ function routeClientCacheKey(config, route) {
1180
+ const existing = routeCacheKeys.get(appKey(config.outPath, route.id));
1181
+ if (existing)
1182
+ return existing;
1183
+ const key = devClientCacheKey(config, route, Boolean(config.compat?.next));
1184
+ routeCacheKeys.set(appKey(config.outPath, route.id), key);
1185
+ return key;
1186
+ }
1187
+ function preloadDevClient(config, route, profile) {
1188
+ if (!route.client && route.clientReferences.length === 0 && !route.needsRouterEntry)
1189
+ return;
1190
+ profileDevStep(profile, `client preload ${route.route}`, () => buildDevClient(config, route)).catch((error) => logDevPreloadError(`client build for ${route.route}`, error)).finally(() => {
1191
+ if (profile)
1192
+ flushDevProfileLines();
1193
+ });
1194
+ }
1195
+ function preloadDevClientReferences(config, route, profile) {
1196
+ if (process.env.PNEXT_DEV_PRELOAD_REFS === "0")
1197
+ return;
1198
+ if (route.clientReferences.length > 0) {
1199
+ profileDevStep(profile, `client references preload ${route.route}`, () => warmDevClientReferences(config, route)).catch((error) => logDevPreloadError(`client references for ${route.route}`, error));
1200
+ }
1201
+ profileDevStep(profile, `page module preload ${route.route}`, () => warmDevPageModule(config, route)).then(() => preloadDevFonts(config, profile)).catch((error) => logDevPreloadError(`page module for ${route.route}`, error));
1202
+ }
1203
+ function preloadDevFonts(config, profile) {
1204
+ return profileDevStep(profile, "font prewarm", () => getFontExtensions().prewarmFontAssets(config, { dev: true })).catch((error) => logDevPreloadError("font prewarm", error));
1205
+ }
1206
+ function deferClientStage() {
1207
+ return process.env.PNEXT_DEV_CLIENT_STAGE !== "eager";
1208
+ }
1209
+ function deferAssetPreload() {
1210
+ return process.env.PNEXT_DEV_ASSET_PRELOAD !== "eager";
1211
+ }
1212
+ function preloadDevPageAssets(config, route, profile) {
1213
+ profileDevStep(profile, "asset preload /assets/global.css", () => buildDevAsset(config, "/assets/global.css", () => buildGlobalCss(config, { dev: true }))).catch((error) => logDevPreloadError("global css build", error));
1214
+ if (route.cssImports.length === 0)
1215
+ return;
1216
+ profileDevStep(profile, `asset preload /assets/${route.id}.css`, () => buildDevAsset(config, `/assets/${route.id}.css`, () => buildRouteCss(config, route, { dev: true }))).catch((error) => logDevPreloadError(`route css build for ${route.route}`, error));
1217
+ }
1218
+ function devLayoutFiles(config, routeFile) {
1219
+ const cached = routeLayoutFiles.get(routeFile);
1220
+ if (cached)
1221
+ return cached;
1222
+ const files = findLayouts(config.appPath, routeFile).filter((file) => existsSync2(file));
1223
+ routeLayoutFiles.set(routeFile, files);
1224
+ return files;
1225
+ }
1226
+ function logDevPreloadError(label, error) {
1227
+ console.error([
1228
+ `PNext dev preload failed for ${label}.`,
1229
+ error instanceof Error ? error.stack ?? error.message : String(error)
1230
+ ].join(`
1231
+ `));
1232
+ }
1233
+ function findDeferredDynamicReference(routes, id) {
1234
+ for (const route of routes) {
1235
+ const reference = route.clientReferences.find((item) => item.id === id && item.dynamic && !ssrClientReference(item));
1236
+ if (reference)
1237
+ return { route, reference };
1238
+ }
1239
+ const registered = deferredDynamicRefById(id);
1240
+ if (registered)
1241
+ return {
1242
+ route: routes.find((item) => item.id === registered.routeId),
1243
+ reference: { id, ...registered }
1244
+ };
1245
+ return;
1246
+ }
1247
+ async function devDynamicEntryFile(config, routes, id, routeId) {
1248
+ const scoped = routeId ? routes.find((route2) => route2.id === routeId) : undefined;
1249
+ const route = scoped ?? findDeferredDynamicReference(routes, id)?.route;
1250
+ if (!route)
1251
+ return;
1252
+ const outDir = path5.dirname(await buildDevClient(config, route));
1253
+ const file = path5.join(outDir, `${id}.js`);
1254
+ return isInside(outDir, file) && existsSync2(file) ? file : undefined;
1255
+ }
1256
+ async function loadDeferredDynamicSidecar(outDir) {
1257
+ try {
1258
+ const parsed = JSON.parse(await readFile3(path5.join(outDir, DEFERRED_DYNAMIC_SIDECAR), "utf8"));
1259
+ for (const [id, ref] of Object.entries(parsed)) {
1260
+ if (ref?.file && ref.exportName)
1261
+ registerDeferredDynamicRef(id, ref);
1262
+ }
1263
+ } catch {}
1264
+ }
1265
+ var devClientRouteSets = new Map;
1266
+ function setDevClientRoutes(config, routes) {
1267
+ devClientRouteSets.set(config.outPath, routes);
1268
+ }
1269
+ function devClientBatchRoutes(config, route) {
1270
+ const all = devClientRouteSets.get(config.outPath);
1271
+ if (!all?.some((candidate) => candidate.id === route.id))
1272
+ return [route];
1273
+ return all.filter((candidate) => candidate.client || candidate.clientReferences.length > 0 || candidate.needsRouterEntry);
1274
+ }
1275
+ async function buildDevClient(config, route) {
1276
+ const batchRoutes = devClientBatchRoutes(config, route);
1277
+ const cacheKeys = await Promise.all(batchRoutes.map((entry) => routeClientCacheKey(config, entry)));
1278
+ const cacheKey = batchRoutes.length === 1 ? cacheKeys[0] : `batch-${clientSourceHash([...cacheKeys].sort().join(`
1279
+ `))}`;
1280
+ const outDir = path5.join(config.outPath, "cache", "client", cacheKey);
1281
+ const outFile = path5.join(outDir, `${clientEntryName(route)}.js`);
1282
+ const existing = clientBuilds.get(outDir);
1283
+ if (existing)
1284
+ return existing;
1285
+ if (existsSync2(outFile)) {
1286
+ if (!indexedClientDirs.has(outDir)) {
1287
+ await indexClientChunks(outDir);
1288
+ await loadDeferredDynamicSidecar(outDir);
1289
+ indexedClientDirs.add(outDir);
1290
+ }
1291
+ return outFile;
1292
+ }
1293
+ const inner = (async () => {
1294
+ await ensureDir(outDir);
1295
+ if (nextCompatEnabled(config))
1296
+ await getClientActionBundler()?.ensureArmed();
1297
+ const file = batchRoutes.length === 1 ? await buildClientEntry({ config, route, outDir, dev: true }) : await (async () => {
1298
+ await buildClientEntries({
1299
+ config,
1300
+ routes: batchRoutes,
1301
+ outDir,
1302
+ dev: true,
1303
+ hasServerActions: true
1304
+ });
1305
+ return outFile;
1306
+ })();
1307
+ await contentAddressDir(outDir, clientChunkStoreDir(config.outPath));
1308
+ await indexClientChunks(outDir);
1309
+ indexedClientDirs.add(outDir);
1310
+ return file;
1311
+ })();
1312
+ let unregister = () => {
1313
+ return;
1314
+ };
1315
+ const stopSignal = new Promise((_, reject) => {
1316
+ clientBuildStopWaiters.add(reject);
1317
+ unregister = () => void clientBuildStopWaiters.delete(reject);
1318
+ });
1319
+ inner.catch(() => {
1320
+ return;
1321
+ });
1322
+ const build = Promise.race([inner, stopSignal]).finally(() => {
1323
+ unregister();
1324
+ clientBuilds.delete(outDir);
1325
+ });
1326
+ clientBuilds.set(outDir, build);
1327
+ return build;
1328
+ }
1329
+ async function maybeDevClientChunk(config, pathname) {
1330
+ const chunkMatch = /^\/__pnext\/client\/chunks\/(.+\.js)$/.exec(pathname);
1331
+ if (!chunkMatch?.[1])
1332
+ return null;
1333
+ const file = await resolveDevClientChunk(config, chunkMatch[1]);
1334
+ return file ? devChunkResponse(await readFile3(file)) : null;
1335
+ }
1336
+ async function resolveDevClientChunk(config, name) {
1337
+ const indexed = clientChunks.get(name);
1338
+ if (indexed && existsSync2(indexed))
1339
+ return indexed;
1340
+ await Promise.allSettled([...clientBuilds.values()]);
1341
+ const settled = clientChunks.get(name);
1342
+ if (settled && existsSync2(settled))
1343
+ return settled;
1344
+ const clientRoot = path5.join(config.outPath, "cache", "client");
1345
+ for (const generation of await readdir2(clientRoot).catch(() => [])) {
1346
+ const chunksDir = path5.join(clientRoot, generation, "chunks");
1347
+ const file = path5.join(chunksDir, name);
1348
+ if (!isInside(chunksDir, file) || !existsSync2(file))
1349
+ continue;
1350
+ clientChunks.set(name, file);
1351
+ return file;
1352
+ }
1353
+ return;
1354
+ }
1355
+ function maybePrebuiltRuntime(config, pathname) {
1356
+ const match = /^\/__pnext\/runtime\/([0-9a-f]+)\/(.+\.js)$/.exec(pathname);
1357
+ if (!match?.[1] || !match[2])
1358
+ return null;
1359
+ const dir = prebuiltRuntimeDir(config, match[1]);
1360
+ const file = path5.join(dir, match[2]);
1361
+ if (!isInside(dir, file) || !existsSync2(file))
1362
+ return null;
1363
+ return devChunkResponse(readFileSync5(file));
1364
+ }
1365
+ function maybeStaticClientChunk(config, staticAssetPathname) {
1366
+ const match = /^\/_next\/static\/chunks\/([^/]+\.js)$/.exec(staticAssetPathname);
1367
+ if (!match?.[1])
1368
+ return null;
1369
+ const chunk = getBundlerExtensions().staticClientChunks(config).find((item) => item.name === match[1]);
1370
+ return chunk ? devChunkResponse(chunk.contents) : null;
1371
+ }
1372
+ async function indexClientChunks(outDir) {
1373
+ const chunksDir = path5.join(outDir, "chunks");
1374
+ if (!existsSync2(chunksDir))
1375
+ return;
1376
+ for (const file of await listFiles(chunksDir)) {
1377
+ if (file.endsWith(".js"))
1378
+ clientChunks.set(path5.basename(file), file);
1379
+ }
1380
+ }
1381
+ async function maybeStaticMetadataFile(config, url) {
1382
+ const target = url.pathname.replace(/^\/+/, "");
1383
+ const file = discoverStaticMetadataFiles(config.appPath).find((item) => item.outputPath === target);
1384
+ if (!file || !existsSync2(file.file))
1385
+ return null;
1386
+ return new Response(await readFile3(file.file), {
1387
+ headers: { "content-type": file.contentType, "cache-control": staticMetadataCacheControl }
1388
+ });
1389
+ }
1390
+ async function maybeStaticFile(publicPath, pathname, exactNames) {
1391
+ const filePath = path5.join(publicPath, pathname.replace(/^\/+/, ""));
1392
+ if (!isInside(publicPath, filePath) || !existsSync2(filePath))
1393
+ return null;
1394
+ if (exactNames && !hasExactName(exactNames, publicPath, path5.relative(publicPath, filePath))) {
1395
+ return null;
1396
+ }
1397
+ const fileStat = await stat3(filePath);
1398
+ if (!fileStat.isFile())
1399
+ return null;
1400
+ return devResponse(await readFile3(filePath), contentType(filePath));
1401
+ }
1402
+ function getNextStaticAssetPathname(pathname, basePath, assetPrefix) {
1403
+ if (pathname.startsWith("/_next/static/"))
1404
+ return pathname;
1405
+ const normalizedBasePath = normalizePathPrefix(basePath);
1406
+ if (normalizedBasePath && pathname.startsWith(`${normalizedBasePath}/_next/static/`)) {
1407
+ return pathname.slice(normalizedBasePath.length);
1408
+ }
1409
+ const normalizedAssetPrefix = normalizePathPrefix(assetPrefix);
1410
+ if (normalizedAssetPrefix && pathname.startsWith(`${normalizedAssetPrefix}/_next/static/`)) {
1411
+ return pathname.slice(normalizedAssetPrefix.length);
1412
+ }
1413
+ return null;
1414
+ }
1415
+ function normalizePathPrefix(prefix) {
1416
+ if (!prefix)
1417
+ return null;
1418
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(prefix))
1419
+ return null;
1420
+ const normalized = `/${prefix.replace(/^\/+|\/+$/g, "")}`;
1421
+ if (normalized === "/")
1422
+ return null;
1423
+ return normalized;
1424
+ }
1425
+ function findClientReferenceCss(routes, id) {
1426
+ return routes.flatMap((route) => route.clientReferences).find((reference) => reference.id === id && reference.cssImports?.length);
1427
+ }
1428
+ function builtAssetPathname(config, pathname) {
1429
+ if (pathname.startsWith("/assets/"))
1430
+ return pathname;
1431
+ const alias = /^\/_next\/static\/([^/]+)$/.exec(pathname);
1432
+ return alias?.[1] && nextCompatEnabled(config) ? `/assets/${alias[1]}` : null;
1433
+ }
1434
+ async function maybeBuiltAsset(config, routes, requestPathname) {
1435
+ const pathname = builtAssetPathname(config, requestPathname);
1436
+ if (!pathname)
1437
+ return null;
1438
+ if (pathname === "/assets/global.css") {
1439
+ await buildDevAsset(config, pathname, () => buildGlobalCss(config, { dev: true }));
1440
+ } else {
1441
+ const cssMatch = /^\/assets\/(.+)\.css$/.exec(pathname);
1442
+ const route = cssMatch?.[1] ? routes.find((item) => item.id === cssMatch[1]) : undefined;
1443
+ const reference = !route && cssMatch?.[1] ? findClientReferenceCss(routes.filter(routeFactsResolved), cssMatch[1]) ?? findClientReferenceCss(routes, cssMatch[1]) : undefined;
1444
+ if (route) {
1445
+ await buildDevAsset(config, pathname, () => buildRouteCss(config, route, { dev: true }));
1446
+ } else if (reference) {
1447
+ await buildDevAsset(config, pathname, () => buildClientReferenceCss(config, reference, { dev: true }));
1448
+ }
1449
+ }
1450
+ const outPath = config.outPath;
1451
+ const filePath = path5.join(outPath, "cache", pathname.replace(/^\/+/, ""));
1452
+ if (!isInside(path5.join(outPath, "cache"), filePath) || !existsSync2(filePath))
1453
+ return null;
1454
+ const fileStat = await stat3(filePath);
1455
+ if (!fileStat.isFile())
1456
+ return null;
1457
+ return new Response(await readFile3(filePath), {
1458
+ headers: { "content-type": contentType(filePath) }
1459
+ });
1460
+ }
1461
+ function buildDevAsset(config, pathname, build) {
1462
+ const key = appKey(config.outPath, pathname);
1463
+ const existing = assetBuilds.get(key);
1464
+ if (existing)
1465
+ return existing;
1466
+ const next = build().catch((error) => {
1467
+ assetBuilds.delete(key);
1468
+ throw error;
1469
+ });
1470
+ assetBuilds.set(key, next);
1471
+ return next;
1472
+ }
1473
+ function maybeDevPagePrefetchResponse(routes, pathname, request) {
1474
+ if (!isDevPagePrefetchRequest(request))
1475
+ return null;
1476
+ const matched = matchRoute(routes, pathname);
1477
+ if (matched?.route.kind !== "page")
1478
+ return null;
1479
+ return devPagePrefetchResponse();
1480
+ }
1481
+ function isDevPagePrefetchRequest(request) {
1482
+ if (request.method.toUpperCase() !== "GET")
1483
+ return false;
1484
+ return headerHasPrefetchToken(request.headers.get("sec-purpose")) || headerHasPrefetchToken(request.headers.get("purpose")) || getRouterProtocolExtensions().prefetchRequestHeaders().some((header) => request.headers.get(header) === "1");
1485
+ }
1486
+ function headerHasPrefetchToken(value) {
1487
+ return Boolean(value?.split(/[;,\s]+/).some((token) => token.toLowerCase() === "prefetch"));
1488
+ }
1489
+ function devPagePrefetchResponse() {
1490
+ return new Response(null, {
1491
+ status: 204,
1492
+ headers: {
1493
+ "cache-control": "no-store",
1494
+ "x-pnext-dev-prefetch": "skipped"
1495
+ }
1496
+ });
1497
+ }
1498
+ function pendingDevPageLoadLog(routes, request, url, start = performance.now()) {
1499
+ const matched = matchRoute(routes, url.pathname);
1500
+ if (matched?.route.kind !== "page")
1501
+ return;
1502
+ return {
1503
+ method: request.method,
1504
+ pathname: url.pathname,
1505
+ route: matched.route.route,
1506
+ start
1507
+ };
1508
+ }
1509
+ function startDevPageStallTimer(pending) {
1510
+ if (!pending)
1511
+ return pending;
1512
+ const delay = Math.max(0, DEV_PAGE_STALL_WARNING_MS - (performance.now() - pending.start));
1513
+ pending.stallTimer = setTimeout(() => {
1514
+ console.warn(formatDevPageStallWarning({
1515
+ method: pending.method,
1516
+ pathname: pending.pathname,
1517
+ route: pending.route,
1518
+ elapsedMs: performance.now() - pending.start
1519
+ }));
1520
+ }, delay);
1521
+ pending.stallTimer.unref?.();
1522
+ return pending;
1523
+ }
1524
+ function clearDevPageStallTimer(pending) {
1525
+ if (!pending?.stallTimer)
1526
+ return;
1527
+ clearTimeout(pending.stallTimer);
1528
+ pending.stallTimer = undefined;
1529
+ }
1530
+ function formatDevPageStallWarning(entry) {
1531
+ const route = entry.route === entry.pathname ? "" : dim(`(${entry.route})`);
1532
+ return [
1533
+ yellow("\u26A0"),
1534
+ dim("page"),
1535
+ dim(entry.method),
1536
+ cyan(entry.pathname),
1537
+ route,
1538
+ yellow("still rendering"),
1539
+ dim("after"),
1540
+ durationLabel(entry.elapsedMs),
1541
+ dim("- no response yet")
1542
+ ].filter(Boolean).join(" ");
1543
+ }
1544
+ function devPageAbortNote(durationMs) {
1545
+ return durationMs >= DEV_IDLE_TIMEOUT_MS ? "dev server idle timeout" : undefined;
1546
+ }
1547
+ function logDevPageResponse(pending, response) {
1548
+ if (!pending)
1549
+ return response;
1550
+ clearDevPageStallTimer(pending);
1551
+ logDevPageLoad({
1552
+ method: pending.method,
1553
+ pathname: pending.pathname,
1554
+ route: pending.route,
1555
+ status: response.status,
1556
+ durationMs: performance.now() - pending.start
1557
+ });
1558
+ return response;
1559
+ }
1560
+ function logDevPageError(pending) {
1561
+ if (!pending)
1562
+ return;
1563
+ clearDevPageStallTimer(pending);
1564
+ logDevPageLoad({
1565
+ method: pending.method,
1566
+ pathname: pending.pathname,
1567
+ route: pending.route,
1568
+ status: 500,
1569
+ durationMs: performance.now() - pending.start
1570
+ });
1571
+ }
1572
+ function logDevPageAbort(pending) {
1573
+ if (!pending)
1574
+ return;
1575
+ clearDevPageStallTimer(pending);
1576
+ const durationMs = performance.now() - pending.start;
1577
+ logDevPageLoad({
1578
+ method: pending.method,
1579
+ pathname: pending.pathname,
1580
+ route: pending.route,
1581
+ status: 499,
1582
+ durationMs,
1583
+ note: devPageAbortNote(durationMs)
1584
+ });
1585
+ }
1586
+ function noteDevCompileStart(route) {
1587
+ if (compiledRoutes.has(route.file))
1588
+ return;
1589
+ compiledRoutes.add(route.file);
1590
+ console.log(`${cyan("\u25CB")} ${dim("Compiling")} ${cyan(route.route)} ${dim("...")}`);
1591
+ }
1592
+ function noteDevCompileDone(route, durationMs) {
1593
+ console.log(`${green("\u2713")} ${dim("Compiled")} ${cyan(route.route)} ${dim("in")} ${durationLabel(durationMs)}`);
1594
+ }
1595
+ function logDevPageLoad(entry) {
1596
+ console.log(formatDevPageLoadLog(entry));
1597
+ }
1598
+ function formatDevPageLoadLog(entry) {
1599
+ const route = entry.route === entry.pathname ? "" : dim(`(${entry.route})`);
1600
+ return [
1601
+ dim("page"),
1602
+ dim(entry.method),
1603
+ cyan(entry.pathname),
1604
+ route,
1605
+ statusLabel(entry.status),
1606
+ dim("in"),
1607
+ durationLabel(entry.durationMs),
1608
+ entry.note ? yellow(`(${entry.note})`) : ""
1609
+ ].filter(Boolean).join(" ");
1610
+ }
1611
+ function statusLabel(status) {
1612
+ const label = String(status);
1613
+ if (status >= 500)
1614
+ return red(label);
1615
+ if (status >= 400)
1616
+ return yellow(label);
1617
+ if (status >= 300)
1618
+ return cyan(label);
1619
+ return green(label);
1620
+ }
1621
+ function durationLabel(durationMs) {
1622
+ const label = formatDuration(durationMs);
1623
+ if (durationMs >= 1000)
1624
+ return yellow(label);
1625
+ if (durationMs >= 250)
1626
+ return cyan(label);
1627
+ return green(label);
1628
+ }
1629
+ function dim(value) {
1630
+ return color(2, 22, value);
1631
+ }
1632
+ function red(value) {
1633
+ return color(31, 39, value);
1634
+ }
1635
+ function yellow(value) {
1636
+ return color(33, 39, value);
1637
+ }
1638
+ function green(value) {
1639
+ return color(32, 39, value);
1640
+ }
1641
+ function cyan(value) {
1642
+ return color(36, 39, value);
1643
+ }
1644
+ function color(open, close, value) {
1645
+ if (!process.stdout.isTTY)
1646
+ return value;
1647
+ return `\x1B[${open}m${value}\x1B[${close}m`;
1648
+ }
1649
+ function devResponse(body, contentType2) {
1650
+ return new Response(body, {
1651
+ headers: {
1652
+ "content-type": contentType2,
1653
+ "cache-control": "no-store"
1654
+ }
1655
+ });
1656
+ }
1657
+ function devChunkResponse(body) {
1658
+ return new Response(body, {
1659
+ headers: {
1660
+ "content-type": "text/javascript; charset=utf-8",
1661
+ "cache-control": "public, max-age=31536000, immutable"
1662
+ }
1663
+ });
1664
+ }
1665
+ function isInside(root, file) {
1666
+ const relative = path5.relative(root, file);
1667
+ return relative === "" || !relative.startsWith("..") && !path5.isAbsolute(relative);
1668
+ }
1669
+ function refreshWatcher(config, routes, current, onChange, bootTime, onEvent) {
1670
+ const roots = devWatchRoots(config, routes);
1671
+ const rootsKey = roots.join("\x00");
1672
+ if (current?.rootsKey === rootsKey)
1673
+ return current;
1674
+ current?.stop();
1675
+ return watchRoots(roots, rootsKey, config.outPath, onChange, bootTime, onEvent);
1676
+ }
1677
+ function devWatchRoots(config, routes) {
1678
+ const packageRoots = workspacePackageRoots(config.workspaceRoot);
1679
+ const roots = new Set([config.appPath]);
1680
+ for (const route of routes.filter(routeFactsResolved)) {
1681
+ for (const file of route.sourceFiles) {
1682
+ if (isInside(config.appPath, file))
1683
+ continue;
1684
+ const packageRoot = packageRoots.find((root) => isInside(root, file));
1685
+ if (packageRoot)
1686
+ roots.add(packageWatchRoot(packageRoot, file));
1687
+ else {
1688
+ const projectRoot = projectWatchRoot(config.root, file);
1689
+ if (projectRoot)
1690
+ roots.add(projectRoot);
1691
+ }
1692
+ }
1693
+ }
1694
+ return [...roots].sort();
1695
+ }
1696
+ function projectWatchRoot(root, file) {
1697
+ if (!isInside(root, file))
1698
+ return;
1699
+ const [segment, ...rest] = path5.relative(root, file).split(path5.sep);
1700
+ if (!segment || rest.length === 0)
1701
+ return;
1702
+ if (segment === "node_modules" || segment.startsWith("."))
1703
+ return;
1704
+ return path5.join(root, segment);
1705
+ }
1706
+ function packageWatchRoot(packageRoot, file) {
1707
+ const relative = path5.relative(packageRoot, file);
1708
+ const [firstSegment] = relative.split(path5.sep);
1709
+ if (!firstSegment || firstSegment === ".." || path5.isAbsolute(relative))
1710
+ return packageRoot;
1711
+ return path5.join(packageRoot, firstSegment);
1712
+ }
1713
+ function isCssOnlyChange(files) {
1714
+ return files.length > 0 && files.every((file) => isCssFile(file) && !/\.module\.[^.]+$/.test(file) && existsSync2(file));
1715
+ }
1716
+ var recursiveWatchBroken = false;
1717
+ function watchRoots(roots, rootsKey, outPath, onChange, bootTime, onEvent) {
1718
+ const controller = new AbortController;
1719
+ let pending;
1720
+ let running = false;
1721
+ let batch = { files: [], renamed: false };
1722
+ async function flush() {
1723
+ if (running || batch.files.length === 0)
1724
+ return;
1725
+ const change = batch;
1726
+ batch = { files: [], renamed: false };
1727
+ running = true;
1728
+ try {
1729
+ await onChange(change);
1730
+ } finally {
1731
+ running = false;
1732
+ }
1733
+ if (batch.files.length > 0)
1734
+ await flush();
1735
+ }
1736
+ function schedule(file, renamed) {
1737
+ if (predatesBoot(file, bootTime))
1738
+ return;
1739
+ onEvent(file);
1740
+ batch.files.push(file);
1741
+ batch.renamed ||= renamed;
1742
+ if (pending)
1743
+ clearTimeout(pending);
1744
+ pending = setTimeout(() => {
1745
+ pending = undefined;
1746
+ flush();
1747
+ }, isCssOnlyChange(batch.files) ? 4 : 40);
1748
+ }
1749
+ for (const root of roots) {
1750
+ watchRoot(root, controller.signal, schedule, () => {
1751
+ recursiveWatchBroken = true;
1752
+ setDevWatcherFreshness(outPath, false);
1753
+ });
1754
+ }
1755
+ if (!recursiveWatchBroken)
1756
+ setDevWatcherFreshness(outPath, true);
1757
+ return {
1758
+ rootsKey,
1759
+ stop() {
1760
+ if (pending)
1761
+ clearTimeout(pending);
1762
+ controller.abort();
1763
+ }
1764
+ };
1765
+ }
1766
+ function predatesBoot(file, bootTime) {
1767
+ const info = statSync2(file, { throwIfNoEntry: false });
1768
+ return Boolean(info?.isFile() && info.mtimeMs <= bootTime);
1769
+ }
1770
+ var ignoredWatchSegment = /(?:^|[\\/])(?:node_modules|\.[^\\/]+)(?:[\\/]|$)/;
1771
+ function isIgnoredWatchPath(relativeFile) {
1772
+ return ignoredWatchSegment.test(relativeFile);
1773
+ }
1774
+ async function watchRoot(root, signal, onChange, onBroken) {
1775
+ try {
1776
+ const watcher = watch(root, { recursive: true, signal });
1777
+ for await (const event of watcher) {
1778
+ if (!event.filename)
1779
+ onChange(root, true);
1780
+ else if (!ignoredWatchSegment.test(event.filename))
1781
+ onChange(path5.resolve(root, event.filename), event.eventType === "rename");
1782
+ }
1783
+ } catch (error) {
1784
+ if (signal.aborted || error instanceof Error && error.name === "AbortError")
1785
+ return;
1786
+ onBroken();
1787
+ }
1788
+ }
1789
+ function eventStream(clients, generation) {
1790
+ let client;
1791
+ const stream = new ReadableStream({
1792
+ start(controller) {
1793
+ client = { controller };
1794
+ clients.add(client);
1795
+ controller.enqueue(new TextEncoder().encode(`event: ready
1796
+ data: ${generation}
1797
+
1798
+ `));
1799
+ },
1800
+ cancel() {
1801
+ if (client)
1802
+ clients.delete(client);
1803
+ }
1804
+ });
1805
+ return new Response(stream, {
1806
+ headers: {
1807
+ "content-type": "text/event-stream",
1808
+ "cache-control": "no-cache",
1809
+ connection: "keep-alive"
1810
+ }
1811
+ });
1812
+ }
1813
+ function broadcast(clients, event) {
1814
+ const payload = new TextEncoder().encode(`event: ${event}
1815
+ data: ${Date.now()}
1816
+
1817
+ `);
1818
+ for (const client of clients) {
1819
+ try {
1820
+ client.controller.enqueue(payload);
1821
+ } catch {
1822
+ clients.delete(client);
1823
+ }
1824
+ }
1825
+ }
1826
+ export {
1827
+ devLastResortError,
1828
+ devPageAbortNote,
1829
+ failInFlightClientBuilds,
1830
+ formatDevPageLoadLog,
1831
+ formatDevPageStallWarning,
1832
+ isDevPagePrefetchRequest,
1833
+ isIgnoredWatchPath,
1834
+ startDevServer
1835
+ };